From f59aa43937d0669c23fa33b34312d4986d8cfeb4 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:19:54 -0500 Subject: [PATCH] D3D12.X: clean up indirect_guard state on ExecuteIndirect skip paths --- crates/xcl/src/hle/d3d12x/bind.rs | 359 ++++++++++++++++++++++++++---- 1 file changed, 317 insertions(+), 42 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e2d454243d..fced31e818 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3788,52 +3788,54 @@ unsafe fn execute_indirect_snapshot( } } } - // (binds a compute root signature and a pipeline: before the dispatch's or draw's own) - let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf); - match bind_abi_resolved(this, list, raw_pso, pso, gfx) { - Ok(b) => { - let mut whole = None; - if compute { - // a wave-local remapped program runs its whole form: the GPU's group counts - // cannot be scaled - if super::real::pso_dispatch_remap_exact(pso).is_some() { - match super::real::remap_fallback::whole_exact(pso) { - Ok(fallback) => whole = Some(fallback), - Err(e) => { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect remap fallback skipped: {e}"); - } - ei_work(this, dispatches, super::targets::SKIPPED); - count(DISPATCHES_SKIPPED); - return; - } + let mut whole = None; + if compute { + // Resolve any whole-program fallback before `indirect_guard::check` and + // `bind_abi_resolved`: a late or failed whole build skips the command without + // dispatching the guard, leaving `indirect_guard`'s shared buffer in + // UNORDERED_ACCESS, or mutating the list's root signature and pipeline state. + if super::real::pso_dispatch_remap_exact(pso).is_some() { + match super::real::remap_fallback::whole_exact(pso) { + Ok(fallback) => whole = Some(fallback), + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect remap fallback skipped: {e}"); } + ei_work(this, dispatches, super::targets::SKIPPED); + count(DISPATCHES_SKIPPED); + return; } - match super::real::dispatch_chain::whole_ready(pso) { - Ok(super::real::dispatch_chain::Whole::Plain) => {} - Ok(super::real::dispatch_chain::Whole::Ready(w)) => whole = Some(w), - Ok(super::real::dispatch_chain::Whole::Late) => { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - let n = N.fetch_add(1, Ordering::Relaxed) + 1; - if n <= 4 || n.is_power_of_two() { - crate::xlog_warn!("D3D12.X: ExecuteIndirect of a split compute program whose whole form is still being built skipped ({n} so far)"); - } - ei_work(this, dispatches, super::targets::SKIPPED); - count(DISPATCHES_SKIPPED); - return; - } - Err(e) => { - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); - } - ei_work(this, dispatches, super::targets::SKIPPED); - count(DISPATCHES_SKIPPED); - return; - } + } + } + match super::real::dispatch_chain::whole_ready(pso) { + Ok(super::real::dispatch_chain::Whole::Plain) => {} + Ok(super::real::dispatch_chain::Whole::Ready(w)) => whole = Some(w), + Ok(super::real::dispatch_chain::Whole::Late) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: ExecuteIndirect of a split compute program whose whole form is still being built skipped ({n} so far)"); } + ei_work(this, dispatches, super::targets::SKIPPED); + count(DISPATCHES_SKIPPED); + return; + } + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); + } + ei_work(this, dispatches, super::targets::SKIPPED); + count(DISPATCHES_SKIPPED); + return; } + } + } + // (binds a compute root signature and a pipeline: before the dispatch's or draw's own) + let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf); + match bind_abi_resolved(this, list, raw_pso, pso, gfx) { + Ok(b) => { // one dispatch: its group counts (as the guard let them through) folded or clamped on // the GPU (`clamp`, which writes a folded count into this dispatch's io), then the // binding set again. Only on a direct or compute list XCL keeps state for, as @@ -3872,6 +3874,13 @@ unsafe fn execute_indirect_snapshot( super::gpu_profile::end(this, t); } Err(e) => { + if let Some(c) = &checked { + // `indirect_guard::check` promoted its shared output buffer to UNORDERED_ACCESS + // and bound its own compute pipeline; return the buffer to COMMON and restore + // the list's resolved pipeline so later work on this list or submit stays valid. + c.read(this); + super::real::bind_pipeline_exact(this, raw_pso, pso); + } ei_work(this, dispatches, super::targets::SKIPPED); count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -10073,4 +10082,270 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) assert_eq!(TWO_PASS[TP_SHRUNK].load(Ordering::Relaxed), shrunk_before); } } + + /// A compute `ExecuteIndirect` whose remap whole-program fallback is unavailable must skip + /// before running `indirect_guard::check` or `bind_abi_resolved` so neither guard state nor + /// command-list bindings are touched. + #[test] + fn execute_indirect_remap_fallback_error_skips_before_guard_and_abi() { + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[25] = fake_set_pso as usize; + orig_vt[59] = fake_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + last_pso: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list = &*fake as *const FakeAdoptedList as *mut c_void; + let pso = 0x7100_9100usize; + real::register_translated_compute_for_test(pso); + // Register a dispatch remap with no fallback source so `remap_fallback::whole_exact` fails. + real::register_compute_metadata_for_test(pso, 0, [64, 1, 1], (2, 1), 0); + with(list, |state| { + state.pso = pso; + state.resolution = None; + }); + STOP_ABI_LIST.store(list as usize, Ordering::Release); + LAST_ABI_PSO.store(0, Ordering::Release); + let skipped_before = counts_snapshot()[4]; + + unsafe { + execute_indirect_retained( + list, + 1, + 1, + 0, + 0, + 0, + 0, + IndirectSignatureInfo::new(true, false, None), + ); + } + + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), 0, "failed remap fallback reached bind_abi_resolved"); + assert_eq!(fake.dispatch_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_pso_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + assert!(counts_snapshot()[4] > skipped_before, "expected DISPATCHES_SKIPPED increment"); + + STOP_ABI_LIST.store(0, Ordering::Release); + forget(list); + real::forget_pso_for_test(pso); + } + + /// Real-GPU verification of `execute_indirect` guard cleanup on both skip paths: + /// 1. A failed compute whole-program fallback skips before `indirect_guard::check` so the + /// command list's root signature and pipeline stay intact. + /// 2. A `bind_abi_resolved` error after `indirect_guard::check` transitions `indirect_guard`'s + /// shared buffer back to COMMON and restores the resolved pipeline so subsequent work on the + /// same list and on another list in the same submit runs cleanly on the GPU. + #[test] + fn gpu_execute_indirect_guard_cleanup_on_abi_error_and_whole_skip() { + use crate::gpu::{fence, recomp::runner::skip_test}; + use windows::Win32::Graphics::Direct3D::{ID3DBlob, D3D_FEATURE_LEVEL_11_0}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + + let _stop_abi = STOP_ABI_TEST.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + skip_test("no GPU"); + return; + } + let Some(dev) = dev else { + skip_test("no GPU"); + return; + }; + let cs = real::compile( + "RWByteAddressBuffer outp : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { outp.Store(0, 0xCAFEBABEu); }\n", + "cs_5_0", + ); + assert!(!cs.is_empty()); + let param = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let rs_desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: 1, pParameters: ¶m, ..Default::default() }; + let mut blob: Option = None; + D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).unwrap(); + let blob = blob.unwrap(); + let rs: ID3D12RootSignature = dev + .CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .unwrap(); + let pso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + ..Default::default() + }) + .unwrap(); + + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let arg_desc = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let mut sig: Option = None; + dev.CreateCommandSignature( + &D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg_desc, NodeMask: 0 }, + None, + &mut sig, + ) + .unwrap(); + let sig = sig.unwrap(); + let sig_raw = sig.as_raw() as usize; + super::super::indirect_guard::note_signature(sig_raw, &[D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0]); + + let make_buf = |bytes: u64| -> (ID3D12Resource, *mut u32) { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let r = r.unwrap(); + let mut p = std::ptr::null_mut(); + r.Map(0, None, Some(&mut p)).unwrap(); + (r, p as *mut u32) + }; + let (args, args_at) = make_buf(256); + *args_at.add(0) = 1; + *args_at.add(1) = 1; + *args_at.add(2) = 1; + let (out1, out1_at) = make_buf(256); + let (out2, out2_at) = make_buf(256); + let (out3, out3_at) = make_buf(256); + *out1_at = 0; + *out2_at = 0; + *out3_at = 0; + + let make_list = || -> (ID3D12CommandAllocator, ID3D12GraphicsCommandList) { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + real::adopt(list.as_raw(), real::Kind::CommandList); + list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); + (alloc, list) + }; + let (_a1, list1) = make_list(); + let (_a2, list2) = make_list(); + let (_a3, list3) = make_list(); + let pso_raw = pso.as_raw() as usize; + + // 1. Remap fallback failure skips before `indirect_guard::check`: neither the bound + // root signature nor the bound pipeline on `list1` is disturbed. + real::register_translated_compute_for_test(pso_raw); + real::register_compute_metadata_for_test(pso_raw, 0, [64, 1, 1], (2, 1), 0); + list1.SetComputeRootSignature(&rs); + real::bind_pipeline_exact(list1.as_raw(), pso_raw, pso_raw); + list1.SetComputeRootUnorderedAccessView(0, out1.GetGPUVirtualAddress()); + with(list1.as_raw(), |s| { + s.pso = pso_raw; + s.resolution = None; + }); + STOP_ABI_LIST.store(list1.as_raw() as usize, Ordering::Release); + LAST_ABI_PSO.store(0, Ordering::Release); + execute_indirect_retained( + list1.as_raw(), + sig_raw, + 1, + args.as_raw() as usize, + 0, + 0, + 0, + IndirectSignatureInfo::new(true, false, None), + ); + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), 0, "whole-skip must not reach bind_abi_resolved"); + // Dispatch without rebinding root signature or pipeline: works only if guard never ran. + list1.Dispatch(1, 1, 1); + + // 2. `bind_abi_resolved` error after `indirect_guard::check`: guard ran and bound its + // own compute PSO and promoted `g.out` to UNORDERED_ACCESS; error cleanup must + // transition `g.out` back to COMMON and restore `pso` on `list2`. + real::forget_pso_for_test(pso_raw); + real::register_translated_compute_for_test(pso_raw); + real::bind_pipeline_exact(list2.as_raw(), pso_raw, pso_raw); + with(list2.as_raw(), |s| { + s.pso = pso_raw; + s.resolution = None; + }); + STOP_ABI_LIST.store(list2.as_raw() as usize, Ordering::Release); + LAST_ABI_PSO.store(0, Ordering::Release); + execute_indirect_retained( + list2.as_raw(), + sig_raw, + 1, + args.as_raw() as usize, + 0, + 0, + 0, + IndirectSignatureInfo::new(true, false, None), + ); + assert_eq!(LAST_ABI_PSO.load(Ordering::Acquire), pso_raw, "expected bind_abi_resolved to be entered and fail"); + // Re-set compute root signature/UAV but intentionally do NOT re-call SetPipelineState: + // this succeeds only if error cleanup restored `pso` over `indirect_guard`'s PSO. + list2.SetComputeRootSignature(&rs); + list2.SetComputeRootUnorderedAccessView(0, out2.GetGPUVirtualAddress()); + list2.Dispatch(1, 1, 1); + + // 3. A second command list in the same submission uses `indirect_guard` cleanly with + // `g.out` back in COMMON after `list2`'s cleanup transition. + let checked = super::super::indirect_guard::check(list3.as_raw(), 0, sig_raw, 1, args.as_raw() as usize, 0, 0) + .expect("guard check on list3"); + type EiFn = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); + let ei: EiFn = std::mem::transmute(real::orig_fn(list3.as_raw(), 59)); + list3.SetComputeRootSignature(&rs); + real::bind_pipeline_exact(list3.as_raw(), pso_raw, pso_raw); + list3.SetComputeRootUnorderedAccessView(0, out3.GetGPUVirtualAddress()); + checked.run(list3.as_raw(), |b, o| ei(list3.as_raw(), sig_raw, 1, b, o, 0, 0)); + + type CloseFn = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT; + for l in [&list1, &list2, &list3] { + let close: CloseFn = std::mem::transmute(real::orig_fn(l.as_raw(), 9)); + close(l.as_raw()).unwrap(); + } + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.ExecuteCommandLists(&[ + Some(list1.cast().unwrap()), + Some(list2.cast().unwrap()), + Some(list3.cast().unwrap()), + ]); + queue.Signal(&done, 1).unwrap(); + fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + + assert_eq!(std::ptr::read_volatile(out1_at), 0xCAFE_BABEu32, "whole-skip must leave list1 root signature and pipeline intact"); + assert_eq!(std::ptr::read_volatile(out2_at), 0xCAFE_BABEu32, "ABI error cleanup must restore resolved pipeline over indirect_guard's PSO"); + assert_eq!(std::ptr::read_volatile(out3_at), 0xCAFE_BABEu32, "second list's checked ExecuteIndirect must run cleanly after g.out returned to COMMON"); + + STOP_ABI_LIST.store(0, Ordering::Release); + super::super::indirect_guard::note_signature(sig_raw, &[]); + real::forget_pso_for_test(pso_raw); + for l in [&list1, &list2, &list3] { + forget(l.as_raw()); + list_x::on_release(l.as_raw() as usize); + } + } + } }