From fe1b50bc7493a24270c7f5156723b325688047d5 Mon Sep 17 00:00:00 2001 From: gdemontalivet Date: Thu, 26 Nov 2026 13:14:59 +0000 Subject: [PATCH 1/3] fix(gpu): guard unmapped root views, sanitize 64-lane indirect draws, and defer GPU retirement --- crates/victory-gpu/src/compute.rs | 7 + crates/victory-gpu/src/draw.rs | 218 +++++++++- crates/victory-gpu/src/host.rs | 222 +++++++++- crates/victory-gpu/src/indirect-clamp.hlsl | 93 ++-- crates/victory-gpu/src/indirect.rs | 482 +++++++++++++++++---- crates/victory-gpu/src/list.rs | 37 +- crates/victory-gpu/src/placement.rs | 17 +- crates/victory-gpu/src/resource.rs | 1 + crates/victory-gpu/src/shadow.rs | 36 +- crates/victory-gpu/src/switch.rs | 22 +- 10 files changed, 992 insertions(+), 143 deletions(-) diff --git a/crates/victory-gpu/src/compute.rs b/crates/victory-gpu/src/compute.rs index 15af69f2..e86ba2d1 100644 --- a/crates/victory-gpu/src/compute.rs +++ b/crates/victory-gpu/src/compute.rs @@ -19,6 +19,9 @@ pub(crate) enum Param<'a> { Table(&'a [Range]), /// `count` 32-bit constants in `b{register}`. Constants { register: u32, count: u32 }, + /// A root constant buffer view in `b{register}, space{space}`. + #[cfg(test)] + Cbv { register: u32, space: u32 }, /// A root shader resource view in `t{register}, space{space}`. Srv { register: u32, space: u32 }, /// A root unordered access view in `u{register}`. @@ -161,6 +164,10 @@ pub(crate) fn root_signature(device: &ID3D12Device, params: &[Param]) -> Result< }, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }, + #[cfg(test)] + Param::Cbv { register, space } => { + descriptor(D3D12_ROOT_PARAMETER_TYPE_CBV, register, space) + } Param::Srv { register, space } => { descriptor(D3D12_ROOT_PARAMETER_TYPE_SRV, register, space) } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e774813a..7d7f2f69 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -875,15 +875,36 @@ impl State { } continue; } - let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) - else { - once!(slot, "a shader reads a root view the title did not set"); - continue; + let gpu = match self.roots_ref(compute).get(usize::from(slot)) { + Some(Root::View(address)) if *address != 0 => { + let found = root_view(list, *address, kind == 1, kind == 2); + if found.is_none() { + once!( + slot, + address = format_args!("{:#x}", *address), + "a shader uses a direct root view outside title memory" + ); + } + found + } + Some(Root::View(_)) => None, + _ => { + once!(slot, "a shader reads a root view the title did not set"); + None + } }; - let Some(gpu) = root_view(list, *address, kind == 1, kind == 2) else { - continue; + let Some(gpu) = gpu.or_else(|| { + let host = crate::host::host()?; + if kind == 2 { + host.sink_root_uav() + } else { + host.zero_root_read() + } + }) else { + not_run("no fallback buffer for a null or unmapped root view"); + return false; }; - // SAFETY: an open list; the address is in live memory. + // SAFETY: an open list; `gpu` lies in a live host buffer. unsafe { match (compute, kind) { (false, 0) => l.SetGraphicsRootConstantBufferView(param, gpu), @@ -4730,4 +4751,187 @@ void main(uint3 id : SV_DispatchThreadID) { assert!(state.host_targets.is_none()); list.close(); } + + /// Direct root CBV/SRV/UAV bindings (`stage.root_cbvs`, `stage.root_srvs`, + /// `stage.root_uavs`) bind zeroed/sink host buffers instead of leaving + /// `0x0` or a previous dispatch's stale GPU VA bound when a slot is null, + /// unset, or outside committed title memory, and shader writes into a null + /// root UAV never corrupt the shared zero-read fallback buffer. + #[test] + fn null_and_unmapped_direct_root_views_bind_safe_fallbacks() { + use victory_shader::emit::{Options, emit_with}; + use victory_shader::native::{ComputeIo, HwStage, NativeProgram, StageIo}; + use victory_shader::{Container, io, ir, resource, structure}; + + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + + const DIRECT_ROOT_HLSL: &str = r#" +cbuffer RootCbv : register(b0) { uint4 cbv_words; }; +StructuredBuffer root_srv : register(t0); +RWByteAddressBuffer sink_uav : register(u0); +RWByteAddressBuffer out_uav : register(u1); +[numthreads(1, 1, 1)] +void main() { + uint sum = cbv_words.x + root_srv[0]; + sink_uav.Store(0, 0xdeadbeefu); + out_uav.Store(0, sum ^ 0x5a5a0000u); +} +"#; + let params = [ + Param::Cbv { + register: 0, + space: 0, + }, + Param::Srv { + register: 0, + space: 0, + }, + Param::Uav { register: 0 }, + Param::Uav { register: 1 }, + ]; + let (root, pso) = crate::compute::pipeline(DIRECT_ROOT_HLSL, s!("direct_roots"), 0, ¶ms) + .expect("direct root view test pipeline"); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 4, + layout: Vec::new(), + used: Vec::new(), + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [1, 1, 1], + }), + code: 0xBF81_0000u32.to_le_bytes().to_vec(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let host_shader = emit_with( + &Container { parts: Vec::new() }, + &native, + &p, + &st, + &io, + &res, + Options::default(), + ) + .unwrap(); + let shader = crate::pipeline::Shader::for_test( + "compute", + crate::pipeline::Translated { + host: host_shader, + used: Vec::new(), + }, + ); + let hp = HostPipeline { + compute: true, + mesh: false, + pso, + root, + stages: vec![crate::pipeline::host::Stage { + shader, + user_data: None, + root_cbvs: vec![(0, 0)], + root_srvs: vec![(1, 1)], + root_uavs: vec![(2, 2), (3, 3)], + memory: None, + memory_dirty: None, + view_addresses: None, + }], + rectangles: false, + slots: 0, + inputs: Vec::new(), + name: "direct_roots_test".into(), + marks: None, + }; + + let cbv_buf = buffer(256); + let srv_buf = buffer(256); + let uav_sink_valid = buffer(256); + let out1 = buffer(256); + let out2 = buffer(256); + let out3 = buffer(256); + let (cbv_ptr, _) = crate::resource::buffer_bytes(cbv_buf).unwrap(); + let (srv_ptr, _) = crate::resource::buffer_bytes(srv_buf).unwrap(); + let (sink_ptr, _) = crate::resource::buffer_bytes(uav_sink_valid).unwrap(); + let (out1_ptr, _) = crate::resource::buffer_bytes(out1).unwrap(); + let (out2_ptr, _) = crate::resource::buffer_bytes(out2).unwrap(); + let (out3_ptr, _) = crate::resource::buffer_bytes(out3).unwrap(); + + // SAFETY: inside our 256-byte title buffers. + unsafe { + cbv_ptr.cast::().write_volatile(0x0011_0022); + srv_ptr.cast::().write_volatile(0x0033_0044); + sink_ptr.cast::().write_volatile(0); + out1_ptr.cast::().write_volatile(0); + out2_ptr.cast::().write_volatile(0); + out3_ptr.cast::().write_volatile(0); + } + + let list = host.new_list().unwrap(); + let mut state = State::default(); + + // Dispatch 1: valid non-zero CBV, SRV, and UAVs bind title shadow VAs. + state.set_view(true, 0, cbv_ptr as u64); + state.set_view(true, 1, srv_ptr as u64); + state.set_view(true, 2, sink_ptr as u64); + state.set_view(true, 3, out1_ptr as u64); + assert!(state.bind(&list, &hp, true)); + // SAFETY: bound compute pipeline and root views on open `list`. + unsafe { list.list.Dispatch(1, 1, 1) }; + + // Dispatch 2 on the same command list: slot 0 = null (`0`), slot 1 = + // invalid address (`0x1000`), slot 2 = null UAV (`0`). Without the fix, + // `continue;` left Dispatch 1's `cbv_buf` / `srv_buf` / `uav_sink_valid` + // VAs bound (or faulted on `0x0`). + state.set_view(true, 0, 0); + state.set_view(true, 1, 0x1000); + state.set_view(true, 2, 0); + state.set_view(true, 3, out2_ptr as u64); + assert!(state.bind(&list, &hp, true)); + // SAFETY: fallback buffers bound on open `list`. + unsafe { list.list.Dispatch(1, 1, 1) }; + + // Dispatch 3: unset slot 0 (`State::default()`), out-of-user-space + // slot 1 (`1 << 47`), unset slot 2 -> `zero_root_read` must still read + // 0 despite Dispatch 2 writing `0xdeadbeef` to `sink_root_uav`. + let mut fresh_state = State::default(); + fresh_state.set_view(true, 1, 1u64 << 47); + fresh_state.set_view(true, 3, out3_ptr as u64); + assert!(fresh_state.bind(&list, &hp, true)); + // SAFETY: fallback buffers bound on open `list`. + unsafe { list.list.Dispatch(1, 1, 1) }; + + list.close(); + host.execute(&[&list]); + + // SAFETY: `execute` waited for the GPU fence and completed copy-back. + unsafe { + assert_eq!( + out1_ptr.cast::().read_volatile(), + (0x0011_0022 + 0x0033_0044) ^ 0x5a5a_0000, + "valid direct root views ran" + ); + assert_eq!( + sink_ptr.cast::().read_volatile(), + 0xdead_beef, + "Dispatch 2 did not overwrite Dispatch 1's UAV after slot 2 became null, and Dispatch 1 wrote 0xdeadbeef" + ); + assert_eq!( + out2_ptr.cast::().read_volatile(), + 0x5a5a_0000, + "null CBV + unmapped SRV read zeros instead of stale Dispatch 1 VAs" + ); + assert_eq!( + out3_ptr.cast::().read_volatile(), + 0x5a5a_0000, + "null UAV writes into sink_root_uav never corrupt zero_root_read" + ); + } + assert_eq!(host.log_messages(), None, "no D3D12 debug errors"); + } } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5d7ad469..1f835e5b 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -89,6 +89,10 @@ pub(crate) struct Host { messages: Option, next_rtv: AtomicU32, presenter: Mutex, + /// Zero-filled 64 KiB read fallback for null or unmapped direct root CBVs/SRVs. + zero_root_read: OnceLock>, + /// Isolated 64 KiB write sink for null or unmapped direct root UAVs. + sink_root_uav: OnceLock>, } // SAFETY: D3D12 devices, queues, fences and descriptor heaps are @@ -386,6 +390,8 @@ fn create() -> windows::core::Result { messages, next_rtv: AtomicU32::new(0), presenter: Mutex::new(Presentation::default()), + zero_root_read: OnceLock::new(), + sink_root_uav: OnceLock::new(), }) } } @@ -2028,6 +2034,7 @@ impl Host { } let _ = (i, started); } + SUBMISSIONS_DONE.store(*submitted, Ordering::Release); let _ = &firsts; let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); @@ -2216,9 +2223,12 @@ impl Host { } } // The submission has run and the next waits for our lock. Host - // copies the title gave up meanwhile may have their last holder here. - release_retired(); - release_later(Box::new((batch, back, withheld, heaps))); + // copies and retired GPU objects stay alive across `bury_lag` + // submissions (~2 frames by default) so D3DMetal/AGX never faults on + // recently retired buffer or texture virtual addresses. + let done = *submitted; + retire_any((batch, back, withheld, heaps)); + advance_retired(done); self.log_messages(); // A listed frame: what this submission's lists drew, as it is now // (the dumps submit lists of their own). @@ -3286,19 +3296,20 @@ impl HostList { (s.current, s.used) = (0, 0); spent }; - // Each release is a kernel call, as in [`release_later`]. + // Each release is a kernel call, deferred across `bury_lag` submissions. if !spent.is_empty() { - release_later(Box::new(spent)); + retire_any(spent); } } - /// The host address of the list's indirect-work budget, zeroed at each + /// The host address of the list's indirect-work budget (plus 64 scratch + /// dwords at bytes 64..320 for the 64-lane clamp), zeroed at each /// submission of the list from the first use after a reset on. pub(crate) fn budget(&self) -> Option { let (buffer, data) = self .budget .get_or_init(|| { - let (b, d) = host()?.shared_buffer(256)?; + let (b, d) = host()?.shared_buffer(512)?; Some((b, d as usize)) }) .as_ref()?; @@ -4815,23 +4826,139 @@ impl Host { } } } + + /// 256-byte-aligned GPU VA of a shared zero-filled 64 KiB buffer bound + /// in place of null, unset, or unmapped direct root CBVs and SRVs. + pub(crate) fn zero_root_read(&self) -> Option { + self.zero_root_read + .get_or_init(|| { + let bytes = (crate::watch::PAGE + 256) as u64; + let (buffer, data) = self.shared_buffer(bytes)?; + name(&buffer, || "null root read".into()); + // SAFETY: `data` points to `bytes` mapped bytes; `buffer` is live. + let gpu = unsafe { + std::ptr::write_bytes(data, 0, bytes as usize); + buffer.GetGPUVirtualAddress().next_multiple_of(256) + }; + Some((buffer, gpu)) + }) + .as_ref() + .map(|&(_, gpu)| gpu) + } + + /// 256-byte-aligned GPU VA of an isolated 64 KiB throwaway buffer bound + /// in place of null, unset, or unmapped direct root UAVs so shader writes + /// never fault or corrupt [`Host::zero_root_read`]. + pub(crate) fn sink_root_uav(&self) -> Option { + self.sink_root_uav + .get_or_init(|| { + let bytes = (crate::watch::PAGE + 256) as u64; + let (buffer, data) = self.shared_buffer(bytes)?; + name(&buffer, || "null root uav sink".into()); + // SAFETY: `data` points to `bytes` mapped bytes; `buffer` is live. + let gpu = unsafe { + std::ptr::write_bytes(data, 0, bytes as usize); + buffer.GetGPUVirtualAddress().next_multiple_of(256) + }; + Some((buffer, gpu)) + }) + .as_ref() + .map(|&(_, gpu)| gpu) + } } -/// Host resources that view heap slots stopped viewing while a submission -/// may have been running ([`retire`]). -static RETIRED: Mutex> = Mutex::new(Vec::new()); +/// Completed host submission count (`Host::execute`). +static SUBMISSIONS_DONE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -/// Keeps `resource` alive until the GPU work running now (or the next -/// submission's) has run: title threads rewrite view heap slots while the -/// GPU runs, and a shader that took the old descriptor still reads what it -/// views. +/// Number of completed host submissions so far. +pub(crate) fn submissions_done() -> u64 { + SUBMISSIONS_DONE.load(Ordering::Acquire) +} + +/// How many host submissions a retired GPU object or recycled command list +/// stays alive after the submission current when it was retired (`16` ~= 2 +/// frames; `VICTORY_BURY_LAG=0` drops right after the current submission). +pub(crate) fn bury_lag() -> u64 { + #[cfg(test)] + if let Some(lag) = TEST_BURY_LAG.with(std::cell::Cell::get) { + return lag; + } + static LAG: OnceLock = OnceLock::new(); + *LAG.get_or_init(|| { + std::env::var("VICTORY_BURY_LAG") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(16) + }) +} + +#[cfg(test)] +thread_local! { + static TEST_BURY_LAG: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +pub(crate) fn with_bury_lag(lag: u64, f: impl FnOnce() -> R) -> R { + struct Guard(Option); + impl Drop for Guard { + fn drop(&mut self) { + TEST_BURY_LAG.with(|cell| cell.set(self.0)); + } + } + let prev = TEST_BURY_LAG.with(|cell| cell.replace(Some(lag))); + let _guard = Guard(prev); + f() +} + +struct Retired(#[allow(dead_code)] Box); + +/// Host GPU objects (`ID3D12Resource`, `ID3D12Heap`, submission batches) kept +/// alive across [`bury_lag`] submissions so D3DMetal/AGX never faults on +/// recently retired virtual addresses. +static RETIRED: Mutex> = + Mutex::new(std::collections::VecDeque::new()); + +/// Keeps `resource` alive until [`bury_lag`] host submissions after now. pub(crate) fn retire(resource: ID3D12Resource) { - RETIRED.lock().unwrap_or_else(|e| e.into_inner()).push(resource); + retire_any(resource); +} + +/// Keeps `object` alive until [`bury_lag`] host submissions after now, then +/// drops it on the background release thread. +pub(crate) fn retire_any(object: T) { + let at = submissions_done(); + RETIRED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push_back((at, Retired(Box::new(object)))); } -/// After a submission has run, with none running: the retired resources go. +/// Releases retired objects whose [`bury_lag`] window has elapsed at +/// `done_submission`. +fn advance_retired(done_submission: u64) { + let lag = bury_lag(); + let ready: Vec<(u64, Retired)> = { + let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + let n = retired + .iter() + .take_while(|(at, _)| at.saturating_add(lag) <= done_submission) + .count(); + if n == 0 { + return; + } + retired.drain(..n).collect() + }; + release_later(Box::new(ready)); +} + +/// Immediately releases all retired objects (tests). +#[cfg(test)] pub(crate) fn release_retired() { - let retired = std::mem::take(&mut *RETIRED.lock().unwrap_or_else(|e| e.into_inner())); + let retired: Vec<(u64, Retired)> = RETIRED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .drain(..) + .collect(); if !retired.is_empty() { release_later(Box::new(retired)); } @@ -5789,6 +5916,67 @@ float4 ps(float4 pos : SV_Position) : SV_Target { "a draw on the new queue runs whole" ); } + + #[test] + fn bury_lag_retains_retired_resources_across_submissions() { + use windows::core::Interface; + let Some(host) = super::host() else { + return; // no host GPU here + }; + let references = |b: &ID3D12Resource| { + // SAFETY: a live COM object; one reference taken and given back. + unsafe { + let raw = b.as_raw(); + let unknown = &*(raw as *const *const windows::core::IUnknown_Vtbl); + ((**unknown).AddRef)(raw); + ((**unknown).Release)(raw) + } + }; + let wait_released = |b: &ID3D12Resource| { + let since = std::time::Instant::now(); + while references(b) > 1 && since.elapsed() < std::time::Duration::from_secs(5) { + std::thread::yield_now(); + } + references(b) + }; + + let (buf_lag, _) = host.shared_buffer(256).unwrap(); + let list = host.new_list().unwrap(); + list.close(); + super::with_bury_lag(3, || { + let _quiet = host.quiet(); + super::retire(buf_lag.clone()); + assert!(references(&buf_lag) >= 2, "held by retirement ring"); + drop(_quiet); + + for step in 1..3 { + list.reset(); + list.close(); + host.execute(&[&list]); + assert!( + references(&buf_lag) >= 2, + "still retained after {step} of 3 lag submissions" + ); + } + list.reset(); + list.close(); + host.execute(&[&list]); + assert_eq!(wait_released(&buf_lag), 1, "released once 3 submissions passed"); + }); + + let (buf_immediate, _) = host.shared_buffer(256).unwrap(); + super::with_bury_lag(0, || { + super::retire(buf_immediate.clone()); + list.reset(); + list.close(); + host.execute(&[&list]); + assert_eq!( + wait_released(&buf_immediate), + 1, + "VICTORY_BURY_LAG=0 releases right after the submission" + ); + }); + } } /// The pipelines of the lists the last submission ran, for a hang's log line diff --git a/crates/victory-gpu/src/indirect-clamp.hlsl b/crates/victory-gpu/src/indirect-clamp.hlsl index ca26baf3..a0cffe67 100644 --- a/crates/victory-gpu/src/indirect-clamp.hlsl +++ b/crates/victory-gpu/src/indirect-clamp.hlsl @@ -1,50 +1,71 @@ #define RS "RootConstants(num32BitConstants=5, b0), SRV(t0), UAV(u1), UAV(u0), SRV(t1)" // `widest`: the most groups in x a dispatch runs (`indirect::widest`). -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint counted; uint widest; }; +cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint flags; uint widest; }; // The title's records, read only; the clamped ones go to the list's own. ByteAddressBuffer args : register(t0); RWByteAddressBuffer dest : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. RWByteAddressBuffer budget : register(u1); -// The title's record count: read only if `counted`. +// The title's record count: read only if `flags & 1`. ByteAddressBuffer countWord : register(t1); static const uint BUDGET = 1u << 27; +// Draws of MOST_DRAW vertices/indices per instance or more are unfilled slots. +static const uint MOST_DRAW = 1u << 23; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; // Clamps the record at `at` into `dest`; its cost. uint clamped(uint at) { uint cost; - if (kind <= 1) { + uint base_bytes; + if (kind <= 1u) { // Draws: vertex or index count, then instances. - uint count = min(args.Load(at), 1u << 24); - uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); + uint raw_count = args.Load(at); + uint raw_instances = args.Load(at + 4u); + uint count = raw_count; + uint instances = 0u; + if (raw_count >= MOST_DRAW) { + count = 0u; + } else { + instances = min(raw_instances, (1u << 26) / max(count, 1u)); + } cost = count * instances; dest.Store2(at, uint2(count, instances)); // The rest of the record as it is: first vertex and instance (4 words // in all), or first index, base vertex and first instance (5). - if (kind == 1) { - dest.Store3(at + 8, args.Load3(at + 8)); + if (kind == 1u) { + dest.Store3(at + 8u, args.Load3(at + 8u)); + base_bytes = 20u; } else { - dest.Store2(at + 8, args.Load2(at + 8)); + dest.Store2(at + 8u, args.Load2(at + 8u)); + base_bytes = 16u; } - } else if (kind == 2) { + } else if (kind == 2u) { uint3 g = args.Load3(at); // Up to `widest` groups in x run as asked; a wider record is cut to // D3D12's 65,535 as before. g = uint3(g.x <= widest ? g.x : 65535u, min(g.y, 65535u), min(g.z, 65535u)); // x * y fits 32 bits where it is looked at; the whole count may not. - if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) { - g = uint3(0, 0, 0); + if ((g.y != 0u && g.x > GROUPS / g.y) || (g.z != 0u && g.x * g.y > GROUPS / g.z)) { + g = uint3(0u, 0u, 0u); } - cost = g.x * g.y * g.z * 64; + cost = g.x * g.y * g.z * 64u; dest.Store3(at, g); + base_bytes = 12u; } else { - // Mesh dispatches: the console's are one-dimensional. - uint3 g = args.Load3(at); - g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); - cost = g.x * g.y * g.z * 128; + // Mesh dispatches: the console's are one-dimensional; unfilled slots + // (`> 65535`, e.g. `0xffffffff`) run empty instead of clamping to 65535. + uint3 raw_g = args.Load3(at); + uint3 g = uint3(raw_g.x, min(raw_g.y, 1u), min(raw_g.z, 1u)); + if (raw_g.x > 65535u) { + g = uint3(0u, 0u, 0u); + } + cost = g.x * g.y * g.z * 128u; dest.Store3(at, g); + base_bytes = 12u; + } + for (uint extra = base_bytes; extra < stride; extra += 4u) { + dest.Store(at + extra, args.Load(at + extra)); } return cost; } @@ -58,9 +79,9 @@ groupshared uint costs[64]; [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint lane : SV_GroupIndex) { - uint left = 0; - if (lane == 0) { - left = BUDGET - min(budget.Load(0), BUDGET); + uint left = 0u; + if (lane == 0u) { + left = BUDGET - min(budget.Load(0u), BUDGET); } // ExecuteIndirect runs min(max, count) records: no others are clamped or // charged. The loop still counts tiles up to `records`, a constant, as @@ -68,37 +89,41 @@ void main(uint lane : SV_GroupIndex) { // in every lane, and barriers need that; tiles past `walked` only wait // at them. uint walked = records; - if (counted != 0) { - walked = min(records, countWord.Load(0)); + if ((flags & 1u) != 0u) { + walked = min(records, countWord.Load(0u)); } - for (uint tile = 0; tile < records / 64 + min(records % 64, 1u); tile++) { - uint record = tile * 64 + lane; + uint take_rest = flags & 2u; + for (uint tile = 0u; tile < (records + 63u) / 64u; tile++) { + uint record = tile * 64u + lane; uint at = record * stride; - uint cost = 0; + uint cost = 0u; if (record < walked) { cost = clamped(at); } costs[lane] = cost; GroupMemoryBarrierWithGroupSync(); - if (lane == 0 && tile * 64 < walked) { - for (uint i = 0; i < 64; i++) { + if (lane == 0u && tile * 64u < walked) { + for (uint i = 0u; i < 64u; i++) { if (costs[i] > left) { - // The first record that does not fit takes what is - // left, so those after it run empty too. costs[i] = PAST; - left = 0; + if (take_rest != 0u) { + left = 0u; + } } else { left -= costs[i]; } } } GroupMemoryBarrierWithGroupSync(); - if (costs[lane] == PAST) { - // Draws keep their layout with no vertices; groups become zero. - dest.Store(at, 0); + if (record < walked && costs[lane] == PAST) { + if (kind <= 1u) { + dest.Store2(at, uint2(0u, 0u)); + } else { + dest.Store3(at, uint3(0u, 0u, 0u)); + } } } - if (lane == 0) { - budget.Store(0, BUDGET - left); + if (lane == 0u) { + budget.Store(0u, BUDGET - left); } } diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 4f85ff16..b2b2d9e6 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -9,15 +9,18 @@ //! Each list also has a budget (2^27 vertex instances or threads, groups //! counted as 64 threads, mesh groups as 128): records past it run empty, //! so a list of thousands of garbage records cannot run for seconds -//! either. +//! either. By default (`VICTORY_INDIRECT_REST=0`), a record that does not +//! fit in the remaining budget runs empty without taking the rest, so +//! smaller draws after it still run. //! //! With a count buffer ExecuteIndirect runs only the first min(max, count) //! records, so the clamp reads the count word and stops there: the maximum //! can be far above the count, and the records between never run. //! -//! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 -//! groups per dimension except in x where [`widest`] allows more, 2^20 -//! per dispatch, one-dimensional mesh dispatches, the budget) cut +//! shortcut: the bounds (below 2^23 vertices per instance, 2^26 vertex +//! instances, 65,535 groups per dimension except in x where [`widest`] +//! allows more, 2^20 per dispatch, one-dimensional mesh dispatches up to +//! 65,535 groups, the budget) cut //! legitimate work beyond them; raise them if the title needs more. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; @@ -55,8 +58,9 @@ pub(crate) fn widest() -> u32 { struct Clamp { root: ID3D12RootSignature, pso: ID3D12PipelineState, - /// Built from [`WORDS_SOURCE`], which also reads the budget as words - /// through root view 5 (the other views are those of [`SOURCE`]). + /// Built from [`WORDS_SOURCE`] or [`WORDS_1_SOURCE`], which also reads + /// the budget as words through root view 5 (the other views are those of + /// [`SOURCE`]). words: bool, } @@ -87,10 +91,45 @@ fn make() -> windows::core::Result { } Err(e) => tracing::warn!(error = %e, "precompiled argument clamp unavailable"), } - make_fxc().or_else(|e| { - tracing::info!(error = %e, "argument clamp: building the one-thread form"); - make_words() - }) + make_fxc() + .or_else(|e| { + tracing::info!(error = %e, "argument clamp: building the 64-lane words form"); + make_words() + }) + .or_else(|e| { + tracing::info!(error = %e, "argument clamp: building the one-thread words form"); + make_words_1() + }) +} + +/// Whether a record that does not fit in what is left of its list's budget +/// takes the rest (`VICTORY_INDIRECT_REST=1`), emptying every record after +/// it. Off (`0`) by default so one oversized record zeroes only itself. +fn indirect_rest() -> bool { + #[cfg(test)] + if let Some(rest) = TEST_INDIRECT_REST.with(std::cell::Cell::get) { + return rest; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| crate::switch::on("VICTORY_INDIRECT_REST")) +} + +#[cfg(test)] +thread_local! { + static TEST_INDIRECT_REST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn with_indirect_rest(rest: bool, f: impl FnOnce() -> R) -> R { + struct Guard(Option); + impl Drop for Guard { + fn drop(&mut self) { + TEST_INDIRECT_REST.with(|cell| cell.set(self.0)); + } + } + let prev = TEST_INDIRECT_REST.with(|cell| cell.replace(Some(rest))); + let _guard = Guard(prev); + f() } /// The clamp compiled by DXC at build time. D3DMetal finds a shader by the @@ -109,46 +148,177 @@ fn precompiled() -> windows::core::Result { from_bytes(&bytes) } -/// The clamp for Wine's HLSL compiler (vkd3d-shader), which has no `Load` -/// on `RWByteAddressBuffer`, no stores to indexed group-shared memory and -/// no `[RootSignature]`: [`SOURCE`]'s clamp, read through structured views -/// of the same buffers, and one thread charging the records in order -/// instead of a group of 64. The results are the same. +/// The 64-lane clamp for Wine's HLSL compiler (vkd3d-shader), which has no +/// `Load` on `RWByteAddressBuffer`, no stores to indexed group-shared memory +/// and no `[RootSignature]`: [`SOURCE`]'s 64-lane tile clamp, read through +/// structured views of the same buffers, with per-lane scratch slots in +/// `budget` bytes `64..320` (`budgetWords[16..80]`). const WORDS_SOURCE: &str = r#" -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint counted; uint widest; }; +cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint flags; uint widest; }; StructuredBuffer argWords : register(t0); RWByteAddressBuffer budget : register(u1); RWByteAddressBuffer dest : register(u0); StructuredBuffer countWords : register(t1); RWStructuredBuffer budgetWords : register(u2); static const uint BUDGET = 1u << 27; +static const uint MOST_DRAW = 1u << 23; static const uint GROUPS = 1u << 20; -uint3 load3(uint at) { return uint3(argWords[at / 4], argWords[at / 4 + 1], argWords[at / 4 + 2]); } +static const uint PAST = 0xffffffffu; +uint3 load3(uint at) { return uint3(argWords[at / 4u], argWords[at / 4u + 1u], argWords[at / 4u + 2u]); } uint clamped(uint at) { uint cost; - if (kind <= 1) { - uint count = min(argWords[at / 4], 1u << 24); - uint instances = min(argWords[at / 4 + 1], (1u << 26) / max(count, 1u)); + uint base_bytes; + if (kind <= 1u) { + uint raw_count = argWords[at / 4u]; + uint raw_instances = argWords[at / 4u + 1u]; + uint count = raw_count; + uint instances = 0u; + if (raw_count >= MOST_DRAW) { + count = 0u; + } else { + instances = min(raw_instances, (1u << 26) / max(count, 1u)); + } cost = count * instances; dest.Store2(at, uint2(count, instances)); - if (kind == 1) { - dest.Store3(at + 8, uint3(argWords[at / 4 + 2], argWords[at / 4 + 3], argWords[at / 4 + 4])); + if (kind == 1u) { + dest.Store3(at + 8u, uint3(argWords[at / 4u + 2u], argWords[at / 4u + 3u], argWords[at / 4u + 4u])); + base_bytes = 20u; } else { - dest.Store2(at + 8, uint2(argWords[at / 4 + 2], argWords[at / 4 + 3])); + dest.Store2(at + 8u, uint2(argWords[at / 4u + 2u], argWords[at / 4u + 3u])); + base_bytes = 16u; } - } else if (kind == 2) { + } else if (kind == 2u) { uint3 g = load3(at); g = uint3(g.x <= widest ? g.x : 65535u, min(g.y, 65535u), min(g.z, 65535u)); - if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) { - g = uint3(0, 0, 0); + if ((g.y != 0u && g.x > GROUPS / g.y) || (g.z != 0u && g.x * g.y > GROUPS / g.z)) { + g = uint3(0u, 0u, 0u); } - cost = g.x * g.y * g.z * 64; + cost = g.x * g.y * g.z * 64u; dest.Store3(at, g); + base_bytes = 12u; } else { + uint3 raw_g = load3(at); + uint3 g = uint3(raw_g.x, min(raw_g.y, 1u), min(raw_g.z, 1u)); + if (raw_g.x > 65535u) { + g = uint3(0u, 0u, 0u); + } + cost = g.x * g.y * g.z * 128u; + dest.Store3(at, g); + base_bytes = 12u; + } + for (uint extra = base_bytes; extra < stride; extra += 4u) { + dest.Store(at + extra, argWords[(at + extra) / 4u]); + } + return cost; +} +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + uint lane = id.x; + uint left = 0u; + if (lane == 0u) { + left = BUDGET - min(budgetWords[0], BUDGET); + } + uint walked = records; + if ((flags & 1u) != 0u) { + walked = min(records, countWords[0]); + } + uint take_rest = flags & 2u; + uint tiles = (records + 63u) / 64u; + for (uint tile = 0u; tile < tiles; tile++) { + uint record = tile * 64u + lane; + uint at = record * stride; + uint cost = 0u; + if (record < walked) { + cost = clamped(at); + } + budget.Store(64u + lane * 4u, cost); + AllMemoryBarrierWithGroupSync(); + if (lane == 0u && tile * 64u < walked) { + for (uint i = 0u; i < 64u; i++) { + uint c = budgetWords[16u + i]; + if (c > left) { + budget.Store(64u + i * 4u, PAST); + if (take_rest != 0u) { + left = 0u; + } + } else { + left -= c; + } + } + } + AllMemoryBarrierWithGroupSync(); + if (record < walked && budgetWords[16u + lane] == PAST) { + if (kind <= 1u) { + dest.Store2(at, uint2(0u, 0u)); + } else { + dest.Store3(at, uint3(0u, 0u, 0u)); + } + } + if (tile + 1u < tiles) { + AllMemoryBarrierWithGroupSync(); + } + } + if (lane == 0u) { + budget.Store(0u, BUDGET - left); + } +} +"#; + +/// One-thread fallback for compilers that refuse [`WORDS_SOURCE`]. +const WORDS_1_SOURCE: &str = r#" +cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint flags; uint widest; }; +StructuredBuffer argWords : register(t0); +RWByteAddressBuffer budget : register(u1); +RWByteAddressBuffer dest : register(u0); +StructuredBuffer countWords : register(t1); +RWStructuredBuffer budgetWords : register(u2); +static const uint BUDGET = 1u << 27; +static const uint MOST_DRAW = 1u << 23; +static const uint GROUPS = 1u << 20; +uint3 load3(uint at) { return uint3(argWords[at / 4u], argWords[at / 4u + 1u], argWords[at / 4u + 2u]); } +uint clamped(uint at) { + uint cost; + uint base_bytes; + if (kind <= 1u) { + uint raw_count = argWords[at / 4u]; + uint raw_instances = argWords[at / 4u + 1u]; + uint count = raw_count; + uint instances = 0u; + if (raw_count >= MOST_DRAW) { + count = 0u; + } else { + instances = min(raw_instances, (1u << 26) / max(count, 1u)); + } + cost = count * instances; + dest.Store2(at, uint2(count, instances)); + if (kind == 1u) { + dest.Store3(at + 8u, uint3(argWords[at / 4u + 2u], argWords[at / 4u + 3u], argWords[at / 4u + 4u])); + base_bytes = 20u; + } else { + dest.Store2(at + 8u, uint2(argWords[at / 4u + 2u], argWords[at / 4u + 3u])); + base_bytes = 16u; + } + } else if (kind == 2u) { uint3 g = load3(at); - g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); - cost = g.x * g.y * g.z * 128; + g = uint3(g.x <= widest ? g.x : 65535u, min(g.y, 65535u), min(g.z, 65535u)); + if ((g.y != 0u && g.x > GROUPS / g.y) || (g.z != 0u && g.x * g.y > GROUPS / g.z)) { + g = uint3(0u, 0u, 0u); + } + cost = g.x * g.y * g.z * 64u; dest.Store3(at, g); + base_bytes = 12u; + } else { + uint3 raw_g = load3(at); + uint3 g = uint3(raw_g.x, min(raw_g.y, 1u), min(raw_g.z, 1u)); + if (raw_g.x > 65535u) { + g = uint3(0u, 0u, 0u); + } + cost = g.x * g.y * g.z * 128u; + dest.Store3(at, g); + base_bytes = 12u; + } + for (uint extra = base_bytes; extra < stride; extra += 4u) { + dest.Store(at + extra, argWords[(at + extra) / 4u]); } return cost; } @@ -156,26 +326,39 @@ uint clamped(uint at) { void main() { uint left = BUDGET - min(budgetWords[0], BUDGET); uint walked = records; - if (counted != 0) { + if ((flags & 1u) != 0u) { walked = min(records, countWords[0]); } - for (uint record = 0; record < walked; record++) { + uint take_rest = flags & 2u; + for (uint record = 0u; record < walked; record++) { uint at = record * stride; uint cost = clamped(at); if (cost > left) { - // The first record that does not fit takes what is left, so - // those after it run empty too. - dest.Store(at, 0); - left = 0; + if (kind <= 1u) { + dest.Store2(at, uint2(0u, 0u)); + } else { + dest.Store3(at, uint3(0u, 0u, 0u)); + } + if (take_rest != 0u) { + left = 0u; + } } else { left -= cost; } } - budget.Store(0, BUDGET - left); + budget.Store(0u, BUDGET - left); } "#; fn make_words() -> windows::core::Result { + make_words_from(WORDS_SOURCE) +} + +fn make_words_1() -> windows::core::Result { + make_words_from(WORDS_1_SOURCE) +} + +fn make_words_from(source: &str) -> windows::core::Result { use crate::compute::Param; let params = [ Param::Constants { register: 0, count: 5 }, @@ -185,7 +368,7 @@ fn make_words() -> windows::core::Result { Param::Srv { register: 1, space: 0 }, Param::Uav { register: 2 }, ]; - let (root, pso) = crate::compute::pipeline(WORDS_SOURCE, s!("clamp"), 0, ¶ms)?; + let (root, pso) = crate::compute::pipeline(source, s!("clamp"), 0, ¶ms)?; Ok(Clamp { root, pso, words: true }) } @@ -292,7 +475,8 @@ fn bound_with( } let out = list.arguments(u64::from(stride) * u64::from(records.max(1)))?; let l = &list.list; - let constants = [kind, stride, records, u32::from(count.is_some()), widest()]; + let flags = u32::from(count.is_some()) | (u32::from(indirect_rest()) << 1); + let constants = [kind, stride, records, flags, widest()]; // SAFETY: an open list; our root signature, pipeline and buffers, and // title buffers' copies the caller's list holds. unsafe { @@ -344,27 +528,24 @@ pub(crate) fn done(list: &HostList, arguments: &ID3D12Resource) { #[cfg(test)] mod tests { - /// The clamp compiles with the system's compiler and the host takes it. + /// The clamp compiles with the system's compiler (including both 64-lane + /// and 1-lane words forms) and the host takes it. #[test] fn argument_clamp_builds() { if super::host().is_none() { return; // no host GPU here } assert!(super::clamp().is_some()); + assert!(super::make_words().is_ok()); + assert!(super::make_words_1().is_ok()); } /// Every word the clamp `c` writes for `records` records of `kind` made /// from `seed` by a small generator, in one list with no count buffer. /// `None` without a host GPU. - #[cfg(victory_dxc_clamp)] - fn clamp_all(c: &super::Clamp, kind: u32, seed: u32, records: u32) -> Option> { + fn clamp_all(c: &super::Clamp, kind: u32, stride_words: usize, seed: u32, records: u32) -> Option> { let host = super::host()?; - let per = match kind { - 0 => 4, - 1 => 5, - _ => 3, - }; - let all = per * records as usize; + let all = stride_words * records as usize; let (buffer, data) = host.shared_buffer(all as u64 * 4 + 16).unwrap(); let data = data.cast::(); let list = host.new_list().unwrap(); @@ -374,11 +555,15 @@ mod tests { unsafe { for at in 0..all { state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - // Mostly small values, now and then a wild one. - let word = if state >> 28 == 0 { state } else { (state >> 8) % 9000 }; + // Mostly small values, now and then a wild or all-ones one. + let word = match state >> 28 { + 0 => state, + 1 => u32::MAX, + _ => (state >> 8) % 9000, + }; data.add(at).write_volatile(word); } - let spec = (kind, per as u32 * 4, records); + let spec = (kind, stride_words as u32 * 4, records); let out = super::bound_with(c, &list, buffer.GetGPUVirtualAddress(), spec, None).unwrap(); super::done(&list, &out); list.close(); @@ -403,13 +588,41 @@ mod tests { assert!(!precompiled.words); assert!(!super::clamp().expect("argument clamp").words); let reference = super::make_fxc().or_else(|_| super::make_words()).expect("the existing clamp"); - for (kind, seed, records) in [(0, 1, 200), (1, 2, 200), (2, 3, 130), (10, 4, 70), (0, 5, 3)] { - let new = clamp_all(&precompiled, kind, seed, records).unwrap(); - let old = clamp_all(&reference, kind, seed, records).unwrap(); + for (kind, per, seed, records) in [(0, 4, 1, 200), (1, 5, 2, 200), (2, 3, 3, 130), (10, 3, 4, 70), (0, 8, 5, 135)] { + let new = clamp_all(&precompiled, kind, per, seed, records).unwrap(); + let old = clamp_all(&reference, kind, per, seed, records).unwrap(); assert_eq!(new, old, "kind {kind}, {records} records"); } } + /// The 64-lane `WORDS_SOURCE` clamp and the 1-lane `WORDS_1_SOURCE` + /// fallback produce identical words across multi-tile batches and padded + /// strides, under both `VICTORY_INDIRECT_REST=0` and `=1`. + #[test] + fn words_64_lane_matches_1_lane_across_tiles_and_strides() { + if super::host().is_none() { + return; // no host GPU here + } + let wide = super::make_words().expect("64-lane words clamp"); + let single = super::make_words_1().expect("1-lane words clamp"); + for rest in [false, true] { + super::with_indirect_rest(rest, || { + for (kind, per, seed, records) in [ + (0, 4, 11, 150), + (0, 8, 12, 135), + (1, 5, 13, 140), + (2, 3, 14, 130), + (10, 3, 15, 145), + (10, 8, 16, 132), + ] { + let a = clamp_all(&wide, kind, per, seed, records).unwrap(); + let b = clamp_all(&single, kind, per, seed, records).unwrap(); + assert_eq!(a, b, "rest {rest}, kind {kind}, stride_words {per}, records {records}"); + } + }); + } + } + /// Clamps `records` records of `kind`, filled by repeating `words`, /// `calls` times in one list: each record's first word in the list's /// argument buffer after (zero when it runs empty). The title's copy, @@ -468,16 +681,119 @@ mod tests { } } - /// Rejected records do not wrap the budget: of 128 garbage draws (2^26 + /// Unfilled draw records (`>= 1 << 23` vertices/indices) and unfilled + /// mesh dispatch records (`> 65535` groups, including `0xffffffff`) are + /// zeroed with trailing words preserved and spend zero budget. + #[test] + fn unfilled_draw_and_mesh_records_run_empty_without_spending_budget() { + let Some(host) = super::host() else { + return; // no host GPU here + }; + // 80 draw records (`stride = 32` bytes = 8 words): 76 unfilled + // (`1 << 23` and `u32::MAX`) followed by 4 valid records. + const COUNT: usize = 80; + let (draw_buf, draw_ptr) = host.shared_buffer((COUNT * 32) as u64).unwrap(); + let (mesh_buf, mesh_ptr) = host.shared_buffer((COUNT * 32) as u64).unwrap(); + // SAFETY: our mapped buffers, written before execution and read after. + unsafe { + let draws = std::slice::from_raw_parts_mut(draw_ptr.cast::<[u32; 8]>(), COUNT); + for (i, d) in draws.iter_mut().enumerate() { + let k = i as u32; + let head = match i { + 0..=37 => [u32::MAX, u32::MAX], + 38..=75 => [1 << 23, 4], + 76 => [(1 << 23) - 1, 1], + _ => [12, 2], + }; + *d = [head[0], head[1], 100 + k, 200 + k, 0xa000 + k, 0xb000 + k, 0xc000 + k, 0xd000 + k]; + } + let meshes = std::slice::from_raw_parts_mut(mesh_ptr.cast::<[u32; 8]>(), COUNT); + for (i, m) in meshes.iter_mut().enumerate() { + let k = i as u32; + let gx = match i { + 0..=37 => u32::MAX, + 38..=75 => 65_536, + 76 => 65_535, + _ => 7, + }; + *m = [gx, 9, 5, 0x1000 + k, 0x2000 + k, 0x3000 + k, 0x4000 + k, 0x5000 + k]; + } + + let list = host.new_list().unwrap(); + let out_d = super::bound(&list, draw_buf.GetGPUVirtualAddress(), (0, 32, COUNT as u32), None).unwrap(); + super::done(&list, &out_d); + list.close(); + host.execute(&[&list]); + let mut p = std::ptr::null_mut(); + out_d.Map(0, None, Some(&mut p)).unwrap(); + let got_d = std::slice::from_raw_parts(p.cast::<[u32; 8]>(), COUNT); + for (i, r) in got_d.iter().enumerate() { + let k = i as u32; + let expected_head = match i { + 0..=75 => [0, 0], + 76 => [(1 << 23) - 1, 1], + _ => [12, 2], + }; + assert_eq!( + *r, + [expected_head[0], expected_head[1], 100 + k, 200 + k, 0xa000 + k, 0xb000 + k, 0xc000 + k, 0xd000 + k], + "draw record {i}" + ); + } + out_d.Unmap(0, None); + + // On a fresh list, 76 unfilled `0xffffffff` mesh records before 16 + // max-cost `65535` mesh records spend nothing so all 16 run. + let (mesh16_buf, mesh16_ptr) = host.shared_buffer(((76 + 16) * 12) as u64).unwrap(); + let m16 = std::slice::from_raw_parts_mut(mesh16_ptr.cast::<[u32; 3]>(), 76 + 16); + for (i, m) in m16.iter_mut().enumerate() { + *m = if i < 76 { [u32::MAX; 3] } else { [65_535, 4, 4] }; + } + list.reset(); + let out_m16 = super::bound(&list, mesh16_buf.GetGPUVirtualAddress(), (10, 12, (76 + 16) as u32), None).unwrap(); + super::done(&list, &out_m16); + list.close(); + host.execute(&[&list]); + out_m16.Map(0, None, Some(&mut p)).unwrap(); + let got_m16 = std::slice::from_raw_parts(p.cast::<[u32; 3]>(), 76 + 16); + assert!(got_m16[..76].iter().all(|&m| m == [0, 0, 0])); + assert!(got_m16[76..].iter().all(|&m| m == [65_535, 1, 1])); + out_m16.Unmap(0, None); + + list.reset(); + let out_m = super::bound(&list, mesh_buf.GetGPUVirtualAddress(), (10, 32, COUNT as u32), None).unwrap(); + super::done(&list, &out_m); + list.close(); + host.execute(&[&list]); + out_m.Map(0, None, Some(&mut p)).unwrap(); + let got_m = std::slice::from_raw_parts(p.cast::<[u32; 8]>(), COUNT); + for (i, r) in got_m.iter().enumerate() { + let k = i as u32; + let head = match i { + 0..=75 => [0, 0, 0], + 76 => [65_535, 1, 1], + _ => [7, 1, 1], + }; + assert_eq!( + *r, + [head[0], head[1], head[2], 0x1000 + k, 0x2000 + k, 0x3000 + k, 0x4000 + k, 0x5000 + k], + "mesh record {i}" + ); + } + out_m.Unmap(0, None); + } + } + + /// Rejected records do not wrap the budget: of 128 max-cost draws (2^26 /// vertex instances each once clamped) two run, where a wrapping add - /// let four; of 600 garbage mesh dispatches 16, not 31. + /// let four; of 600 max-cost mesh dispatches 16, not 31. #[test] fn rejected_records_do_not_wrap_the_budget() { - let Some(draws) = clamped(0, &[u32::MAX], 128, 1) else { + let Some(draws) = clamped(0, &[1 << 22, u32::MAX, 0, 0], 128, 1) else { return; // no host GPU here }; assert_eq!(draws.iter().filter(|&&count| count != 0).count(), 2); - let meshes = clamped(10, &[u32::MAX], 600, 1).unwrap(); + let meshes = clamped(10, &[65_535, 1, 1], 600, 1).unwrap(); assert_eq!(meshes.iter().filter(|&&groups| groups != 0).count(), 16); } @@ -495,18 +811,30 @@ mod tests { assert!(small.iter().all(|&count| count == 1)); } - /// A record that does not fit ends the budget: after two draws of - /// 3 * 2^24 vertex instances a third takes what is left, and the small - /// ones after it run empty. + /// By default (`VICTORY_INDIRECT_REST=0`), a record that does not fit in + /// the remaining budget runs empty while smaller records after it still + /// run; with `VICTORY_INDIRECT_REST=1`, it takes what is left so later + /// records run empty too. #[test] - fn a_record_that_does_not_fit_ends_the_budget() { - let mut words = [1 << 24, 3, 0, 0].repeat(3); - words.extend([3, 1, 0, 0].repeat(6)); - let Some(draws) = clamped(0, &words, 8, 1) else { + fn a_record_that_does_not_fit_respects_indirect_rest() { + let mut words = [1 << 22, 12, 0, 0].repeat(3); + words.extend([3, 1, 0, 0].repeat(5)); + let Some(draws_default) = clamped(0, &words, 8, 1) else { return; // no host GPU here }; - let ran: Vec = draws.iter().map(|&count| count != 0).collect(); - assert_eq!(ran, [true, true, false, false, false, false, false, false]); + let ran_default: Vec = draws_default.iter().map(|&count| count != 0).collect(); + assert_eq!( + ran_default, + [true, true, false, true, true, true, true, true], + "VICTORY_INDIRECT_REST=0 keeps budget for later fitting records" + ); + let draws_rest = super::with_indirect_rest(true, || clamped(0, &words, 8, 1).unwrap()); + let ran_rest: Vec = draws_rest.iter().map(|&count| count != 0).collect(); + assert_eq!( + ran_rest, + [true, true, false, false, false, false, false, false], + "VICTORY_INDIRECT_REST=1 ends the budget on the first overflow" + ); } /// Two lists clamping into their own argument buffers, run in either @@ -567,29 +895,30 @@ mod tests { /// finds it spent, and they all run empty. #[test] fn a_spent_budget_stays_spent() { - let Some(twice) = clamped(1, &[u32::MAX], 64, 2) else { + let Some(twice) = clamped(1, &[1 << 22, u32::MAX, 0, 0, 0], 64, 2) else { return; // no host GPU here }; assert!(twice.iter().all(|&count| count == 0)); } - /// The walk stops at the count: of 128 garbage draws under a count of 3 + /// The walk stops at the count: of 128 max-cost draws under a count of 3 /// the first two run and the third runs empty, as they do without one, /// and the others are never read (the argument buffer's fresh words stay /// zero). A count above the records changes nothing; a count of zero /// walks none. #[test] fn the_walk_stops_at_the_count() { - let Some(under) = clamped_under(0, &[u32::MAX], 128, 1, Some(3)) else { + let words = [1 << 22, u32::MAX, 0, 0]; + let Some(under) = clamped_under(0, &words, 128, 1, Some(3)) else { return; // no host GPU here }; - assert_eq!(under[..3], [1 << 24, 1 << 24, 0]); + assert_eq!(under[..3], [1 << 22, 1 << 22, 0]); assert!(under[3..].iter().all(|&count| count == 0)); - let all = clamped(0, &[u32::MAX], 128, 1).unwrap(); + let all = clamped(0, &words, 128, 1).unwrap(); assert_eq!(under[..3], all[..3]); - let above = clamped_under(0, &[u32::MAX], 128, 1, Some(1 << 20)).unwrap(); + let above = clamped_under(0, &words, 128, 1, Some(1 << 20)).unwrap(); assert_eq!(above, all); - let none = clamped_under(0, &[u32::MAX], 128, 1, Some(0)).unwrap(); + let none = clamped_under(0, &words, 128, 1, Some(0)).unwrap(); assert!(none.iter().all(|&count| count == 0)); } @@ -598,11 +927,12 @@ mod tests { /// the same draws with no count spent it all on records that never ran. #[test] fn records_past_the_count_are_not_charged() { - let Some(twice) = clamped_under(0, &[u32::MAX], 128, 2, Some(1)) else { + let words = [1 << 22, u32::MAX, 0, 0]; + let Some(twice) = clamped_under(0, &words, 128, 2, Some(1)) else { return; // no host GPU here }; - assert_eq!(twice[0], 1 << 24); - let spent = clamped(0, &[u32::MAX], 128, 2).unwrap(); + assert_eq!(twice[0], 1 << 22); + let spent = clamped(0, &words, 128, 2).unwrap(); assert!(spent.iter().all(|&count| count == 0)); } diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index af760c2c..35ecf0e7 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -272,17 +272,50 @@ fn restart(this: This) -> Option> { #[cfg(windows)] static SPARE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// Host lists waiting out [`crate::host::bury_lag`] submissions before their +/// command allocators and kept resources are reset. +#[cfg(windows)] +static AGING: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::VecDeque::new()); + /// A host list a queue has run: one no title list holds any more is reset -/// and kept for [`restart`]. +/// and kept for [`restart`] (after [`crate::host::bury_lag`] submissions). #[cfg(windows)] pub(crate) fn recycle(list: std::sync::Arc) { const KEPT: usize = 64; - if let Ok(list) = std::sync::Arc::try_unwrap(list) { + let Ok(list) = std::sync::Arc::try_unwrap(list) else { + return; + }; + let lag = crate::host::bury_lag(); + let done = crate::host::submissions_done(); + if lag == 0 { list.reset(); let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); if spare.len() < KEPT { spare.push(list); } + return; + } + let ready: Vec = { + let mut aging = AGING.lock().unwrap_or_else(|e| e.into_inner()); + aging.push_back((done, list)); + let n = aging + .iter() + .take_while(|(at, _)| at.saturating_add(lag) <= done) + .count(); + aging.drain(..n).map(|(_, l)| l).collect() + }; + if ready.is_empty() { + return; + } + for l in &ready { + l.reset(); + } + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + for l in ready { + if spare.len() < KEPT { + spare.push(l); + } } } diff --git a/crates/victory-gpu/src/placement.rs b/crates/victory-gpu/src/placement.rs index 7c0afbbc..2627d8b1 100644 --- a/crates/victory-gpu/src/placement.rs +++ b/crates/victory-gpu/src/placement.rs @@ -114,13 +114,20 @@ impl Heaps { } let empty = |h: &Heap| h.free.get(&0) == Some(&HEAP); let mut spare = 0; - self.heaps.retain(|h| { - if !empty(h) { - return true; + let mut i = 0; + while i < self.heaps.len() { + if !empty(&self.heaps[i]) { + i += 1; + continue; } spare += 1; - spare <= SPARE - }); + if spare <= SPARE { + i += 1; + } else { + let removed = self.heaps.remove(i); + crate::host::retire_any(removed.heap); + } + } } /// A range of `size` bytes: in a heap with room, else in a new heap. diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 9940fb6f..3e7a9675 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1023,6 +1023,7 @@ impl Drop for HostTexture { use windows::core::Interface; life::note(self.texture.as_raw() as usize, life::LET_GO, 0, life::holders(&self.texture)); } + crate::host::retire(self.texture.clone()); } } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index ca502923..27cc387e 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -1091,6 +1091,8 @@ impl Drop for Shadow { fn drop(&mut self) { if let Some(slice) = self.slice { arena().give_back(slice); + } else { + crate::host::retire(self.buffer.clone()); } if let Some(base) = self.marks { let mut m = marks(); @@ -1822,10 +1824,20 @@ pub(crate) fn log_held() { ); } +/// User virtual space ends at 2^47 on x86_64 Windows; pages below +/// [`LOWEST_MAPPED`] are the unmapped null guard region. +const USER_SPACE_END: u64 = 1 << 47; + /// The copy of the innermost title buffer holding `[address, address + /// len)`, made on first use. pub(crate) fn find(address: u64, len: u64) -> Option> { + if address < LOWEST_MAPPED { + return None; + } let end = address.checked_add(len.max(1))?; + if end > USER_SPACE_END { + return None; + } if !lookup_cache_enabled() { return find_uncached(address, end); } @@ -1946,7 +1958,11 @@ fn loose(address: u64, end: u64) -> Option> { } let window = loose_window_bytes(); let start = address & !(window - 1); - let len = end.checked_next_multiple_of(window)? - start; + let rounded_end = end.checked_next_multiple_of(window)?; + if rounded_end > USER_SPACE_END { + return None; + } + let len = rounded_end - start; let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); if let Some(shadow) = enclosing_window(&map, LOOSE_SPAN.load(Ordering::Relaxed), address, end) { return Some(shadow.clone()); @@ -3385,4 +3401,22 @@ pub(crate) mod tests { assert!(ranges_disjoint(&[(0x2000, 0x1000), (0x1000, 0x1000)])); assert!(!ranges_disjoint(&[(0x1000, 0x1500), (0x2000, 0x1000)])); } + + #[test] + fn null_and_out_of_range_addresses_never_create_loose_copies() { + for bad in [ + 0, + 0x80, + 0xfffc, + USER_SPACE_END - 8, + USER_SPACE_END, + 0u64.wrapping_sub(0x80), + u64::MAX, + ] { + assert!( + find(bad, 16).is_none(), + "address {bad:#x} must be rejected" + ); + } + } } diff --git a/crates/victory-gpu/src/switch.rs b/crates/victory-gpu/src/switch.rs index 749d60b2..0f92cf4a 100644 --- a/crates/victory-gpu/src/switch.rs +++ b/crates/victory-gpu/src/switch.rs @@ -1,4 +1,5 @@ //! The `VICTORY_*` on/off switches (`VICTORY_D3D12_DEBUG=1` and its siblings). +#![allow(dead_code)] use std::ffi::OsStr; @@ -10,14 +11,24 @@ pub(crate) fn value_is_on(value: Option<&OsStr>) -> bool { value.is_some_and(|v| v != "0") } +/// Whether an on-by-default switch's value leaves it on: anything except `0`. +fn value_is_on_by_default(value: Option<&OsStr>) -> bool { + value != Some(OsStr::new("0")) +} + /// Whether the environment variable `name` switches something on. pub(crate) fn on(name: &str) -> bool { value_is_on(std::env::var_os(name).as_deref()) } +/// Whether the environment variable `name` leaves an on-by-default switch on. +pub(crate) fn on_by_default(name: &str) -> bool { + value_is_on_by_default(std::env::var_os(name).as_deref()) +} + #[cfg(test)] mod tests { - use super::value_is_on; + use super::{on_by_default, value_is_on, value_is_on_by_default}; use std::ffi::OsStr; #[test] @@ -42,4 +53,13 @@ mod tests { assert!(value_is_on(Some(OsStr::new(value))), "{value:?}"); } } + + #[test] + fn on_by_default_only_zero_is_off() { + assert!(value_is_on_by_default(None)); + assert!(!value_is_on_by_default(Some(OsStr::new("0")))); + assert!(value_is_on_by_default(Some(OsStr::new("1")))); + assert!(value_is_on_by_default(Some(OsStr::new("")))); + assert!(on_by_default("VICTORY_TEST_DEFINITELY_UNSET_SWITCH")); + } } From f5a99ed52c0a8c4cb95a79f22c3080bfece624a9 Mon Sep 17 00:00:00 2001 From: Pragyaan Gaur Date: Fri, 27 Nov 2026 08:36:31 +0530 Subject: [PATCH 2/3] fix(gpu): adapt the hoisted budget test to the unfilled draw cut, pass the rest flag in hoisted clamps, and make the bury lag test count-proof The hoisted budget tests used 2^24 vertices per record, which the unfilled draw rule now empties, so they use 2^22 vertices and 16 instances for the same 2^26 cost. The hoisted batch now passes the rest flag like the inline clamp. The bury lag test checks retention against the global submission count, which tests running at the same time also advance. --- crates/victory-gpu/src/host.rs | 9 +++++++-- crates/victory-gpu/src/indirect.rs | 17 +++++++++-------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 5dfdfffa..8e369f2e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -6582,6 +6582,10 @@ float4 ps(float4 pos : SV_Position) : SV_Target { list.close(); super::with_bury_lag(3, || { let _quiet = host.quiet(); + // The submission count is global: tests that run at the same + // time add to it, so retention is checked against the count the + // retirement could not have been recorded after. + let before = super::submissions_done(); super::retire(buf_lag.clone()); assert!(references(&buf_lag) >= 2, "held by retirement ring"); drop(_quiet); @@ -6590,9 +6594,10 @@ float4 ps(float4 pos : SV_Position) : SV_Target { list.reset(); list.close(); host.execute(&[&list]); + let passed = super::submissions_done().saturating_sub(before); assert!( - references(&buf_lag) >= 2, - "still retained after {step} of 3 lag submissions" + passed >= 3 || references(&buf_lag) >= 2, + "still retained after {step} of 3 lag submissions ({passed} passed)" ); } list.reset(); diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 66b3017a..a8ead2ac 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -629,6 +629,7 @@ pub(crate) fn record_batch( )); } let widest = widest(); + let rest = indirect_rest(); // SAFETY: `cmd` is the host list's open prelude command list; our clamp // pipeline, budget buffer, hoisted argument buffers, and title shadow // copies are kept alive by the host list until reset. @@ -654,7 +655,7 @@ pub(crate) fn record_batch( clamp.kind, clamp.stride, clamp.records, - u32::from(clamp.count_gpu.is_some()), + u32::from(clamp.count_gpu.is_some()) | (u32::from(rest) << 1), widest, ]; cmd.SetComputeRoot32BitConstants( @@ -1343,8 +1344,8 @@ void main(uint3 g : SV_GroupID) { stride: 16, records: 4, words: vec![ - 1 << 24, 4, 0, 0, - 1 << 24, 4, 0, 0, + 1 << 22, 16, 0, 0, + 1 << 22, 16, 0, 0, 3, 1, 0, 0, 3, 1, 0, 0, ], @@ -1717,7 +1718,7 @@ void main() { let Some(host) = super::host() else { return; // no host GPU here }; - // Each record asks for 2^24 * 4 = 2^26 vertex instances (half the 2^27 + // Each record asks for 2^22 * 16 = 2^26 vertex instances (half the 2^27 // list budget). Two hoisted records exhaust the budget completely, so // an inline record after them in the same list must be zeroed. let (src, ptr) = host.shared_buffer(32).unwrap(); @@ -1726,8 +1727,8 @@ void main() { let (src_gpu, inline_gpu) = unsafe { let p = ptr.cast::(); for i in 0..2 { - p.add(i * 4).write_volatile(1 << 24); - p.add(i * 4 + 1).write_volatile(4); + p.add(i * 4).write_volatile(1 << 22); + p.add(i * 4 + 1).write_volatile(16); p.add(i * 4 + 2).write_volatile(0); p.add(i * 4 + 3).write_volatile(0); } @@ -1751,8 +1752,8 @@ void main() { unsafe { hoisted_buf.Map(0, None, Some(&mut p)).unwrap(); let base = p.cast::().add(hoisted_off as usize).cast::(); - assert_eq!(base.add(0).read_volatile(), 1 << 24, "hoisted record 0 fits"); - assert_eq!(base.add(4).read_volatile(), 1 << 24, "hoisted record 1 fits"); + assert_eq!(base.add(0).read_volatile(), 1 << 22, "hoisted record 0 fits"); + assert_eq!(base.add(4).read_volatile(), 1 << 22, "hoisted record 1 fits"); hoisted_buf.Unmap(0, None); inline_buf.Map(0, None, Some(&mut p)).unwrap(); From 63d4e6b83df421e1ff11409341d9af537568cbc0 Mon Sep 17 00:00:00 2001 From: Pragyaan Gaur Date: Fri, 27 Nov 2026 11:30:17 +0530 Subject: [PATCH 3/3] Fix the test code and imports after merging main --- crates/victory-gpu/src/draw.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b11a11a6..e0682f6a 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -6166,6 +6166,8 @@ void main() { crate::pipeline::Translated { host: host_shader, used: Vec::new(), + used_written: Vec::new(), + write_unknown: true, }, ); let hp = HostPipeline {