diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index f4a3b95d8c..0abc5314e4 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1936,11 +1936,16 @@ pub(crate) unsafe fn record_indirect_slicer( list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); list.Dispatch(1, 1, 1); + // INDIRECT_ARGUMENT alone: vkd3d-proton hoists an ExecuteIndirect's preprocessing to the start + // of its command buffer (or of the submit) unless the list transitions something to exactly + // that state before it, so with any other bit set the pieces read the commands before this + // pass wrote them: zeros or a dispatch before's groups and slab origins (RADV: a TCP page + // fault where a split chain's indirect dispatch runs) list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(out), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER }) } }]); + StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }) } }]); Ok(()) } @@ -1950,7 +1955,7 @@ pub(crate) unsafe fn restore_indirect_commands(list: &ID3D12GraphicsCommandList, list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(commands), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, + StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS }) } }]); } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 0c064f8f93..62d5549b14 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3809,13 +3809,13 @@ unsafe fn execute_indirect_snapshot( if gfx && super::present::trace_frame() { trace_ui_draw(this, raw_pso, pso, true); } + // (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); // a split compute program's one Dispatch-only command runs its chain (`dispatch_chain`) if compute && max == 1 && count_buf == 0 && signature.dispatch_only().is_some() { use super::real::dispatch_chain::Indirect; - let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(Indirect::Whole), |address| { - super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, with(this, |s| s.allocator), address, - |root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3], None, 0).map(|_| ())) - }); + let chained = execute_indirect_chain(this, list, raw_pso, pso, with(this, |s| s.allocator), checked.as_ref(), args, args_off_title, args_off, + |root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3], None, 0).map(|_| ())); match chained { Ok(Indirect::Ran) => { ei_work(this, dispatches, super::targets::RAN); @@ -3834,8 +3834,6 @@ 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; @@ -3960,6 +3958,36 @@ fn take_indirect_skip_counts() -> [u32; 2] { INDIRECT_SKIP_COUNTS.with(|counts| counts.replace([0; 2])) } +/// A split compute program's one Dispatch-only ExecuteIndirect through its chain +/// (`dispatch_chain::execute_indirect`, `allocator` the list's), from the counts as the guard let +/// them through (`checked`; the title's own where it checks none): the slicer clamps each count to +/// 65 535 but runs a partial split's whole count in one dispatch, up to 65 535^3 groups of +/// garbage. `bind(root)` binds the program's arguments under the chain's root signature. +pub(super) unsafe fn execute_indirect_chain( + this: *mut c_void, list: &ID3D12GraphicsCommandList, raw_pso: usize, pso: usize, allocator: usize, + checked: Option<&super::indirect_guard::Checked>, args: usize, args_off_title: u64, args_off: u64, + bind: impl FnOnce(usize) -> Result<(), String>, +) -> Result { + use super::real::dispatch_chain::Indirect; + let address = match checked { + Some(c) => Some(c.gpu_address()), + None => indirect_address(args, args_off_title, args_off), + }; + let Some(address) = address else { return Ok(Indirect::Whole) }; + let (out, _) = checked.map_or((0, 0), |c| c.arguments()); + let chained = super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, allocator, address, bind, + // (the slicer reads the checked counts as a root SRV; only when a chain records it) + |reading| if out != 0 { + let (uav, srv) = (D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + let (before, after) = if reading { (uav, srv) } else { (srv, uav) }; + super::list_x::transition(this, out, before, after); + }); + if let (Some(c), Ok(Indirect::Ran) | Err(_)) = (checked, &chained) { + c.read(this); + } + chained +} + unsafe fn indirect_address(resource: usize, title_offset: u64, pc_offset: u64) -> Option { match super::real::console_buffer(resource) { Some((base, size)) if title_offset.checked_add(12).is_some_and(|end| end <= size as u64) => { diff --git a/crates/xcl/src/hle/d3d12x/indirect_guard.rs b/crates/xcl/src/hle/d3d12x/indirect_guard.rs index e34169cfc4..7b9f873689 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_guard.rs +++ b/crates/xcl/src/hle/d3d12x/indirect_guard.rs @@ -199,11 +199,13 @@ unsafe fn guard_of(list: &ID3D12GraphicsCommandList) -> Option> { let mut dev: Option = None; list.GetDevice(&mut dev).ok()?; let dev = dev?; + // (before `GUARD`: DXC's pool may make the first ExecuteIndirect wait, `counts` must not) + let dxil = dxil(); let mut g = GUARD.lock().unwrap(); if let Some(g) = g.as_ref().filter(|g| g.dev == dev.as_raw() as usize) { return Some(g.clone()); } - match super::title_textures::own_work(|| make(&dev)) { + match super::title_textures::own_work(|| make(&dev, dxil)) { Ok(n) => { let n = Arc::new(n); *g = Some(n.clone()); @@ -217,11 +219,16 @@ unsafe fn guard_of(list: &ID3D12GraphicsCommandList) -> Option> { } } -unsafe fn make(dev: &ID3D12Device) -> Result { - let cs = real::compile(&program(), "cs_5_0"); - if cs.is_empty() { - return Err("its program does not compile".into()); - } +/// The guard's program as DXIL, compiled once for every device. DXC, not D3DCompile: Wine's +/// d3dcompiler (vkd3d-shader) has no Load3 on a RWByteAddressBuffer, so under Wine the guard +/// never ran and garbage counts reached the GPU (RADV: a ring timeout in a DISPATCH_INDIRECT of a +/// small program). +fn dxil() -> &'static Result, String> { + static DXIL: std::sync::OnceLock, String>> = std::sync::OnceLock::new(); + DXIL.get_or_init(|| crate::gpu::recomp::dxc::compile(&program(), "main", "cs_6_0", &[])) +} + +unsafe fn make(dev: &ID3D12Device, dxil: &Result, String>) -> Result { let root = |ty, anonymous| D3D12_ROOT_PARAMETER { ParameterType: ty, Anonymous: anonymous, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL }; let uav = |k| root(D3D12_ROOT_PARAMETER_TYPE_UAV, D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: k, RegisterSpace: 0 } }); let params = [ @@ -236,10 +243,22 @@ unsafe fn make(dev: &ID3D12Device) -> Result { D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("root signature: {e}"))?; let blob = blob.ok_or("root signature")?; let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())).map_err(|e| format!("CreateRootSignature: {e}"))?; - let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }; - let pso: ID3D12PipelineState = dev - .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }) - .map_err(|e| format!("CreateComputePipelineState: {e}"))?; + let pso_of = |cs: &[u8]| -> Result { + let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }; + dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }) + .map_err(|e| format!("CreateComputePipelineState: {e}")) + }; + // D3DCompile's when DXC failed, or the device refused its DXIL (unsigned: no dxil.dll) + let pso = match dxil.as_ref().map_err(String::clone).and_then(|cs| pso_of(cs)) { + Ok(pso) => pso, + Err(e) => { + let cs = real::compile(&program(), "cs_5_0"); + if cs.is_empty() { + return Err(format!("its program does not compile ({e})")); + } + pso_of(&cs).map_err(|e5| format!("{e5} (DXC: {e})"))? + } + }; let buffer = |heap: D3D12_HEAP_PROPERTIES, width: u64| -> Result { let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, @@ -376,6 +395,12 @@ impl Checked { (self.guard.out.as_raw() as usize, self.slot as u64 * SLOT as u64) } + /// The GPU address of the checked counts (`arguments`), for a pass that reads them through a + /// root view; `read` after it. + pub(super) fn gpu_address(&self) -> u64 { + self.guard.out_va + self.slot as u64 * SLOT as u64 + } + /// After a pass read the counts at `arguments`: the buffer back to COMMON (its write and that /// read left it in UNORDERED_ACCESS). pub(super) unsafe fn read(&self, list: *mut c_void) { @@ -447,7 +472,7 @@ fn report(g: &Guard) { } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::super::list_x; use super::*; use crate::gpu::{fence, recomp::runner::skip_test}; @@ -456,7 +481,7 @@ mod tests { type Close = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT; /// the guard (and its count of what was out of range) is the device's: one test at a time - static ONE: Mutex<()> = Mutex::new(()); + pub(in crate::hle::d3d12x) static ONE: Mutex<()> = Mutex::new(()); unsafe fn device() -> Option { let mut dev: Option = None; @@ -529,6 +554,18 @@ mod tests { assert_eq!(counts_va_in(0x100, in_one_window, va_of), None, "not in a window"); } + /// The guard's program compiles with DXC (`make`): Wine's D3DCompile refuses it, which left + /// the guard off in every run under Wine. + #[test] + fn the_guards_program_compiles_with_dxc() { + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let dxil = crate::gpu::recomp::dxc::compile(&program(), "main", "cs_6_0", &[]).unwrap(); + assert!(!dxil.is_empty()); + } + #[test] fn a_counter_is_logged_at_its_first_values_and_at_each_doubling_however_it_jumps() { assert!(logged_again(0, 1) && logged_again(0, 7) && logged_again(3, 5)); @@ -562,7 +599,12 @@ void main() { c.InterlockedAdd(0, 1u); } unsafe { let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); let Some(dev) = device() else { return }; - let cs = real::compile(src, "cs_5_0"); + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + // (DXC: Wine's D3DCompile has no InterlockedAdd on a RWByteAddressBuffer either) + let cs = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_0", &[]).unwrap(); assert!(!cs.is_empty()); let param = D3D12_ROOT_PARAMETER { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, @@ -593,11 +635,13 @@ void main() { c.InterlockedAdd(0, 1u); } let raw = list.as_raw(); type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let ei: Ei = std::mem::transmute(real::orig_fn(raw, 59)); - let before = GUARD.lock().unwrap().as_ref().map_or(0, |g| bad_so_far(g)); if let Some(g) = GUARD.lock().unwrap().as_ref() { g.next.store(0, Ordering::Relaxed); } let checked = check(raw, 0, s, 1, a, off, 0).expect("checked"); + // (after `check`: the guard is the device's, and the test before may have left + // another device's; nothing is counted until the list runs) + let before = bad_so_far(&checked.guard); assert!(k == 0 || checked.slot == 0); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); @@ -647,7 +691,14 @@ void main() { c.InterlockedAdd(0, 1u); } let (_alloc, list) = title_list(&dev, ty); let raw = list.as_raw(); let sig = if is_indexed { &indexed } else { &plain }; - let checked = check(raw, 0, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0).expect("checked"); + let Some(checked) = check(raw, 0, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0) else { + // (no guard without a compiler for its program: under Wine that takes DXC) + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + panic!("checked"); + }; // (the arguments, copied out instead of drawn) checked.run(raw, |b, o| { list_x::transition(raw, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6f6172165d..b968575807 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -587,9 +587,11 @@ pub(in crate::hle::d3d12x) enum Indirect { /// (`pso::chain_command_signature`), so it waits for no other build. The slicer writes either /// bounded piece commands or the whole-form command, never a partial chain; the latter is left out /// while the whole form is not there (queued as for `whole_ready`, never waited for). +/// `around_slicer(true)` and `(false)` bracket the one pass that reads `args`, only when it is +/// recorded. pub(in crate::hle::d3d12x) unsafe fn execute_indirect( list: &ID3D12GraphicsCommandList, original: usize, pso: usize, allocator: usize, args: u64, - bind: impl FnOnce(usize) -> Result<(), String>, + bind: impl FnOnce(usize) -> Result<(), String>, mut around_slicer: impl FnMut(bool), ) -> Result { let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(Indirect::Whole) }; note_indirect_use(&chain); @@ -617,10 +619,13 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( &chain.builder.device, list.as_raw() as usize, allocator, command_bytes, ).ok_or("no command buffer for split ExecuteIndirect")?; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - pso::record_indirect_slicer( + around_slicer(true); + let sliced = pso::record_indirect_slicer( list, args, rounds, (scratch.bytes / group).max(1), &commands.buffer, |slicer| super::bind_pipeline_exact(list.as_raw(), original, slicer.as_raw() as usize), - )?; + ); + around_slicer(false); + sliced?; let bound = bind(chain.builder.signature.as_raw() as usize); if bound.is_ok() { if let Some(whole) = &whole { @@ -796,7 +801,7 @@ mod tests { let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); let args = pso::chain_commands_buffer(&dev, 1).unwrap(); - assert_eq!(execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into())), Err("bind failed".into())); + assert_eq!(execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into()), |_| {}), Err("bind failed".into())); let recorded = RECORDINGS.lock().unwrap().get(&allocator).unwrap()[0]._indirect_commands.clone().unwrap(); let reused = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); assert!(Arc::ptr_eq(&recorded, &reused)); @@ -854,8 +859,13 @@ mod tests { list.SetComputeRootSignature(&rs); Ok(()) }; + // (the guard's transitions around the slicer: none where no chain records one) + let mut around = Vec::new(); + assert_eq!(execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_| Ok(()), |r| around.push(r)), Ok(Indirect::Whole)); + assert!(around.is_empty(), "no slicer, no transitions"); CHAINS.lock().unwrap().insert(key, chain); - assert_eq!(execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), bind), Ok(Indirect::Ran)); + assert_eq!(execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), bind, |r| around.push(r)), Ok(Indirect::Ran)); + assert_eq!(around, [true, false], "the slicer bracketed once"); let ran = CHAINS.lock().unwrap().get(&key).cloned().unwrap(); assert!(ran.whole.ready().is_none(), "the whole form was not built"); type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT; @@ -868,6 +878,117 @@ mod tests { } } + /// A split program's indirect dispatch runs its chain from the counts the guard let through + /// (`bind::execute_indirect_chain`), not from the title's buffer: the slicer, the one pass that + /// reads them, writes no groups for garbage there, where it would clamp it to 65 535 groups. + /// And the pieces run the groups the slicer wrote: vkd3d-proton ran their ExecuteIndirects + /// from the commands as they were before it (`pso::record_indirect_slicer`). + #[test] + fn a_split_indirect_dispatch_slices_the_counts_the_guard_let_through() { + use super::super::super::{bind, indirect_guard, list_x}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe extern "system" fn never(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } + // the counts in the title's buffer, and the groups the slicer may hand the pieces + let cases: [([u32; 3], u64); 3] = [([3, 2, 1], 6), ([1, 1, 0x1_0000], 0), ([2, 1, 1], 2)]; + unsafe { + let _one = indirect_guard::tests::ONE.lock().unwrap_or_else(|e| e.into_inner()); + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev: ID3D12Device = dev.unwrap(); + // (a piece that counts its groups, in the ABI's first root UAV) + let src = "RWByteAddressBuffer c : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { c.InterlockedAdd(0, 1u); }"; + let Ok(dxil) = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_0", &[]) else { + return crate::gpu::recomp::runner::skip_test("no DXC"); + }; + let rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; + let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain }); + let key = first.as_raw() as usize; + CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: Vec::new(), words: 4, whole_code: Vec::new(), + whole: WholeBuild::new(), indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(true) })); + // buffers the CPU and the GPU see: the title's arguments, the slicer's commands, the + // groups run + let cpu_buffer = |width: u64| { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: width, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() }; + 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 rounds = indirect_rounds(); + let command_bytes = pso::chain_tail_offset(rounds) + 12; + let ((args, args_at), (sliced, sliced_at), (ran, ran_at)) = (cpu_buffer(256), cpu_buffer(command_bytes), cpu_buffer(256)); + let arg = 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, NodeMask: 0 }, None, &mut sig).unwrap(); + let sig = sig.unwrap(); + indirect_guard::note_signature(sig.as_raw() as usize, &[D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0]); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let transition = |r: &ID3D12Resource, before, after| D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new( + D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(r), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, StateAfter: after }) } }; + for (want, runs) in cases { + for (i, w) in want.iter().enumerate() { + *args_at.add(i) = *w; + } + *ran_at = 0; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + // (a list as XCL has a title's) + super::super::adopt(list.as_raw(), Kind::CommandList); + list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); + let (raw, allocator) = (list.as_raw(), alloc.as_raw() as usize); + super::super::super::alloc_pool::created_on(raw as usize, allocator, ty.0); + let Some(checked) = indirect_guard::check(raw, key, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0) else { + panic!("{want:x?}: checked"); + }; + let bind = |root: usize| { + assert_eq!(root, rs.as_raw() as usize); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, ran.GetGPUVirtualAddress()); + Ok(()) + }; + let chained = bind::execute_indirect_chain(raw, &list, key, key, allocator, Some(&checked), args.as_raw() as usize, 0, 0, bind); + assert_eq!(chained, Ok(Indirect::Ran), "{want:x?}"); + // what the slicer wrote, for the CPU + let commands = RECORDINGS.lock().unwrap().get(&allocator).unwrap().last().unwrap()._indirect_commands.clone().unwrap(); + list.ResourceBarrier(&[transition(&commands.buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&sliced, 0, &commands.buffer, 0, command_bytes); + list.ResourceBarrier(&[transition(&commands.buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT; + let close: Close = std::mem::transmute(super::super::orig_fn(raw, 9)); + assert!(close(raw) >= 0, "{want:x?}: the recorded chain closes"); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + // each round's Dispatch arguments, then the whole form's + let groups = |at: u64| (0..3).map(|i| u64::from(std::ptr::read_volatile(sliced_at.add(at as usize / 4 + i)))).product::(); + let total: u64 = (0..rounds).map(|r| groups(pso::chain_tail_offset(r) + pso::CHAIN_DISPATCH_AT)).sum::() + + groups(pso::chain_tail_offset(rounds)); + assert_eq!(total, runs, "{want:x?}: groups sliced"); + assert_eq!(u64::from(std::ptr::read_volatile(ran_at)), runs, "{want:x?}: groups the pieces ran"); + allocator_reset(allocator); + list_reset(raw as usize); + super::super::super::alloc_pool::forget_list(raw as usize); + } + forget(key); + } + } + #[test] fn remap_compile_oom_retries_but_deterministic_failure_is_final() { let at = std::time::Instant::now();