From fc582385cee118528a8d6bc7aa20fa3af834c4bc Mon Sep 17 00:00:00 2001 From: gmanka Date: Thu, 26 Nov 2026 01:57:24 +0500 Subject: [PATCH 1/3] GPU: clamp indirect arguments in a private list buffer An in-place clamp overwrites records in the title shadow buffer and transitions the entire buffer even when later commands bind other regions as vertex or shader input. Read the title records through an SRV and execute from a reusable per-list buffer so only the clamp output changes state. Keep previous allocations alive when the list grows and preserve the signed base vertex and other draw offsets. Based-on: https://github.com/Marvisak/VIctory/commit/315cea185d2505ed84643b2b47c39c224e757837 Tested-on: Fedora Linux 45, Lavapipe and native VKD3D-Proton (44 GPU tests passed) Assisted-by: gpt-6.2 sol xhigh --- crates/victory-gpu/src/draw.rs | 20 +++---- crates/victory-gpu/src/host.rs | 18 ++++++ crates/victory-gpu/src/indirect.rs | 96 +++++++++++++++++++++--------- 3 files changed, 95 insertions(+), 39 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 7efe77ec9a5..0eda462fe3f 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -955,7 +955,7 @@ impl State { arguments: u64, count: Option, ) -> bool { - // Skip before the argument clamp can mutate the indirect buffer. + // Skip before recording unnecessary clamp work. #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { crate::pipeline::note_drop(self.pipeline as This); @@ -996,10 +996,10 @@ impl State { s.refresh(list, *at, 4); } // Bounded first: the clamp binds a compute pipeline of its own. - if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) { - why("not bounded (no clamp, or arguments not 4-byte aligned)"); + let Some(clamped) = crate::indirect::bound(list, args.gpu(arguments), (kind, stride, max)) else { + why("argument clamp unavailable"); return false; - } + }; self.host_pipeline = 0; self.host_roots[1] = 0; let ran = match kind { @@ -1015,7 +1015,7 @@ impl State { _ => false, }; if !ran { - crate::indirect::done(list, &args.buffer); + crate::indirect::done(list, &clamped); #[cfg(feature = "diagnostics")] match crate::pipeline::host_pipeline(self.pipeline as This) { None => crate::pipeline::note_drop(self.pipeline as This), @@ -1027,19 +1027,19 @@ impl State { list.note_op(|| { self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) }); - // SAFETY: an open list with everything set; the buffers are host - // copies the list keeps alive (refresh), the signature is cached. + // SAFETY: an open list with everything set; the list holds both + // buffers, and the signature is cached. unsafe { list.list.ExecuteIndirect( &signature, max, - &args.buffer, - args.offset(arguments), + &clamped, + 0, counter.as_ref().map(|(s, _)| &s.buffer), counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; - crate::indirect::done(list, &args.buffer); + crate::indirect::done(list, &clamped); if kind == DISPATCH { DISPATCHED.fetch_add(1, Ordering::Relaxed); } else { diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 46cf638c057..3dcdc020f2e 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -339,6 +339,7 @@ pub(crate) struct HostList { /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted. budget: OnceLock>, + arguments: Mutex>, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -573,6 +574,7 @@ impl Host { prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), budget: OnceLock::new(), + arguments: Mutex::new(None), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -1274,6 +1276,22 @@ impl HostList { Some(unsafe { buffer.GetGPUVirtualAddress() }) } + /// The list's private argument buffer, in COMMON between uses. + pub(crate) fn arguments(&self, bytes: u64) -> Option { + let mut arguments = self.arguments.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: a descriptor query on a live resource. + if let Some(buffer) = arguments.as_ref().filter(|buffer| unsafe { buffer.GetDesc() }.Width >= bytes) { + return Some(buffer.clone()); + } + let (buffer, _) = host()?.shared_buffer(bytes.checked_next_power_of_two()?.max(1 << 16))?; + name(&buffer, || "indirect arguments".into()); + // Earlier commands can still reference the smaller allocation. + if let Some(old) = arguments.replace(buffer.clone()) { + self.keep(&old); + } + Some(buffer) + } + /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 7bf77aaab9b..3d93ea194c4 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -28,9 +28,10 @@ use windows::core::s; use crate::host::{HostList, host, transition}; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0), UAV(u1)" +#define RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u1), UAV(u0)" cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; -RWByteAddressBuffer args : register(u0); +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); @@ -48,7 +49,12 @@ void main(uint3 id : SV_DispatchThreadID) { uint count = min(args.Load(at), 1u << 24); uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); cost = count * instances; - args.Store2(at, uint2(count, instances)); + dest.Store2(at, uint2(count, instances)); + if (kind == 1) { + dest.Store3(at + 8, args.Load3(at + 8)); + } else { + dest.Store2(at + 8, args.Load2(at + 8)); + } } else if (kind == 2) { uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); // x * y fits 32 bits; the whole count may not. @@ -56,19 +62,19 @@ void main(uint3 id : SV_DispatchThreadID) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64; - args.Store3(at, g); + dest.Store3(at, g); } else { // Mesh dispatches: the console's are one-dimensional. uint3 g = args.Load3(at); g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); cost = g.x * g.y * g.z * 128; - args.Store3(at, g); + dest.Store3(at, g); } uint before; budget.InterlockedAdd(0, cost, before); if (before >= BUDGET || before + cost > BUDGET) { // Draws keep their layout with no vertices; groups become zero. - args.Store(at, 0); + dest.Store(at, 0); } } "#; @@ -170,56 +176,53 @@ fn make() -> windows::core::Result { } /// Records, in `list`, the clamp of `records` records of `kind` (PC -/// argument numbering) `stride` bytes apart at host address `gpu` in -/// `buffer`, and leaves the buffer ready to be read as arguments. Replaces -/// the list's compute root signature and pipeline (callers bind theirs -/// after). False if the clamp is not available. -pub(crate) fn bound( - list: &HostList, - buffer: &ID3D12Resource, - gpu: u64, - (kind, stride, records): (u32, u32, u32), -) -> bool { - let (Some(c), Some(budget)) = (clamp(), list.budget()) else { - return false; - }; +/// argument numbering) `stride` bytes apart at host address `gpu`. The +/// list's private buffer holds the results until [`done`]. Replaces the +/// list's compute root signature and pipeline (callers bind theirs after). +pub(crate) fn bound(list: &HostList, gpu: u64, (kind, stride, records): (u32, u32, u32)) -> Option { if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { - return false; + return None; } + let c = clamp()?; + let budget = list.budget()?; + let out = list.arguments(u64::from(stride) * u64::from(records.max(1)))?; let l = &list.list; let constants = [kind, stride, records, 0]; - // SAFETY: an open list; our root signature, pipeline and a live buffer - // the caller's list holds. + // SAFETY: an open list; the caller holds the input alive and the list + // keeps the output and budget allocated. unsafe { // Earlier shader writes (the title's argument passes) first. - l.ResourceBarrier(&[uav_barrier()]); + l.ResourceBarrier(&[ + uav_barrier(), + transition(&out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); l.SetComputeRootSignature(&c.root); l.SetPipelineState(&c.pso); l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - l.SetComputeRootUnorderedAccessView(1, gpu); + l.SetComputeRootShaderResourceView(1, gpu); l.SetComputeRootUnorderedAccessView(2, budget); + l.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); l.Dispatch(records.div_ceil(64), 1, 1); l.ResourceBarrier(&[ uav_barrier(), transition( - buffer, + &out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, ), ]); } - true + Some(out) } -/// After the execution: the buffer back to unordered access, where the -/// title's passes keep using it. +/// Restore the private buffer to COMMON for the next clamp. pub(crate) fn done(list: &HostList, buffer: &ID3D12Resource) { // SAFETY: an open list and a live buffer. unsafe { list.list.ResourceBarrier(&[transition( buffer, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COMMON, )]) }; } @@ -236,6 +239,8 @@ fn uav_barrier() -> D3D12_RESOURCE_BARRIER { #[cfg(test)] mod tests { + use super::*; + /// The clamp compiles with the system's compiler and the host takes it. #[test] fn argument_clamp_builds() { @@ -262,4 +267,37 @@ mod tests { #[cfg(not(windows))] assert_eq!(handler(), ours); } + + #[test] + fn argument_clamp_preserves_title_records() { + let Some(host) = host() else { return }; + if cfg!(not(windows)) && std::env::var_os("VICTORY_DXCOMPILER").is_none() { + return; + } + // Two indexed records with a nonzero base offset and padded stride. + let title = [0xfeed, u32::MAX, 9, 31, u32::MAX - 16, 7, 0xbeef, 3, 2, 12, 0, 6, 0]; + let (input, data) = host.shared_buffer(std::mem::size_of_val(&title) as u64).unwrap(); + let list = host.new_list().unwrap(); + // SAFETY: the mapping covers the title words and the buffer is idle. + let gpu = unsafe { + std::ptr::copy_nonoverlapping(title.as_ptr(), data.cast::(), title.len()); + input.GetGPUVirtualAddress() + }; + let output = bound(&list, gpu + 4, (1, 24, 2)).expect("clamp recorded"); + assert_ne!(output, input); + assert_eq!(output, list.arguments(48).unwrap()); + done(&list, &output); + list.close(); + host.execute(&[&list]); + + let mut mapped = std::ptr::null_mut(); + // SAFETY: the GPU finished. Both mapped buffers cover the inspected words. + unsafe { + output.Map(0, None, Some(&mut mapped)).unwrap(); + let clamped = std::slice::from_raw_parts(mapped.cast::(), 11); + assert_eq!(&clamped[..5], &[1 << 24, 4, 31, u32::MAX - 16, 7]); + assert_eq!(&clamped[6..], &[3, 2, 12, 0, 6]); + assert_eq!(std::slice::from_raw_parts(data.cast::(), title.len()), title); + } + } } From 2f37af1f67ab310862a10f130cd607f3eeb261f7 Mon Sep 17 00:00:00 2001 From: gmanka Date: Thu, 26 Nov 2026 02:43:24 +0500 Subject: [PATCH 2/3] GPU: clamp only the active native indirect records The native clamp walks MaxCommandCount even when a count buffer limits execution to fewer records. Inactive records can contain unrelated data and consume the per-list budget before a valid dispatch. Read the count in the clamp, skip the unused records, and store the bounded count beside the private arguments for ExecuteIndirect. Earlier UAV writers are ordered before the clamp and their title buffers are restored before the title pipeline binds. Based-on: https://github.com/Marvisak/VIctory/pull/242 Depends-on: https://github.com/spidercraft/VIctory/pull/11 Tested-on: Intel Xeon E5-2670 v3, Fedora Linux 45, Lavapipe and native VKD3D-Proton (45 GPU tests) Assisted-by: gpt-6.2 sol xhigh --- crates/victory-gpu/src/draw.rs | 12 ++- crates/victory-gpu/src/host.rs | 12 ++- crates/victory-gpu/src/indirect.rs | 163 +++++++++++++++++++++++++---- 3 files changed, 159 insertions(+), 28 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 0eda462fe3f..ab075e045ba 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -996,7 +996,13 @@ impl State { s.refresh(list, *at, 4); } // Bounded first: the clamp binds a compute pipeline of its own. - let Some(clamped) = crate::indirect::bound(list, args.gpu(arguments), (kind, stride, max)) else { + let count_source = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + let Some(clamped) = crate::indirect::bound( + list, + (&args.buffer, args.offset(arguments)), + count_source, + (kind, stride, max), + ) else { why("argument clamp unavailable"); return false; }; @@ -1034,9 +1040,9 @@ impl State { &signature, max, &clamped, + if count_source.is_some() { crate::indirect::COUNT_BYTES } else { 0 }, + count_source.map(|_| &clamped), 0, - counter.as_ref().map(|(s, _)| &s.buffer), - counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), ) }; crate::indirect::done(list, &clamped); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 3dcdc020f2e..ff2a0d72593 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -499,6 +499,8 @@ struct Deferred { refreshed: std::collections::HashSet<(usize, usize, usize)>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, + /// Host buffers that earlier shaders in this list used as UAVs. + gpu_written: std::collections::HashSet, /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, @@ -1201,9 +1203,13 @@ impl HostList { address: usize, len: usize, ) { - self.deferred() - .copies - .push(Step::GpuWrite(shadow.clone(), address, len)); + let mut deferred = self.deferred(); + deferred.gpu_written.insert(shadow.buffer.as_raw() as usize); + deferred.copies.push(Step::GpuWrite(shadow.clone(), address, len)); + } + + pub(crate) fn gpu_written(&self, buffer: &ID3D12Resource) -> bool { + self.deferred().gpu_written.contains(&(buffer.as_raw() as usize)) } /// Stores `what` (`bytes` of it) at `dst` once the list has run. diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 3d93ea194c4..88c7f3a4017 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -27,10 +27,14 @@ use windows::core::s; use crate::host::{HostList, host, transition}; +/// A counted execution puts its count before the clamped records. +pub(crate) const COUNT_BYTES: u64 = size_of::() as u64; + const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u1), UAV(u0)" -cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint unused; }; +#define RS "RootConstants(num32BitConstants=4, b0), SRV(t0), UAV(u1), UAV(u0), SRV(t1)" +cbuffer Record : register(b0) { uint kind; uint stride; uint records; uint count_bytes; }; ByteAddressBuffer args : register(t0); +ByteAddressBuffer count_buf : register(t1); RWByteAddressBuffer dest : register(u0); // The list's work so far (vertex instances, threads): past the budget, // records run empty. @@ -41,19 +45,25 @@ static const uint GROUPS = 1u << 20; [RootSignature(RS)] [numthreads(64, 1, 1)] void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= records) return; + uint active_records = records; + if (count_bytes != 0) { + active_records = min(active_records, count_buf.Load(0)); + if (id.x == 0) dest.Store(0, active_records); + } + if (id.x >= active_records) return; uint at = id.x * stride; + uint dst = at + count_bytes; uint cost; if (kind <= 1) { // Draws: vertex or index count, then instances. uint count = min(args.Load(at), 1u << 24); uint instances = min(args.Load(at + 4), (1u << 26) / max(count, 1u)); cost = count * instances; - dest.Store2(at, uint2(count, instances)); + dest.Store2(dst, uint2(count, instances)); if (kind == 1) { - dest.Store3(at + 8, args.Load3(at + 8)); + dest.Store3(dst + 8, args.Load3(at + 8)); } else { - dest.Store2(at + 8, args.Load2(at + 8)); + dest.Store2(dst + 8, args.Load2(at + 8)); } } else if (kind == 2) { uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535)); @@ -62,19 +72,19 @@ void main(uint3 id : SV_DispatchThreadID) { g = uint3(0, 0, 0); } cost = g.x * g.y * g.z * 64; - dest.Store3(at, g); + dest.Store3(dst, g); } else { // Mesh dispatches: the console's are one-dimensional. uint3 g = args.Load3(at); g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); cost = g.x * g.y * g.z * 128; - dest.Store3(at, g); + dest.Store3(dst, g); } uint before; budget.InterlockedAdd(0, cost, before); if (before >= BUDGET || before + cost > BUDGET) { // Draws keep their layout with no vertices; groups become zero. - dest.Store(at, 0); + dest.Store(dst, 0); } } "#; @@ -176,41 +186,70 @@ fn make() -> windows::core::Result { } /// Records, in `list`, the clamp of `records` records of `kind` (PC -/// argument numbering) `stride` bytes apart at host address `gpu`. The -/// list's private buffer holds the results until [`done`]. Replaces the -/// list's compute root signature and pipeline (callers bind theirs after). -pub(crate) fn bound(list: &HostList, gpu: u64, (kind, stride, records): (u32, u32, u32)) -> Option { - if !gpu.is_multiple_of(4) || !stride.is_multiple_of(4) { +/// argument numbering) `stride` bytes apart. The list's private buffer +/// holds the snapped count (when present) and results until [`done`]. +/// Replaces the list's compute root signature and pipeline. +pub(crate) fn bound( + list: &HostList, + args: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + (kind, stride, records): (u32, u32, u32), +) -> Option { + if !args.1.is_multiple_of(4) || !stride.is_multiple_of(4) + || count.is_some_and(|(_, offset)| !offset.is_multiple_of(4)) + { return None; } let c = clamp()?; let budget = list.budget()?; - let out = list.arguments(u64::from(stride) * u64::from(records.max(1)))?; + let count_bytes = if count.is_some() { COUNT_BYTES } else { 0 }; + let bytes = (u64::from(stride) * u64::from(records.max(1))).checked_add(count_bytes)?; + let bytes = u32::try_from(bytes).ok()?; + let out = list.arguments(u64::from(bytes))?; + let sources = [Some(args.0), count.map(|(buffer, _)| buffer).filter(|&buffer| buffer != args.0)]; + let written = sources.map(|source| source.filter(|buffer| list.gpu_written(buffer))); + // SAFETY: each buffer lives through this recording and its execution. + let gpu = unsafe { args.0.GetGPUVirtualAddress() }.checked_add(args.1)?; + let count_gpu = match count { + Some((buffer, offset)) => unsafe { buffer.GetGPUVirtualAddress() }.checked_add(offset)?, + None => gpu, + }; let l = &list.list; - let constants = [kind, stride, records, 0]; + let constants = [kind, stride, records, count_bytes as u32]; + let uav = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; // SAFETY: an open list; the caller holds the input alive and the list // keeps the output and budget allocated. unsafe { // Earlier shader writes (the title's argument passes) first. l.ResourceBarrier(&[ uav_barrier(), - transition(&out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + transition(&out, D3D12_RESOURCE_STATE_COMMON, uav), ]); + for buffer in written.into_iter().flatten() { + l.ResourceBarrier(&[transition(buffer, uav, read)]); + } l.SetComputeRootSignature(&c.root); l.SetPipelineState(&c.pso); l.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); l.SetComputeRootShaderResourceView(1, gpu); l.SetComputeRootUnorderedAccessView(2, budget); l.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); - l.Dispatch(records.div_ceil(64), 1, 1); + l.SetComputeRootShaderResourceView(4, count_gpu); + l.Dispatch(records.div_ceil(64).max(u32::from(count.is_some())), 1, 1); l.ResourceBarrier(&[ uav_barrier(), transition( &out, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + uav, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, ), ]); + // Execution reads the snapshot, so both title buffers can return + // to their previous state before the draw binds its resources. + for buffer in written.into_iter().flatten() { + l.ResourceBarrier(&[transition(buffer, read, uav)]); + } } Some(out) } @@ -279,11 +318,10 @@ mod tests { let (input, data) = host.shared_buffer(std::mem::size_of_val(&title) as u64).unwrap(); let list = host.new_list().unwrap(); // SAFETY: the mapping covers the title words and the buffer is idle. - let gpu = unsafe { + unsafe { std::ptr::copy_nonoverlapping(title.as_ptr(), data.cast::(), title.len()); - input.GetGPUVirtualAddress() }; - let output = bound(&list, gpu + 4, (1, 24, 2)).expect("clamp recorded"); + let output = bound(&list, (&input, 4), None, (1, 24, 2)).expect("clamp recorded"); assert_ne!(output, input); assert_eq!(output, list.arguments(48).unwrap()); done(&list, &output); @@ -300,4 +338,85 @@ mod tests { assert_eq!(std::slice::from_raw_parts(data.cast::(), title.len()), title); } } + + #[test] + fn argument_clamp_counted_dispatches_only_active_records() { + let Some(host) = host() else { return }; + if cfg!(not(windows)) && std::env::var_os("VICTORY_DXCOMPILER").is_none() { + return; + } + let c = clamp().expect("clamp pipeline"); + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }; + let mut signature: Option = None; + // SAFETY: a live description of one dispatch argument with no root changes. + unsafe { + host.device.CreateCommandSignature( + &D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 12, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }, + None::<&ID3D12RootSignature>, + &mut signature, + ).unwrap(); + } + let signature = signature.unwrap(); + for count in [0u32, 1, 7] { + let title = [2u32, 1, 1, 3, 1, 1, count]; + let sentinel = [2u32, 1, 1, 1, 1, 1, 1]; + let (input, data) = host.shared_buffer(size_of_val(&title) as u64).unwrap(); + let (witness, witnessed) = host.shared_buffer(512).unwrap(); + let list = host.new_list().unwrap(); + let output = list.arguments(size_of_val(&sentinel) as u64).unwrap(); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the idle mappings cover all initialized words. + unsafe { + std::ptr::copy_nonoverlapping(title.as_ptr(), data.cast::(), title.len()); + witnessed.cast::().write(0); + output.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::copy_nonoverlapping(sentinel.as_ptr(), mapped.cast::(), sentinel.len()); + } + let clamped = bound(&list, (&input, 0), Some((&input, 24)), (2, 12, 2)).unwrap(); + assert_eq!(clamped, output); + + // Reuse the clamp as a test compute pipeline. Each indirect + // dispatch adds 128 to its separate budget at `witnessed`. + let constants = [2u32, 12, 1, 0]; + // SAFETY: all buffers live through execution. The private buffer + // is in INDIRECT_ARGUMENT and has distinct count and argument offsets. + unsafe { + let command = &list.list; + let gpu = input.GetGPUVirtualAddress(); + let witness = witness.GetGPUVirtualAddress(); + command.SetComputeRootSignature(&c.root); + command.SetPipelineState(&c.pso); + command.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + command.SetComputeRootShaderResourceView(1, gpu); + command.SetComputeRootUnorderedAccessView(2, witness); + command.SetComputeRootUnorderedAccessView(3, witness + 256); + command.SetComputeRootShaderResourceView(4, gpu); + command.ExecuteIndirect(&signature, 2, &clamped, COUNT_BYTES, Some(&clamped), 0); + } + done(&list, &clamped); + list.close(); + host.execute(&[&list]); + + let active = count.min(2) as usize; + // SAFETY: the GPU finished and each mapping covers the inspected words. + unsafe { + let words = std::slice::from_raw_parts(mapped.cast::(), sentinel.len()); + assert_eq!(words[0], active as u32); + let tail = active * 3; + assert_eq!(&words[1..1 + tail], &title[..tail]); + assert_eq!(&words[1 + tail..], &sentinel[1 + tail..]); + assert_eq!(witnessed.cast::().read(), (active * 128) as u32); + assert_eq!(std::slice::from_raw_parts(data.cast::(), title.len()), title); + output.Unmap(0, None); + } + } + } } From fd14c3000ae4c6ea352bf2147388e2c77e15b8a2 Mon Sep 17 00:00:00 2001 From: gmanka Date: Thu, 26 Nov 2026 03:32:23 +0500 Subject: [PATCH 3/3] GPU: stop the native indirect work budget from wrapping The argument clamp charges rejected records to a 32-bit accumulator. After enough large records, the accumulator wraps and admits more work even though the list has already spent its budget. A 128-record test admits four maximum-cost draws when only two fit. Saturate the reservation at the work limit. Groups reserve their total once, so a large argument table avoids a compare-exchange loop for each record. Resolve the one group that crosses the limit in lane order. A single active group can update the counter directly because the UAV barriers between clamps already order its access. Read back large and small batches as well as the boundary inside a group. Counted dispatches now use a separate atomic witness shader to count commands even when the driver overlaps their dispatches. Based-on: https://github.com/Marvisak/VIctory/pull/1510 Based-on: https://github.com/fxceless/victory-fork/commit/f85101b6095e8cf3cecf8f0647cc7f5428daa177 Depends-on: https://github.com/spidercraft/VIctory/pull/14 Tested-on: Fedora Linux 45, Intel Xeon E5-2670 v3, Lavapipe and AMD Radeon RX 6800 using native VKD3D-Proton. Microsoft FXC compiled both shaders as cs_5_1 under Wine. Assisted-by: gpt-6.2 sol xhigh --- crates/victory-gpu/src/indirect.rs | 193 ++++++++++++++++++++++++----- 1 file changed, 162 insertions(+), 31 deletions(-) diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 88c7f3a4017..5d458c91417 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -8,9 +8,9 @@ //! Linux DXC compiles it, as 6.0, if `VICTORY_DXCOMPILER` names one). //! //! 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. +//! counted as 64 threads, mesh groups as 128): records past it run empty. +//! Groups reserve work from a saturating counter so rejected costs cannot +//! wrap it and admit more records. //! //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 //! groups per dimension and 2^20 per dispatch, one-dimensional mesh @@ -42,17 +42,7 @@ RWByteAddressBuffer budget : register(u1); static const uint BUDGET = 1u << 27; // Groups of one dispatch; more run empty. static const uint GROUPS = 1u << 20; -[RootSignature(RS)] -[numthreads(64, 1, 1)] -void main(uint3 id : SV_DispatchThreadID) { - uint active_records = records; - if (count_bytes != 0) { - active_records = min(active_records, count_buf.Load(0)); - if (id.x == 0) dest.Store(0, active_records); - } - if (id.x >= active_records) return; - uint at = id.x * stride; - uint dst = at + count_bytes; +uint clamp_record(uint at, uint dst) { uint cost; if (kind <= 1) { // Draws: vertex or index count, then instances. @@ -80,10 +70,83 @@ void main(uint3 id : SV_DispatchThreadID) { cost = g.x * g.y * g.z * 128; dest.Store3(dst, g); } - uint before; - budget.InterlockedAdd(0, cost, before); - if (before >= BUDGET || before + cost > BUDGET) { - // Draws keep their layout with no vertices; groups become zero. + return cost; +} + +// Reserve one group's work. A single active group is the only writer, and +// the UAV barriers between clamps already order its load and store. +uint reserve_budget(uint cost, bool only_group) { + uint before = 0; + if (only_group) { + before = min(budget.Load(0), BUDGET); + if (before < BUDGET) budget.Store(0, before + min(cost, BUDGET - before)); + } else { + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint after = before + min(cost, BUDGET - before); + uint observed = before; + budget.InterlockedCompareExchange(0, before, after, observed); + if (observed == before) break; + before = observed; + } + } + return BUDGET - min(before, BUDGET); +} + +groupshared uint costs[64]; +groupshared uint totals[2]; +groupshared uint allowance; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 group : SV_GroupID, uint lane : SV_GroupIndex) { + uint active_records = records; + if (count_bytes != 0) { + active_records = min(active_records, count_buf.Load(0)); + if (group.x == 0 && lane == 0) dest.Store(0, active_records); + } + uint first = group.x * 64u; + if (first >= active_records) return; + uint active_lanes = min(64u, active_records - first); + uint at = (first + lane) * stride; + uint dst = at + count_bytes; + uint cost = 0; + [branch] + if (lane < active_lanes) cost = clamp_record(at, dst); + if (active_lanes == 1) { + if (lane == 0 && cost != 0) { + uint left = reserve_budget(cost, active_records == 1); + if (cost > left) dest.Store(dst, 0); + } + return; + } + costs[lane] = cost; + if (lane < 2) totals[lane] = 0; + GroupMemoryBarrierWithGroupSync(); + // A half group fits in uint even if every record costs 2^26. + if (cost != 0) { + uint unused; + InterlockedAdd(totals[lane / 32], cost, unused); + } + GroupMemoryBarrierWithGroupSync(); + if (lane == 0) { + uint total = min(totals[0], BUDGET + 1u) + min(totals[1], BUDGET + 1u); + allowance = 0; + if (total != 0) allowance = reserve_budget(total, active_records <= 64); + if (allowance >= total) { + allowance = BUDGET; + } else if (allowance != 0) { + // Just the group that straddles the budget needs a prefix. + uint prefix = 0; + for (uint i = 0; i < active_lanes; i++) { + prefix = min(prefix + costs[i], BUDGET + 1u); + costs[i] = prefix; + } + } + } + GroupMemoryBarrierWithGroupSync(); + if (cost != 0 && costs[lane] > allowance) { + // Clear only the count; the other argument fields keep their layout. dest.Store(dst, 0); } } @@ -131,13 +194,18 @@ pub(crate) fn compiled() -> windows::core::Result> { /// The clamp's DXBC, with its root signature. #[cfg(windows)] fn compiled() -> windows::core::Result> { + compile_fxc(SOURCE) +} + +#[cfg(windows)] +fn compile_fxc(source: &str) -> windows::core::Result> { let mut code: Option = None; let mut errors: Option = None; // SAFETY: the source and names live through the call; out pointers ours. let compiled = unsafe { D3DCompile( - SOURCE.as_ptr().cast(), - SOURCE.len(), + source.as_ptr().cast(), + source.len(), s!("clamp"), None, None, @@ -168,8 +236,11 @@ fn compiled() -> windows::core::Result> { } fn make() -> windows::core::Result { + make_pipeline(&compiled()?) +} + +fn make_pipeline(bytes: &[u8]) -> windows::core::Result { let device = &host().ok_or_else(windows::core::Error::empty)?.device; - let bytes = &compiled()?[..]; // SAFETY: the root signature is inside the shader. unsafe { let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; @@ -339,13 +410,79 @@ mod tests { } } + #[test] + fn argument_clamp_budget_never_wraps() { + let Some(host) = host() else { return }; + if cfg!(not(windows)) && std::env::var_os("VICTORY_DXCOMPILER").is_none() { + return; + } + let clamp_draws = |draws: &[[u32; 4]]| { + let bytes = size_of_val(draws) as u64; + let (input, data) = host.shared_buffer(bytes).unwrap(); + let list = host.new_list().unwrap(); + // SAFETY: the idle mapping holds all supplied draw records. + unsafe { + std::ptr::copy_nonoverlapping(draws.as_ptr(), data.cast(), draws.len()); + } + let output = bound(&list, (&input, 0), None, (0, 16, draws.len() as u32)) + .expect("clamp recorded"); + done(&list, &output); + list.close(); + host.execute(&[&list]); + // SAFETY: the clamp completed and each mapping covers the inspected records. + unsafe { + let mut mapped = std::ptr::null_mut(); + output.Map(0, None, Some(&mut mapped)).unwrap(); + let records = std::slice::from_raw_parts(mapped.cast::<[u32; 4]>(), draws.len()); + let counts = records.iter().map(|r| r[0]).collect::>(); + assert!(records.iter().zip(draws).all(|(clamped, src)| clamped[2..] == src[2..])); + assert_eq!(std::slice::from_raw_parts(data.cast::<[u32; 4]>(), draws.len()), draws); + output.Unmap(0, None); + counts + } + }; + + // Each clamped draw costs 2^26, so only two fit. The old add + // wrapped at 64 draws and let a further two through. + let large = [u32::MAX, 4, 11, 17]; + let counts = clamp_draws(&[large; 128]); + assert_eq!(counts.iter().filter(|&&vertices| vertices != 0).count(), 2); + + // Lane order within a group is fixed. After two draws, the third + // consumes the remainder and the small fourth draw is rejected. + let almost = [1 << 24, 3, 11, 17]; + assert_eq!( + clamp_draws(&[almost, almost, almost, [1, 1, 11, 17]]), + [1 << 24, 1 << 24, 0, 0] + ); + + let small = vec![[1, 1, 11, 17]; 1 << 16]; + assert!(clamp_draws(&small).iter().all(|&vertices| vertices == 1)); + } + #[test] fn argument_clamp_counted_dispatches_only_active_records() { let Some(host) = host() else { return }; if cfg!(not(windows)) && std::env::var_os("VICTORY_DXCOMPILER").is_none() { return; } - let c = clamp().expect("clamp pipeline"); + const WITNESS: &str = r#" +RWByteAddressBuffer output : register(u0); +[RootSignature("UAV(u0)")] +[numthreads(1, 1, 1)] +void main(uint3 group : SV_GroupID) { + if (all(group == 0)) { + uint unused; + output.InterlockedAdd(0, 128, unused); + } +} +"#; + #[cfg(windows)] + let witness = compile_fxc(WITNESS).expect("witness shader"); + #[cfg(not(windows))] + let witness = + victory_shader::hostlib::compile_hlsl(WITNESS, "main", "cs_6_0").expect("witness shader"); + let c = make_pipeline(&witness).expect("witness pipeline"); let argument = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() @@ -383,22 +520,16 @@ mod tests { let clamped = bound(&list, (&input, 0), Some((&input, 24)), (2, 12, 2)).unwrap(); assert_eq!(clamped, output); - // Reuse the clamp as a test compute pipeline. Each indirect - // dispatch adds 128 to its separate budget at `witnessed`. - let constants = [2u32, 12, 1, 0]; + // Each executed dispatch increments the same witness, even if + // the driver overlaps the commands in this ExecuteIndirect. // SAFETY: all buffers live through execution. The private buffer // is in INDIRECT_ARGUMENT and has distinct count and argument offsets. unsafe { let command = &list.list; - let gpu = input.GetGPUVirtualAddress(); let witness = witness.GetGPUVirtualAddress(); command.SetComputeRootSignature(&c.root); command.SetPipelineState(&c.pso); - command.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - command.SetComputeRootShaderResourceView(1, gpu); - command.SetComputeRootUnorderedAccessView(2, witness); - command.SetComputeRootUnorderedAccessView(3, witness + 256); - command.SetComputeRootShaderResourceView(4, gpu); + command.SetComputeRootUnorderedAccessView(0, witness); command.ExecuteIndirect(&signature, 2, &clamped, COUNT_BYTES, Some(&clamped), 0); } done(&list, &clamped);