From 450ed9bd8893fc67f2a3a768b589275579ad94a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 18:04:15 +0000 Subject: [PATCH 1/3] Move host.rs's and lower.rs's test modules to their own files, under the asset policy's 512 KiB limit The check job fails on main: crates/victory-gpu/src/host.rs (528,954 bytes) and crates/victory-shader/src/emit/lower.rs (535,588 bytes) are over the asset policy's 512 KiB limit (#1342). Only #[cfg(test)] modules move, verbatim apart from losing one level of indentation; module names and paths are unchanged, no non-test code changes. - host.rs: its eight test modules (tests, relay_tests, grouped_tests, late_tests, trail, spare, batch, queue2_tests) move to host/.rs, the layout profile.rs and profile/tests.rs already use. 492,495 bytes. - lower.rs: mod tests moves to emit/lower_tests.rs, declared with #[path = "lower_tests.rs"] as in #1322. 512,559 bytes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015kFDn6faAxnJwPKPwiCnj1 --- crates/victory-gpu/src/host.rs | 795 +----------------- crates/victory-gpu/src/host/batch.rs | 106 +++ crates/victory-gpu/src/host/grouped_tests.rs | 41 + crates/victory-gpu/src/host/late_tests.rs | 48 ++ crates/victory-gpu/src/host/queue2_tests.rs | 331 ++++++++ crates/victory-gpu/src/host/relay_tests.rs | 64 ++ crates/victory-gpu/src/host/spare.rs | 23 + crates/victory-gpu/src/host/tests.rs | 144 ++++ crates/victory-gpu/src/host/trail.rs | 14 + crates/victory-shader/src/emit/lower.rs | 630 +------------- crates/victory-shader/src/emit/lower_tests.rs | 626 ++++++++++++++ 11 files changed, 1407 insertions(+), 1415 deletions(-) create mode 100644 crates/victory-gpu/src/host/batch.rs create mode 100644 crates/victory-gpu/src/host/grouped_tests.rs create mode 100644 crates/victory-gpu/src/host/late_tests.rs create mode 100644 crates/victory-gpu/src/host/queue2_tests.rs create mode 100644 crates/victory-gpu/src/host/relay_tests.rs create mode 100644 crates/victory-gpu/src/host/spare.rs create mode 100644 crates/victory-gpu/src/host/tests.rs create mode 100644 crates/victory-gpu/src/host/trail.rs create mode 100644 crates/victory-shader/src/emit/lower_tests.rs diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 9b758bb0fb..0a6fb76131 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -1388,152 +1388,7 @@ pub(crate) fn warp_adapter() -> windows::core::Result { } #[cfg(test)] -mod tests { - /// Run once with VICTORY_CARD_SYNC_BATCH=0 and once with it set to 1. - #[test] - #[ignore = "requires a D3D12 adapter and the card hash pipeline; run alone"] - fn two_dirty_card_buffers_reach_readback_in_the_same_submission() { - use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, - }; - const MEM_WRITE_WATCH: u32 = 0x20_0000; - const MIB: usize = 1 << 20; - const PIECE: usize = 64 << 10; - let host = super::host().expect("a D3D12 device"); - assert!(host.card_ready(), "the card hash pipeline must be available"); - // SAFETY: a private allocation held through the fenced submissions. - let allocation = unsafe { - VirtualAlloc(std::ptr::null(), 2 * MIB, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) - }; - assert!(!allocation.is_null()); - let bases = [allocation as usize, allocation as usize + MIB]; - let shadows = bases.map(|base| { - crate::shadow::register(base, base as u64, MIB as u64); - let copy = crate::shadow::find(base as u64, MIB as u64).unwrap(); - assert!(copy.carded(), "both title buffers must have a card copy"); - copy - }); - let readback = host.read_back_buffer(16).unwrap(); - let hash_readback = host.read_back_buffer(64).unwrap(); - let mut previous = [0u128; 4]; - for round in [0x11u32, 0x55] { - let list = host.new_list().unwrap(); - let mut expected = [0u32; 4]; - for (i, (shadow, &base)) in shadows.iter().zip(&bases).enumerate() { - for (j, offset) in [32, PIECE + 20].into_iter().enumerate() { - let k = 2 * i + j; - expected[k] = round * 0x0101_0101 + k as u32; - // SAFETY: aligned dword in the private allocation. - unsafe { ((base + offset) as *mut u32).write_volatile(expected[k]); } - shadow.refresh(&list, (base + offset) as u64, 4); - // Request the before-hash for each of the two distinct pieces. - shadow.gpu_writes(&list, (base + offset) as u64, 4); - // SAFETY: the readback and the copy outlive this fenced list. - unsafe { list.list.CopyBufferRegion(&readback, (k * 4) as u64, &shadow.buffer, offset as u64, 4); } - } - } - list.close(); - host.execute(&[&list]); - let mut mapped = std::ptr::null_mut(); - // SAFETY: execute waited for all four writes, and the buffer holds 16 bytes. - let got = unsafe { - readback.Map(0, None, Some(&mut mapped)).unwrap(); - let got = mapped.cast::<[u32; 4]>().read_unaligned(); - readback.Unmap(0, None); - got - }; - assert_eq!(got, expected, "both copied pieces of each buffer"); - let hash_list = host.new_list().unwrap(); - for (i, shadow) in shadows.iter().enumerate() { - let hashes = shadow.card_sides().unwrap().1.expect("before-hashes were made"); - // SAFETY: two consecutive 16-byte piece hashes from each live buffer. - unsafe { hash_list.list.CopyBufferRegion(&hash_readback, (32 * i) as u64, &hashes, 0, 32); } - } - hash_list.close(); - host.execute(&[&hash_list]); - // SAFETY: all 64 bytes of the readback were written and fenced. - let current = unsafe { - hash_readback.Map(0, None, Some(&mut mapped)).unwrap(); - let words = mapped.cast::<[u128; 4]>().read_unaligned(); - hash_readback.Unmap(0, None); - words - }; - for (i, hash) in current.iter().enumerate() { - assert_ne!(*hash, previous[i], "piece {i} must be rehashed"); - assert!(!current[..i].contains(hash), "each piece has different input"); - } - previous = current; - } - for base in bases { - crate::shadow::unregister(base, base as u64); - } - drop(shadows); - // SAFETY: the lists completed and the copies were unregistered. - unsafe { VirtualFree(allocation, 0, MEM_RELEASE); } - } - - #[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] - 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 }; - // 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}", - desc.VendorId, desc.Flags - ); - assert_eq!( - warp_adapter().is_ok(), - desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, - ); - } -} +mod tests; /// A host command list and its allocator, always used together. pub(crate) struct HostList { @@ -3354,72 +3209,7 @@ fn note_beside(noted: &mut std::collections::HashMap<(usize, u32), u64>, fetched } #[cfg(test)] -mod relay_tests { - use super::{fetched_beside, flagged_pieces, landable, note_beside}; - - /// A piece fetched on the copy queue while a later flight was in the - /// air is fetched again by that flight, and by no flight sent after - /// the fetch had run; the note goes when its flights have landed. - #[test] - fn a_piece_fetched_beside_a_later_flight_is_fetched_again_by_it() { - let mut noted = std::collections::HashMap::new(); - let (a, p) = (0x1000usize, 7u32); - // Flight 5 lands; its fetch ran while 6 and 7 had started. - assert_eq!(note_beside(&mut noted, &[(a, p)], 5, 7), 1); - assert!(fetched_beside(noted.get(&(a, p)).copied(), 6)); - assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); - // Flight 8 was sent after the fetch had run: its compare decides. - assert!(!fetched_beside(noted.get(&(a, p)).copied(), 8)); - // Another piece was never noted. - assert!(!fetched_beside(noted.get(&(a, p + 1)).copied(), 6)); - // Flight 6 lands and fetches it again, with 7 still in the air and - // nothing newer: the note stays for 7. - assert_eq!(note_beside(&mut noted, &[(a, p)], 6, 7), 1); - assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); - // Flight 7 lands with nothing behind it: nothing is noted any more. - assert_eq!(note_beside(&mut noted, &[(a, p)], 7, 7), 0); - assert!(noted.is_empty()); - // A fetch with nothing later in the air notes nothing. - assert_eq!(note_beside(&mut noted, &[(a, p)], 9, 9), 0); - assert!(noted.is_empty()); - } - - /// 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); - } -} +mod relay_tests; /// The most host lists in the air before the flights are settled /// (`VICTORY_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the @@ -4139,49 +3929,7 @@ fn grouped(given: impl Iterator) -> Vec<(T } #[cfg(test)] -mod grouped_tests { - /// What the search per step gives (`declared_writes` without the - /// switch), for keys that stand for themselves. - fn searched(given: &[(usize, (usize, usize))]) -> Vec<(usize, Vec<(usize, usize)>)> { - let mut back: Vec<(usize, Vec<(usize, usize)>)> = Vec::new(); - for &(key, range) in given { - match back.iter_mut().find(|(k, _)| *k == key) { - Some((_, ranges)) => { - if !ranges.contains(&range) { - ranges.push(range); - } - } - None => back.push((key, vec![range])), - } - } - back - } - - /// The index gives what the search gives: the same keys in the same - /// order, each with the same ranges in the same order, whatever comes - /// twice and however the keys take turns. - #[test] - fn the_index_gives_what_the_search_gives() { - let mut seed = 0x9e37_79b9_7f4a_7c15u64; - let mut next = |below: usize| { - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - (seed >> 33) as usize % below - }; - assert!(super::grouped(std::iter::empty::<(usize, usize, (usize, usize))>()).is_empty()); - for (keys, ranges, steps) in [(1, 1, 5), (3, 4, 200), (40, 6, 3000), (500, 50, 3000)] { - for _ in 0..20 { - let given: Vec<(usize, (usize, usize))> = (0..steps) - .map(|_| { - let from = next(ranges) * 64; - (0x1000 + next(keys) * 8, (from, from + 16 + next(2) * 16)) - }) - .collect(); - let by_index = super::grouped(given.iter().map(|&(key, range)| (key, key, range))); - assert_eq!(by_index, searched(&given), "{keys} keys, {ranges} ranges, {steps} steps"); - } - } - } -} +mod grouped_tests; /// The ranges of `runs`' steps that give memory to shaders, with the copy /// each is of; `carded`: only those of copies in the card's memory. @@ -4828,56 +4576,7 @@ fn late_line(frames: 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)); - } -} +mod late_tests; /// 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 @@ -10986,159 +10685,13 @@ 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"); - } -} +mod trail; #[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()); - } -} +mod spare; #[cfg(test)] -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; - - #[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() - ); - } - - #[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); - } -} +mod batch; // Batch::texture_due lives here; `mod tests` is already taken at the top of this file /// The host's own paths for a copy in the card's memory, end to end, on /// the software adapter only: the title's bytes go up, a shader reads them @@ -11155,336 +10708,4 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at /// The same title memory must come out whatever the switches: through the /// direct queue alone, and through the copy queues. #[cfg(test)] -mod queue2_tests { - use super::*; - - /// `memory[to] = memory[from] + add`, after `spin` steps. - const ADD: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" -cbuffer What : register(b0) { uint to; uint from; uint add; uint spin; }; -RWByteAddressBuffer memory : register(u0); -[RootSignature(RS)] -[numthreads(1, 1, 1)] -void main() { - uint h = 0u; - [loop] - for (uint i = 0u; i < spin; i++) { - h = (h ^ memory.Load(from)) * 0x01000193u; - } - memory.Store(to, memory.Load(from) + add + (h & 0u)); -} -"#; - - #[test] - fn warp_title_bytes_go_up_and_shader_writes_come_back_whatever_the_queues() { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; - const MEM_WRITE_WATCH: u32 = 0x0020_0000; - let Some(host) = host() else { - return; - }; - // Never on a real card. - // SAFETY: a plain query. - let software = host - .adapter - .as_ref() - .and_then(|a| unsafe { a.GetDesc1() }.ok()) - .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); - if !software { - eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); - return; - } - const PIECE: usize = 64 << 10; - const LEN: usize = 4 << 20; - const ROUNDS: usize = 12; - // "Title memory": write-watched, as the title's is. - // SAFETY: a plain allocation of our own. - let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; - assert!(!title.is_null()); - let dword = |at: usize| unsafe { title.add(at).cast::() }; - for i in 0..LEN / 4 { - // SAFETY: inside the allocation. - unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; - } - crate::shadow::register(0x51_5151, title as u64, LEN as u64); - let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); - if !shadow.carded() { - eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); - return; - } - let code = compile(ADD, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); - // SAFETY: the shader's own root signature; plain creation. - let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); - let pso = 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"); - (root, pso) - }; - // Round k: the title writes a dword in piece 1+k; a submission's - // shader adds k to it and stores the sum in piece 30+k, a range - // declared as shader-written. Nothing is waited for between the - // rounds where submissions are sent ahead. - let from = |k: usize| (1 + k) * PIECE + 4 * k + 64; - let to = |k: usize| (30 + k) * PIECE + 8 * k + 128; - let titles = |k: usize| 0x0100_0000 + 0x1000 * k as u32 + 7; - let mut lists = Vec::new(); - for k in 0..ROUNDS { - // SAFETY: inside the allocation. - unsafe { dword(from(k)).write_volatile(titles(k)) }; - let list = host.new_list().expect("a host list"); - shadow.refresh(&list, title as u64, LEN as u64); - shadow.gpu_writes(&list, (title as usize + (30 + k) * PIECE) as u64, PIECE as u64); - // SAFETY: an open list; the copy's buffer, with unordered - // access; the shader's own root signature. - unsafe { - list.list.SetComputeRootSignature(&root); - list.list.SetPipelineState(&pso); - let constants = [to(k) as u32, from(k) as u32, k as u32, 30_000]; - list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); - list.list.Dispatch(1, 1, 1); - } - list.close(); - if late() { - host.execute_own(&list); - } else { - host.execute(&[&list]); - } - lists.push(list); - } - settle_now(WHY_SYNC); - for k in 0..ROUNDS { - // SAFETY: inside the allocation. - let (sum, kept) = unsafe { (dword(to(k)).read_volatile(), dword(from(k)).read_volatile()) }; - assert_eq!(kept, titles(k), "round {k}: the title's own dword changed"); - assert_eq!( - sum, - titles(k) + k as u32, - "round {k}: the shader read {:#x} where the title had written {:#x}, or its write did not come back", - sum.wrapping_sub(k as u32), - titles(k) - ); - } - // Nothing else moved. - let touched: std::collections::HashSet = (0..ROUNDS).flat_map(|k| [from(k), to(k)]).collect(); - for i in (0..LEN / 4).filter(|i| !touched.contains(&(i * 4))) { - // SAFETY: inside the allocation. - let got = unsafe { dword(i * 4).read_volatile() }; - assert_eq!(got, 0x5A00_0000 | i as u32, "dword {i} of title memory changed"); - } - // The queues the switches name did the work. - if let Some(second) = crate::queue2::second() { - let (down, up) = (second.down.stats.jobs.load(Ordering::Relaxed), second.up.stats.jobs.load(Ordering::Relaxed)); - // (Sends that found no landing buffer went the old way.) - let no_room = second.landing[1].load(Ordering::Relaxed); - eprintln!( - "queue2_tests: VICTORY_QUEUE2={} late {} relay {}: {down} fetches and {up} sends through the copy queues ({no_room} more found no landing buffer), the direct queue told to wait {} times", - crate::queue2::bits(), - late(), - relay(), - second.held[0].load(Ordering::Relaxed) - ); - assert_eq!(down > 0, second.fetches(), "fetches through the copy queue"); - assert_eq!(up + no_room > 0, second.uploads(), "sends through the copy queue"); - assert_eq!(up, second.held[0].load(Ordering::Relaxed), "the direct queue waits for every send"); - } else { - eprintln!("queue2_tests: the direct queue alone (late {}, relay {})", late(), relay()); - } - drop(lists); - } - - /// `memory[to] = first` at once; then `spin` steps, each a store to - /// `memory[to + 4]`; then `memory[to + 4] = 0` and `memory[to] = last`. - /// Whatever `spin` is, the bytes it leaves are the same. - const TWICE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" -cbuffer What : register(b0) { uint to; uint first; uint last; uint spin; }; -RWByteAddressBuffer memory : register(u0); -[RootSignature(RS)] -[numthreads(1, 1, 1)] -void main() { - memory.Store(to, first); - [loop] - for (uint i = 0u; i < spin; i++) { - memory.Store(to + 4u, i); - } - memory.Store(to + 4u, 0u); - memory.Store(to, last); -} -"#; - - /// The hole a fetch on the copy queue had (`VICTORY_QUEUE2` bit 1 with - /// the relay): flight A writes a piece; flight B, sent behind it, - /// writes the same piece through a half-way value and leaves it as A - /// left it. A is landed while B is half way: the fetch, beside B on - /// the copy queue, brings B's half-way bytes into title memory. B's - /// compare finds the piece as A's compare left it and flags nothing, - /// so B's landing fetched nothing and title memory kept the half-way - /// bytes. With the fix B's landing fetches the piece all the same - /// (`BESIDE`). - /// - /// `VICTORY_D3D12_WARP=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_QUEUE2=1 - /// VICTORY_RELAY=1 cargo test -p victory-gpu --features diagnostics - /// fetched_again -- --nocapture` (alone: it lands its two flights - /// itself; `VICTORY_QUEUE2_REFETCH=0` shows the fault). - #[test] - fn warp_a_piece_fetched_while_a_later_flight_writes_it_is_fetched_again() { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; - const MEM_WRITE_WATCH: u32 = 0x0020_0000; - let Some(host) = host() else { - return; - }; - // Never on a real card. - // SAFETY: a plain query. - let software = host - .adapter - .as_ref() - .and_then(|a| unsafe { a.GetDesc1() }.ok()) - .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); - if !software { - eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); - return; - } - if !relay() || !crate::queue2::second().is_some_and(|s| s.fetches()) { - eprintln!("queue2_tests: skipped, fetches do not go to a copy queue beside the relay (VICTORY_RELAY=1 VICTORY_QUEUE2=1)"); - return; - } - const PIECE: usize = 64 << 10; - const LEN: usize = 4 << 20; - // SAFETY: a plain allocation of our own. - let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; - assert!(!title.is_null()); - let dword = |at: usize| unsafe { title.add(at).cast::() }; - for i in 0..LEN / 4 { - // SAFETY: inside the allocation. - unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; - } - crate::shadow::register(0x52_5252, title as u64, LEN as u64); - let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); - if !shadow.carded() { - eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); - return; - } - let code = compile(TWICE, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); - // SAFETY: the shader's own root signature; plain creation. - let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); - let pso = 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"); - (root, pso) - }; - // A list whose shader writes the dword at 256 of `piece`, declared. - let record = |piece: usize, first: u32, last: u32, spin: u32| { - let list = host.new_list().expect("a host list"); - shadow.refresh(&list, title as u64, LEN as u64); - shadow.gpu_writes(&list, (title as usize + piece * PIECE) as u64, PIECE as u64); - // SAFETY: an open list; the copy's buffer, with unordered - // access; the shader's own root signature. - unsafe { - list.list.SetComputeRootSignature(&root); - list.list.SetPipelineState(&pso); - let constants = [(piece * PIECE + 256) as u32, first, last, spin]; - list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); - list.list.Dispatch(1, 1, 1); - } - list.close(); - list - }; - // SAFETY: a plain query. - let completed = || unsafe { host.fence.GetCompletedValue() }; - let wait_for = |value: u64| { - while completed() < value { - std::thread::sleep(std::time::Duration::from_millis(1)); - } - }; - // How many steps keep the card busy for some seconds: timed on - // another piece, waited for. - const TRIAL: u32 = 1 << 20; - let trial = record(40, 1, 2, TRIAL); - let timing = std::time::Instant::now(); - host.execute(&[&trial]); - let took = timing.elapsed().as_secs_f64().max(1e-4); - let spin = (f64::from(TRIAL) * 3.0 / took).clamp(f64::from(TRIAL), 2.0e9) as u32; - // SAFETY: inside the allocation. - assert_eq!(unsafe { dword(40 * PIECE + 256).read_volatile() }, 2, "the trial's write did not come back"); - const AT: usize = 20 * PIECE + 256; - const HALF_WAY: u32 = 0xDEAD_0001; - const LEFT: u32 = 0x600D_0002; - // Flight A, and the card has run it. - let a = record(20, HALF_WAY, LEFT, 16); - let (submitted, mut sent_a) = host.submit(&[&a], true).expect("flight A sent ahead"); - let fence_a = *submitted; - drop(submitted); - wait_for(fence_a); - // Flight B: the same piece, through the half-way value, for seconds. - let b = record(20, HALF_WAY, LEFT, spin); - let (submitted, mut sent_b) = host.submit(&[&b], true).expect("flight B sent ahead"); - let fence_b = *submitted; - drop(submitted); - std::thread::sleep(std::time::Duration::from_millis(300)); - assert!( - completed() < fence_b, - "flight B had run after 0.3 s ({spin} steps; the trial's {TRIAL} took {took:.3} s): nothing to show" - ); - // A lands, as `Host::relay_land` lands it, while B is half way. - let mut fetch = None; - { - let plan = sent_a.card.as_ref().expect("flight A has a plan for the card's copies"); - host.relay_card_back(&[(sent_a.number, plan)], &mut fetch, fence_a, sent_a.number); - } - for (copy, ranges) in &sent_a.back { - copy.copy_back_done(ranges); - } - // SAFETY: inside the allocation. - let seen = unsafe { dword(AT).read_volatile() }; - let b_ran = completed() >= fence_b; - eprintln!( - "queue2_tests: after A's landing title memory holds {seen:#x} (half way {HALF_WAY:#x}, left {LEFT:#x}); B had run: {b_ran}; {spin} steps" - ); - assert_eq!( - seen, HALF_WAY, - "the fetch for A did not come down beside B (it waited for B, or B had not begun): this machine cannot show the fault" - ); - // B has run; it left the piece as A left it, so its compare flags - // nothing. Its landing must bring the piece down all the same. - wait_for(fence_b); - { - let plan = sent_b.card.as_ref().expect("flight B has a plan for the card's copies"); - host.relay_card_back(&[(sent_b.number, plan)], &mut fetch, fence_b, sent_b.number); - } - for (copy, ranges) in &sent_b.back { - copy.copy_back_done(ranges); - } - // SAFETY: inside the allocation. - let (left, beside) = unsafe { (dword(AT).read_volatile(), dword(AT + 4).read_volatile()) }; - assert_eq!( - left, LEFT, - "title memory kept flight B's half-way bytes: B's compare found the piece as A left it and B's landing fetched nothing" - ); - assert_eq!(beside, 0, "the dword beside it holds a half-way count"); - for sent in [&mut sent_a, &mut sent_b] { - if let Some(plan) = sent.card.take() { - host.card_done(plan); - } - } - drop((a, b, trial)); - } -} +mod queue2_tests; diff --git a/crates/victory-gpu/src/host/batch.rs b/crates/victory-gpu/src/host/batch.rs new file mode 100644 index 0000000000..a760f0a729 --- /dev/null +++ b/crates/victory-gpu/src/host/batch.rs @@ -0,0 +1,106 @@ +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() + ); +} + +#[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/host/grouped_tests.rs b/crates/victory-gpu/src/host/grouped_tests.rs new file mode 100644 index 0000000000..7e4fbeb5f8 --- /dev/null +++ b/crates/victory-gpu/src/host/grouped_tests.rs @@ -0,0 +1,41 @@ +/// What the search per step gives (`declared_writes` without the +/// switch), for keys that stand for themselves. +fn searched(given: &[(usize, (usize, usize))]) -> Vec<(usize, Vec<(usize, usize)>)> { + let mut back: Vec<(usize, Vec<(usize, usize)>)> = Vec::new(); + for &(key, range) in given { + match back.iter_mut().find(|(k, _)| *k == key) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => back.push((key, vec![range])), + } + } + back +} + +/// The index gives what the search gives: the same keys in the same +/// order, each with the same ranges in the same order, whatever comes +/// twice and however the keys take turns. +#[test] +fn the_index_gives_what_the_search_gives() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |below: usize| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as usize % below + }; + assert!(super::grouped(std::iter::empty::<(usize, usize, (usize, usize))>()).is_empty()); + for (keys, ranges, steps) in [(1, 1, 5), (3, 4, 200), (40, 6, 3000), (500, 50, 3000)] { + for _ in 0..20 { + let given: Vec<(usize, (usize, usize))> = (0..steps) + .map(|_| { + let from = next(ranges) * 64; + (0x1000 + next(keys) * 8, (from, from + 16 + next(2) * 16)) + }) + .collect(); + let by_index = super::grouped(given.iter().map(|&(key, range)| (key, key, range))); + assert_eq!(by_index, searched(&given), "{keys} keys, {ranges} ranges, {steps} steps"); + } + } +} diff --git a/crates/victory-gpu/src/host/late_tests.rs b/crates/victory-gpu/src/host/late_tests.rs new file mode 100644 index 0000000000..1aa078f996 --- /dev/null +++ b/crates/victory-gpu/src/host/late_tests.rs @@ -0,0 +1,48 @@ +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)); +} diff --git a/crates/victory-gpu/src/host/queue2_tests.rs b/crates/victory-gpu/src/host/queue2_tests.rs new file mode 100644 index 0000000000..1f0ef4f648 --- /dev/null +++ b/crates/victory-gpu/src/host/queue2_tests.rs @@ -0,0 +1,331 @@ +use super::*; + +/// `memory[to] = memory[from] + add`, after `spin` steps. +const ADD: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" +cbuffer What : register(b0) { uint to; uint from; uint add; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint h = 0u; + [loop] + for (uint i = 0u; i < spin; i++) { + h = (h ^ memory.Load(from)) * 0x01000193u; + } + memory.Store(to, memory.Load(from) + add + (h & 0u)); +} +"#; + +#[test] +fn warp_title_bytes_go_up_and_shader_writes_come_back_whatever_the_queues() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x0020_0000; + let Some(host) = host() else { + return; + }; + // Never on a real card. + // SAFETY: a plain query. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + if !software { + eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); + return; + } + const PIECE: usize = 64 << 10; + const LEN: usize = 4 << 20; + const ROUNDS: usize = 12; + // "Title memory": write-watched, as the title's is. + // SAFETY: a plain allocation of our own. + let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + assert!(!title.is_null()); + let dword = |at: usize| unsafe { title.add(at).cast::() }; + for i in 0..LEN / 4 { + // SAFETY: inside the allocation. + unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; + } + crate::shadow::register(0x51_5151, title as u64, LEN as u64); + let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); + if !shadow.carded() { + eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); + return; + } + let code = compile(ADD, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + // SAFETY: the shader's own root signature; plain creation. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let pso = 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"); + (root, pso) + }; + // Round k: the title writes a dword in piece 1+k; a submission's + // shader adds k to it and stores the sum in piece 30+k, a range + // declared as shader-written. Nothing is waited for between the + // rounds where submissions are sent ahead. + let from = |k: usize| (1 + k) * PIECE + 4 * k + 64; + let to = |k: usize| (30 + k) * PIECE + 8 * k + 128; + let titles = |k: usize| 0x0100_0000 + 0x1000 * k as u32 + 7; + let mut lists = Vec::new(); + for k in 0..ROUNDS { + // SAFETY: inside the allocation. + unsafe { dword(from(k)).write_volatile(titles(k)) }; + let list = host.new_list().expect("a host list"); + shadow.refresh(&list, title as u64, LEN as u64); + shadow.gpu_writes(&list, (title as usize + (30 + k) * PIECE) as u64, PIECE as u64); + // SAFETY: an open list; the copy's buffer, with unordered + // access; the shader's own root signature. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + let constants = [to(k) as u32, from(k) as u32, k as u32, 30_000]; + list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + } + list.close(); + if late() { + host.execute_own(&list); + } else { + host.execute(&[&list]); + } + lists.push(list); + } + settle_now(WHY_SYNC); + for k in 0..ROUNDS { + // SAFETY: inside the allocation. + let (sum, kept) = unsafe { (dword(to(k)).read_volatile(), dword(from(k)).read_volatile()) }; + assert_eq!(kept, titles(k), "round {k}: the title's own dword changed"); + assert_eq!( + sum, + titles(k) + k as u32, + "round {k}: the shader read {:#x} where the title had written {:#x}, or its write did not come back", + sum.wrapping_sub(k as u32), + titles(k) + ); + } + // Nothing else moved. + let touched: std::collections::HashSet = (0..ROUNDS).flat_map(|k| [from(k), to(k)]).collect(); + for i in (0..LEN / 4).filter(|i| !touched.contains(&(i * 4))) { + // SAFETY: inside the allocation. + let got = unsafe { dword(i * 4).read_volatile() }; + assert_eq!(got, 0x5A00_0000 | i as u32, "dword {i} of title memory changed"); + } + // The queues the switches name did the work. + if let Some(second) = crate::queue2::second() { + let (down, up) = (second.down.stats.jobs.load(Ordering::Relaxed), second.up.stats.jobs.load(Ordering::Relaxed)); + // (Sends that found no landing buffer went the old way.) + let no_room = second.landing[1].load(Ordering::Relaxed); + eprintln!( + "queue2_tests: VICTORY_QUEUE2={} late {} relay {}: {down} fetches and {up} sends through the copy queues ({no_room} more found no landing buffer), the direct queue told to wait {} times", + crate::queue2::bits(), + late(), + relay(), + second.held[0].load(Ordering::Relaxed) + ); + assert_eq!(down > 0, second.fetches(), "fetches through the copy queue"); + assert_eq!(up + no_room > 0, second.uploads(), "sends through the copy queue"); + assert_eq!(up, second.held[0].load(Ordering::Relaxed), "the direct queue waits for every send"); + } else { + eprintln!("queue2_tests: the direct queue alone (late {}, relay {})", late(), relay()); + } + drop(lists); +} + +/// `memory[to] = first` at once; then `spin` steps, each a store to +/// `memory[to + 4]`; then `memory[to + 4] = 0` and `memory[to] = last`. +/// Whatever `spin` is, the bytes it leaves are the same. +const TWICE: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" +cbuffer What : register(b0) { uint to; uint first; uint last; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + memory.Store(to, first); + [loop] + for (uint i = 0u; i < spin; i++) { + memory.Store(to + 4u, i); + } + memory.Store(to + 4u, 0u); + memory.Store(to, last); +} +"#; + +/// The hole a fetch on the copy queue had (`VICTORY_QUEUE2` bit 1 with +/// the relay): flight A writes a piece; flight B, sent behind it, +/// writes the same piece through a half-way value and leaves it as A +/// left it. A is landed while B is half way: the fetch, beside B on +/// the copy queue, brings B's half-way bytes into title memory. B's +/// compare finds the piece as A's compare left it and flags nothing, +/// so B's landing fetched nothing and title memory kept the half-way +/// bytes. With the fix B's landing fetches the piece all the same +/// (`BESIDE`). +/// +/// `VICTORY_D3D12_WARP=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_QUEUE2=1 +/// VICTORY_RELAY=1 cargo test -p victory-gpu --features diagnostics +/// fetched_again -- --nocapture` (alone: it lands its two flights +/// itself; `VICTORY_QUEUE2_REFETCH=0` shows the fault). +#[test] +fn warp_a_piece_fetched_while_a_later_flight_writes_it_is_fetched_again() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x0020_0000; + let Some(host) = host() else { + return; + }; + // Never on a real card. + // SAFETY: a plain query. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + if !software { + eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); + return; + } + if !relay() || !crate::queue2::second().is_some_and(|s| s.fetches()) { + eprintln!("queue2_tests: skipped, fetches do not go to a copy queue beside the relay (VICTORY_RELAY=1 VICTORY_QUEUE2=1)"); + return; + } + const PIECE: usize = 64 << 10; + const LEN: usize = 4 << 20; + // SAFETY: a plain allocation of our own. + let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + assert!(!title.is_null()); + let dword = |at: usize| unsafe { title.add(at).cast::() }; + for i in 0..LEN / 4 { + // SAFETY: inside the allocation. + unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; + } + crate::shadow::register(0x52_5252, title as u64, LEN as u64); + let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); + if !shadow.carded() { + eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); + return; + } + let code = compile(TWICE, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + // SAFETY: the shader's own root signature; plain creation. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let pso = 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"); + (root, pso) + }; + // A list whose shader writes the dword at 256 of `piece`, declared. + let record = |piece: usize, first: u32, last: u32, spin: u32| { + let list = host.new_list().expect("a host list"); + shadow.refresh(&list, title as u64, LEN as u64); + shadow.gpu_writes(&list, (title as usize + piece * PIECE) as u64, PIECE as u64); + // SAFETY: an open list; the copy's buffer, with unordered + // access; the shader's own root signature. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + let constants = [(piece * PIECE + 256) as u32, first, last, spin]; + list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + } + list.close(); + list + }; + // SAFETY: a plain query. + let completed = || unsafe { host.fence.GetCompletedValue() }; + let wait_for = |value: u64| { + while completed() < value { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + // How many steps keep the card busy for some seconds: timed on + // another piece, waited for. + const TRIAL: u32 = 1 << 20; + let trial = record(40, 1, 2, TRIAL); + let timing = std::time::Instant::now(); + host.execute(&[&trial]); + let took = timing.elapsed().as_secs_f64().max(1e-4); + let spin = (f64::from(TRIAL) * 3.0 / took).clamp(f64::from(TRIAL), 2.0e9) as u32; + // SAFETY: inside the allocation. + assert_eq!(unsafe { dword(40 * PIECE + 256).read_volatile() }, 2, "the trial's write did not come back"); + const AT: usize = 20 * PIECE + 256; + const HALF_WAY: u32 = 0xDEAD_0001; + const LEFT: u32 = 0x600D_0002; + // Flight A, and the card has run it. + let a = record(20, HALF_WAY, LEFT, 16); + let (submitted, mut sent_a) = host.submit(&[&a], true).expect("flight A sent ahead"); + let fence_a = *submitted; + drop(submitted); + wait_for(fence_a); + // Flight B: the same piece, through the half-way value, for seconds. + let b = record(20, HALF_WAY, LEFT, spin); + let (submitted, mut sent_b) = host.submit(&[&b], true).expect("flight B sent ahead"); + let fence_b = *submitted; + drop(submitted); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert!( + completed() < fence_b, + "flight B had run after 0.3 s ({spin} steps; the trial's {TRIAL} took {took:.3} s): nothing to show" + ); + // A lands, as `Host::relay_land` lands it, while B is half way. + let mut fetch = None; + { + let plan = sent_a.card.as_ref().expect("flight A has a plan for the card's copies"); + host.relay_card_back(&[(sent_a.number, plan)], &mut fetch, fence_a, sent_a.number); + } + for (copy, ranges) in &sent_a.back { + copy.copy_back_done(ranges); + } + // SAFETY: inside the allocation. + let seen = unsafe { dword(AT).read_volatile() }; + let b_ran = completed() >= fence_b; + eprintln!( + "queue2_tests: after A's landing title memory holds {seen:#x} (half way {HALF_WAY:#x}, left {LEFT:#x}); B had run: {b_ran}; {spin} steps" + ); + assert_eq!( + seen, HALF_WAY, + "the fetch for A did not come down beside B (it waited for B, or B had not begun): this machine cannot show the fault" + ); + // B has run; it left the piece as A left it, so its compare flags + // nothing. Its landing must bring the piece down all the same. + wait_for(fence_b); + { + let plan = sent_b.card.as_ref().expect("flight B has a plan for the card's copies"); + host.relay_card_back(&[(sent_b.number, plan)], &mut fetch, fence_b, sent_b.number); + } + for (copy, ranges) in &sent_b.back { + copy.copy_back_done(ranges); + } + // SAFETY: inside the allocation. + let (left, beside) = unsafe { (dword(AT).read_volatile(), dword(AT + 4).read_volatile()) }; + assert_eq!( + left, LEFT, + "title memory kept flight B's half-way bytes: B's compare found the piece as A left it and B's landing fetched nothing" + ); + assert_eq!(beside, 0, "the dword beside it holds a half-way count"); + for sent in [&mut sent_a, &mut sent_b] { + if let Some(plan) = sent.card.take() { + host.card_done(plan); + } + } + drop((a, b, trial)); +} diff --git a/crates/victory-gpu/src/host/relay_tests.rs b/crates/victory-gpu/src/host/relay_tests.rs new file mode 100644 index 0000000000..d9877008a0 --- /dev/null +++ b/crates/victory-gpu/src/host/relay_tests.rs @@ -0,0 +1,64 @@ +use super::{fetched_beside, flagged_pieces, landable, note_beside}; + +/// A piece fetched on the copy queue while a later flight was in the +/// air is fetched again by that flight, and by no flight sent after +/// the fetch had run; the note goes when its flights have landed. +#[test] +fn a_piece_fetched_beside_a_later_flight_is_fetched_again_by_it() { + let mut noted = std::collections::HashMap::new(); + let (a, p) = (0x1000usize, 7u32); + // Flight 5 lands; its fetch ran while 6 and 7 had started. + assert_eq!(note_beside(&mut noted, &[(a, p)], 5, 7), 1); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 6)); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); + // Flight 8 was sent after the fetch had run: its compare decides. + assert!(!fetched_beside(noted.get(&(a, p)).copied(), 8)); + // Another piece was never noted. + assert!(!fetched_beside(noted.get(&(a, p + 1)).copied(), 6)); + // Flight 6 lands and fetches it again, with 7 still in the air and + // nothing newer: the note stays for 7. + assert_eq!(note_beside(&mut noted, &[(a, p)], 6, 7), 1); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); + // Flight 7 lands with nothing behind it: nothing is noted any more. + assert_eq!(note_beside(&mut noted, &[(a, p)], 7, 7), 0); + assert!(noted.is_empty()); + // A fetch with nothing later in the air notes nothing. + assert_eq!(note_beside(&mut noted, &[(a, p)], 9, 9), 0); + assert!(noted.is_empty()); +} + +/// 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); +} diff --git a/crates/victory-gpu/src/host/spare.rs b/crates/victory-gpu/src/host/spare.rs new file mode 100644 index 0000000000..c940e4855e --- /dev/null +++ b/crates/victory-gpu/src/host/spare.rs @@ -0,0 +1,23 @@ +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()); +} diff --git a/crates/victory-gpu/src/host/tests.rs b/crates/victory-gpu/src/host/tests.rs new file mode 100644 index 0000000000..1de6d4fecc --- /dev/null +++ b/crates/victory-gpu/src/host/tests.rs @@ -0,0 +1,144 @@ +/// Run once with VICTORY_CARD_SYNC_BATCH=0 and once with it set to 1. +#[test] +#[ignore = "requires a D3D12 adapter and the card hash pipeline; run alone"] +fn two_dirty_card_buffers_reach_readback_in_the_same_submission() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + const MIB: usize = 1 << 20; + const PIECE: usize = 64 << 10; + let host = super::host().expect("a D3D12 device"); + assert!(host.card_ready(), "the card hash pipeline must be available"); + // SAFETY: a private allocation held through the fenced submissions. + let allocation = unsafe { + VirtualAlloc(std::ptr::null(), 2 * MIB, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) + }; + assert!(!allocation.is_null()); + let bases = [allocation as usize, allocation as usize + MIB]; + let shadows = bases.map(|base| { + crate::shadow::register(base, base as u64, MIB as u64); + let copy = crate::shadow::find(base as u64, MIB as u64).unwrap(); + assert!(copy.carded(), "both title buffers must have a card copy"); + copy + }); + let readback = host.read_back_buffer(16).unwrap(); + let hash_readback = host.read_back_buffer(64).unwrap(); + let mut previous = [0u128; 4]; + for round in [0x11u32, 0x55] { + let list = host.new_list().unwrap(); + let mut expected = [0u32; 4]; + for (i, (shadow, &base)) in shadows.iter().zip(&bases).enumerate() { + for (j, offset) in [32, PIECE + 20].into_iter().enumerate() { + let k = 2 * i + j; + expected[k] = round * 0x0101_0101 + k as u32; + // SAFETY: aligned dword in the private allocation. + unsafe { ((base + offset) as *mut u32).write_volatile(expected[k]); } + shadow.refresh(&list, (base + offset) as u64, 4); + // Request the before-hash for each of the two distinct pieces. + shadow.gpu_writes(&list, (base + offset) as u64, 4); + // SAFETY: the readback and the copy outlive this fenced list. + unsafe { list.list.CopyBufferRegion(&readback, (k * 4) as u64, &shadow.buffer, offset as u64, 4); } + } + } + list.close(); + host.execute(&[&list]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: execute waited for all four writes, and the buffer holds 16 bytes. + let got = unsafe { + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let got = mapped.cast::<[u32; 4]>().read_unaligned(); + readback.Unmap(0, None); + got + }; + assert_eq!(got, expected, "both copied pieces of each buffer"); + let hash_list = host.new_list().unwrap(); + for (i, shadow) in shadows.iter().enumerate() { + let hashes = shadow.card_sides().unwrap().1.expect("before-hashes were made"); + // SAFETY: two consecutive 16-byte piece hashes from each live buffer. + unsafe { hash_list.list.CopyBufferRegion(&hash_readback, (32 * i) as u64, &hashes, 0, 32); } + } + hash_list.close(); + host.execute(&[&hash_list]); + // SAFETY: all 64 bytes of the readback were written and fenced. + let current = unsafe { + hash_readback.Map(0, None, Some(&mut mapped)).unwrap(); + let words = mapped.cast::<[u128; 4]>().read_unaligned(); + hash_readback.Unmap(0, None); + words + }; + for (i, hash) in current.iter().enumerate() { + assert_ne!(*hash, previous[i], "piece {i} must be rehashed"); + assert!(!current[..i].contains(hash), "each piece has different input"); + } + previous = current; + } + for base in bases { + crate::shadow::unregister(base, base as u64); + } + drop(shadows); + // SAFETY: the lists completed and the copies were unregistered. + unsafe { VirtualFree(allocation, 0, MEM_RELEASE); } +} + +#[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] +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 }; + // 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}", + desc.VendorId, desc.Flags + ); + assert_eq!( + warp_adapter().is_ok(), + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, + ); +} diff --git a/crates/victory-gpu/src/host/trail.rs b/crates/victory-gpu/src/host/trail.rs new file mode 100644 index 0000000000..b4f9b236b6 --- /dev/null +++ b/crates/victory-gpu/src/host/trail.rs @@ -0,0 +1,14 @@ +/// 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"); +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ad91c1251e..46d9f91a72 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -11687,631 +11687,5 @@ fn interp_mode(kind: Barycentric) -> Option { } #[cfg(test)] -mod tests { - use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; - use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, - }; - use crate::{io, ir, resource, structure}; - - 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 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] - 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(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 256).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, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - }) - .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 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, - 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 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 - // 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, 0).unwrap(); - } - } - - 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 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 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 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(); - } - - /// 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 a_uniform_branch_can_choose_between_immediate_samplers() { - // A root constant selects wrap or clamp. Keep the sample live with an LDS store. - let words = [ - 0xBE84_0300, 0xBE85_0380, // s[4:5] = texture table - 0xF40C_0302, 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0 - 0xBE89_0380, 0xBE8A_0380, 0xBE8B_0380, // sampler words 1-3 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0xBF85_0002, // branch to clamp - 0xBE88_0380, 0xBF82_0002, // wrap, skip clamp - 0xBE88_03FF, 0x0000_0092, // clamp all axes - 0xF09C_0F08, 0x0043_0C02, // image_sample_lz v[12:15], ..., s[8:11] - 0xD834_0000, 0x0000_0C00, // ds_write_b32 v0, v12 - S_ENDPGM, - ]; - let (mut layout, mut used) = texture_tables(); - layout[1] = root(RootType::Constants, 1, 1); - used.truncate(1); - let shader = lower_with(&words, layout, used).unwrap(); - assert_eq!(shader.samplers.len(), 2); - assert!(shader.samplers.contains(&[0, 0, 0, 0])); - assert!(shader.samplers.contains(&[0x92, 0, 0, 0])); - } - - #[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); - } - } - - /// [`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 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, 0).unwrap(); - } - } - - #[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, - 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, - // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. - assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); - assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); - assert_eq!( - buffer_format(50), - Some((&[10, 10, 10, 2][..], Numeric::Unorm)) - ); - assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); - assert_eq!( - buffer_format(77), - Some((&[32, 32, 32, 32][..], Numeric::Float)) - ); - // Invalid, past the table. - assert_eq!(buffer_format(0), 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); - } -} +#[path = "lower_tests.rs"] +mod tests; diff --git a/crates/victory-shader/src/emit/lower_tests.rs b/crates/victory-shader/src/emit/lower_tests.rs new file mode 100644 index 0000000000..5c8cf4ecd6 --- /dev/null +++ b/crates/victory-shader/src/emit/lower_tests.rs @@ -0,0 +1,626 @@ +use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +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 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] +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(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).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, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .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 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, + 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 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 + // 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, 0).unwrap(); + } +} + +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 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 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 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(); +} + +/// 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 a_uniform_branch_can_choose_between_immediate_samplers() { + // A root constant selects wrap or clamp. Keep the sample live with an LDS store. + let words = [ + 0xBE84_0300, 0xBE85_0380, // s[4:5] = texture table + 0xF40C_0302, 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0 + 0xBE89_0380, 0xBE8A_0380, 0xBE8B_0380, // sampler words 1-3 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0002, // branch to clamp + 0xBE88_0380, 0xBF82_0002, // wrap, skip clamp + 0xBE88_03FF, 0x0000_0092, // clamp all axes + 0xF09C_0F08, 0x0043_0C02, // image_sample_lz v[12:15], ..., s[8:11] + 0xD834_0000, 0x0000_0C00, // ds_write_b32 v0, v12 + S_ENDPGM, + ]; + let (mut layout, mut used) = texture_tables(); + layout[1] = root(RootType::Constants, 1, 1); + used.truncate(1); + let shader = lower_with(&words, layout, used).unwrap(); + assert_eq!(shader.samplers.len(), 2); + assert!(shader.samplers.contains(&[0, 0, 0, 0])); + assert!(shader.samplers.contains(&[0x92, 0, 0, 0])); +} + +#[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); + } +} + +/// [`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 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, 0).unwrap(); + } +} + +#[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, + 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, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), 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 9aac3495e2259aa7d4fbf0a363259b6b55caab20 Mon Sep 17 00:00:00 2001 From: ChatGPT Date: Thu, 26 Nov 2026 20:23:42 +0100 Subject: [PATCH 2/3] GPU: forget both descriptor range caches when a heap is destroyed AI-assisted adaptation to upstream stable heap IDs and marked-pass cache; no cadence changes. --- crates/victory-gpu/src/descriptor.rs | 1 + crates/victory-gpu/src/draw.rs | 45 +++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 372b4402fd..b8823dbac8 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -545,6 +545,7 @@ impl Drop for Heap { // #589, AscilCH). if let Some(Some(host)) = self.host.get() { crate::memory::forget_heap(host); + crate::draw::forget_heap_ranges(host.id()); } } } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c6245693ba..3473c100d5 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -953,12 +953,49 @@ pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); /// level so that the marked pass can have this one start anew: /// [`State::heap_buffers_marked`].) type Ranges = std::collections::HashMap, u64, u64)>; -static RANGES: std::sync::Mutex>> = +static RANGES: std::sync::Mutex>> = std::sync::Mutex::new(None); /// Per host heap, for [`State::heap_buffers_marked`]: what the marked pass /// keeps (`VICTORY_HEAP_PASS_MARKED`; nothing while that is unset). type Marked = crate::heap_pass::Picked>; -static MARKED: std::sync::Mutex>> = std::sync::Mutex::new(None); +static MARKED: std::sync::Mutex>> = std::sync::Mutex::new(None); +/// Called when the title heap is destroyed, after the shader-heap registry +/// lock is released. Drop cached resource references outside both locks. +pub(crate) fn forget_heap_ranges(id: u64) { + let marked = MARKED.lock().unwrap_or_else(|e| e.into_inner()) + .as_mut().and_then(|heaps| heaps.remove(&id)); + let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()) + .as_mut().and_then(|heaps| heaps.remove(&id)); + drop(marked); + drop(ranges); +} + +#[cfg(test)] +#[test] +fn heap_range_cache_forgets_both_passes() { + // IDs are allocated monotonically from 1. Reserve a synthetic high ID. + let id = u64::MAX - 1; + let other = u64::MAX - 2; + { + let mut ranges = RANGES.lock().unwrap(); + let heaps = ranges.get_or_insert_with(Default::default); + heaps.insert(id, (17, Ranges::new())); + heaps.insert(other, (3, Ranges::new())); + } + { + let mut marked = MARKED.lock().unwrap(); + let heaps = marked.get_or_insert_with(Default::default); + heaps.insert(id, Marked::new(false)); + heaps.insert(other, Marked::new(false)); + } + forget_heap_ranges(id); + assert!(!RANGES.lock().unwrap().as_ref().unwrap().contains_key(&id)); + assert!(!MARKED.lock().unwrap().as_ref().unwrap().contains_key(&id)); + assert!(RANGES.lock().unwrap().as_ref().unwrap().contains_key(&other)); + assert!(MARKED.lock().unwrap().as_ref().unwrap().contains_key(&other)); + forget_heap_ranges(other); +} + pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); /// Where the pass over textures picked by index records its uploads: into /// a list of the title's, or into lists of the thread that runs it ahead. @@ -2156,7 +2193,7 @@ impl State { 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) + .entry(host.id()) .or_insert_with(|| (0, Ranges::new())); let changed = host.buffer_changes(); let slots = if *passes % 16 == 0 { @@ -2304,7 +2341,7 @@ impl State { for picked in heaps.values_mut() { picked.note_forgotten(forgotten.as_deref()); } - let ranges = heaps.entry(std::ptr::from_ref(host) as usize).or_insert_with(|| Marked::new(false)); + let ranges = heaps.entry(host.id()).or_insert_with(|| Marked::new(false)); let changed = host.buffer_changes(); let record = |index: u32| heap.handle(index).map(crate::descriptor::record_at); let slots = ranges.plan(changed, || host.buffer_slots(), record, crate::descriptor::record_entry); From 900c15f5f1911ccfbfc1a0af80f542ff13c30b8f Mon Sep 17 00:00:00 2001 From: spk-c Date: Fri, 27 Nov 2026 00:55:19 +0100 Subject: [PATCH 3/3] GPU: cache exact buffer span unions per heap AI-assisted selective adaptation of Kelvaroq 0055 via fork #41; preserves upstream scan cadence and depends on stable heap lifetime fix #1372. --- crates/victory-gpu/src/descriptor/host.rs | 3 + .../src/descriptor/host/buffer_spans.rs | 102 ++++++++++++++++++ crates/victory-gpu/src/draw.rs | 58 +++++++--- docs/descriptor-buffer-spans.md | 9 ++ 4 files changed, 158 insertions(+), 14 deletions(-) create mode 100644 crates/victory-gpu/src/descriptor/host/buffer_spans.rs create mode 100644 docs/descriptor-buffer-spans.md diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 851d81e61c..df345e0a5c 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -14,6 +14,9 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::{VIEW_TAG, View, view_at}; use crate::host::host; +mod buffer_spans; +pub(crate) type BufferSpanIndex = buffer_spans::BufferSpans>; + /// The locks [`HostHeap::kept`] is spread over: slot `i` is behind lock /// `i % KEPT_PIECES`, at place `i / KEPT_PIECES`. Neighbouring slots are /// behind different locks on purpose: the recording threads take their diff --git a/crates/victory-gpu/src/descriptor/host/buffer_spans.rs b/crates/victory-gpu/src/descriptor/host/buffer_spans.rs new file mode 100644 index 0000000000..dd40f80414 --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host/buffer_spans.rs @@ -0,0 +1,102 @@ +//! Maintain the exact enclosing range for each backing buffer from its live slots. +use std::collections::{BTreeSet, HashMap}; + +struct Span { + copy: T, + starts: BTreeSet<(u64, u32)>, + ends: BTreeSet<(u64, u32)>, +} + +pub(crate) struct BufferSpans { + copies: HashMap>, +} + +impl Default for BufferSpans { + fn default() -> Self { + Self { copies: HashMap::new() } + } +} + +impl BufferSpans { + pub(crate) fn insert(&mut self, key: usize, slot: u32, copy: &T, from: u64, to: u64) { + let span = self.copies.entry(key).or_insert_with(|| Span { + copy: copy.clone(), + starts: BTreeSet::new(), + ends: BTreeSet::new(), + }); + span.starts.insert((from, slot)); + span.ends.insert((to, slot)); + } + + /// False means the caller must rebuild from its authoritative slot map. + pub(crate) fn remove(&mut self, key: usize, slot: u32, from: u64, to: u64) -> bool { + let Some(span) = self.copies.get_mut(&key) else { + return false; + }; + let start = span.starts.remove(&(from, slot)); + let end = span.ends.remove(&(to, slot)); + if span.starts.is_empty() && span.ends.is_empty() { + self.copies.remove(&key); + } + start && end + } + + /// Exactly the same per-buffer unions as walking all live descriptors. + pub(crate) fn snapshot(&self) -> HashMap { + self.copies.iter().map(|(&key, span)| { + let &(from, _) = span.starts.first().expect("nonempty span"); + let &(to, _) = span.ends.last().expect("nonempty span"); + (key, (span.copy.clone(), from, to)) + }).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn span_index_matches_full_scan_after_slot_moves_and_removals() { + let mut index = BufferSpans::default(); + let mut slots: HashMap = HashMap::new(); + for n in 0..2048u32 { + let slot = (n * 17) % 97; + if let Some((key, from, to)) = slots.remove(&slot) { + assert!(index.remove(key, slot, from, to)); + } + if n % 5 != 0 { + let key = ((n * 13) % 11) as usize; + let from = u64::from(n % 7) * 64; + let to = from + u64::from((n % 9) + 1) * 32; + slots.insert(slot, (key, from, to)); + index.insert(key, slot, &key, from, to); + } + let mut expected = HashMap::new(); + for &(key, from, to) in slots.values() { + let span = expected.entry(key).or_insert((key, from, to)); + span.1 = span.1.min(from); + span.2 = span.2.max(to); + } + assert_eq!(index.snapshot(), expected); + } + for (slot, (key, from, to)) in slots { + assert!(index.remove(key, slot, from, to)); + } + assert!(index.snapshot().is_empty()); + assert!(!index.remove(0, 0, 0, 1)); + } + + #[test] + fn duplicate_bounds_are_kept_until_the_last_slot_is_removed() { + let mut index = BufferSpans::default(); + index.insert(1, 0, &1, 16, 64); + index.insert(1, 1, &1, 16, 64); + index.insert(1, 2, &1, 32, 48); + assert!(index.remove(1, 0, 16, 64)); + assert_eq!(index.snapshot()[&1], (1, 16, 64)); + assert!(index.remove(1, 1, 16, 64)); + assert_eq!(index.snapshot()[&1], (1, 32, 48)); + assert!(index.remove(1, 2, 32, 48)); + assert!(index.snapshot().is_empty()); + } +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index a84fa572d8..516e8812d9 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -953,7 +953,13 @@ pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); /// level so that the marked pass can have this one start anew: /// [`State::heap_buffers_marked`].) type Ranges = std::collections::HashMap, u64, u64)>; -static RANGES: std::sync::Mutex>> = +#[derive(Default)] +struct BufferScan { + passes: u64, + ranges: Ranges, + span_index: Option, +} +static RANGES: std::sync::Mutex>> = std::sync::Mutex::new(None); /// Per host heap, for [`State::heap_buffers_marked`]: what the marked pass /// keeps (`VICTORY_HEAP_PASS_MARKED`; nothing while that is unset). @@ -979,8 +985,8 @@ fn heap_range_cache_forgets_both_passes() { { let mut ranges = RANGES.lock().unwrap(); let heaps = ranges.get_or_insert_with(Default::default); - heaps.insert(id, (17, Ranges::new())); - heaps.insert(other, (3, Ranges::new())); + heaps.insert(id, BufferScan { passes: 17, ..Default::default() }); + heaps.insert(other, BufferScan { passes: 3, ..Default::default() }); } { let mut marked = MARKED.lock().unwrap(); @@ -2191,13 +2197,18 @@ impl State { // released resource goes stale without a write, and a slot written // before its memory had a host copy is only made then. let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); - let (passes, ranges) = kept + let BufferScan { passes, ranges, span_index } = kept .get_or_insert_with(Default::default) .entry(host.id()) - .or_insert_with(|| (0, Ranges::new())); + .or_default(); + static INCREMENTAL_SPANS: std::sync::OnceLock = std::sync::OnceLock::new(); + let incremental_spans = *INCREMENTAL_SPANS.get_or_init(|| { + std::env::var_os("VICTORY_DESCRIPTOR_BUFFER_SPANS").is_some_and(|v| v == "1") + }); let changed = host.buffer_changes(); let slots = if *passes % 16 == 0 { ranges.clear(); + *span_index = None; host.buffer_slots() } else { changed @@ -2209,7 +2220,12 @@ impl State { let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); HEAP_PASS_PARTS[1].fetch_add(slots.len() as u64, Ordering::Relaxed); for (n, &index) in slots.iter().enumerate() { - ranges.remove(&index); + if let Some((shadow, from, to)) = ranges.remove(&index) + && let Some(spans) = span_index + && !spans.remove(std::sync::Arc::as_ptr(&shadow) as usize, index, from, to) + { + *span_index = None; + } let Some(handle) = heap.handle(index) else { continue; }; @@ -2240,18 +2256,32 @@ impl State { if host.shows(index, &shadow.buffer) == Some(false) { HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); } + if let Some(spans) = span_index { + spans.insert(std::sync::Arc::as_ptr(&shadow) as usize, index, &shadow, address, address + len); + } 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); - } + let spans = if incremental_spans { + span_index.get_or_insert_with(|| { + let mut spans = crate::descriptor::host::BufferSpanIndex::default(); + for (&slot, (shadow, from, to)) in ranges.iter() { + spans.insert(std::sync::Arc::as_ptr(shadow) as usize, slot, shadow, *from, *to); + } + spans + }).snapshot() + } else { + 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); + } + spans + }; 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. diff --git a/docs/descriptor-buffer-spans.md b/docs/descriptor-buffer-spans.md new file mode 100644 index 0000000000..8cb1757bb4 --- /dev/null +++ b/docs/descriptor-buffer-spans.md @@ -0,0 +1,9 @@ +# Incremental descriptor buffer unions (Kelvaroq 0055 subset) + +Source concept: https://github.com/stellarr-studio/kelvaroq/blob/1270c422adaef1e0f369f670138d8d29d8f6f4c3/native/patches/0055-descriptors.patch (GPL-3.0; Kelvaroq contributors). AI-assisted adaptation. + +Set VICTORY_DESCRIPTOR_BUFFER_SPANS=1 in a fresh process. In the existing unmarked buffer pass, retain each live backing buffer's minimum start and maximum end in a per-heap index, updated only for the descriptors revalidated by the existing scan. Preserve its authoritative slot map, full/partitioned revalidation, heap identity, dirty drain, refresh cadence and enclosing range semantics. On index mismatch rebuild from the authoritative map; full scans and epoch resets invalidate the index. The marked pass is unchanged and remains independently selectable. + +This does not skip unwatched bytes, relax dirty tracking or modify descriptor table cache keys. It reduces span aggregation from a walk of all live slots to a walk of distinct copies on unchanged passes, at the cost of ordered sets and additional retained metadata. Both modes issue the same enclosing ranges. Tests cover duplicate endpoints, shrinking, moving, deleting and 2048 mixed updates against a full-scan oracle. Local builds deferred during active benchmark; CI and live A/B required. No FPS claim. + +Upstream adaptation: the index is part of the stable heap-ID cache introduced by #1372. It resets on full scans, marked-pass resets and heap destruction; there is no partition-spread path in this baseline. CI on the independent port is pending.