From b1d2ab604b848b3d054a66c8b3b55c2dd2c4eaad Mon Sep 17 00:00:00 2001 From: Utkarsh Bhatnagar Date: Tue, 24 Nov 2026 12:34:56 +0530 Subject: [PATCH] D3D12.X: repack root-changing ExecuteIndirect commands on the GPU Translated pipelines use XCL's ABI root signature and cannot consume a title's root-changing command signature directly. Repack standard draw and dispatch commands on the GPU so each command sees its own root values and the native call retains the count buffer. --- README.md | 3 + crates/xcl/src/hle/d3d12x/bind.rs | 67 ++- crates/xcl/src/hle/d3d12x/device_x.rs | 9 +- crates/xcl/src/hle/d3d12x/indirect.rs | 479 ++++++++++++++++++ .../xcl/src/hle/d3d12x/indirect_repack.hlsl | 41 ++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 12 + 7 files changed, 584 insertions(+), 28 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/indirect.rs create mode 100644 crates/xcl/src/hle/d3d12x/indirect_repack.hlsl diff --git a/README.md b/README.md index 4d1932d2a..bd8ae9b43 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,9 @@ next steps: | **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU | | **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output | +Translated draw, indexed draw and compute dispatch signatures can update root constants and +buffer descriptors per indirect command when their arguments are in unified memory or an upload heap. + ### Media and tools | Feature | State | What it does | Verified by | diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e0c1518fa..32abd0cda 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -17,6 +17,7 @@ use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use super::console_list::{self, Layout, Param}; +use super::indirect; #[derive(Default)] struct State { @@ -222,22 +223,15 @@ fn note_address(va: u64) { } } -/// command signatures that change root arguments (they need the title's root signature) -static ROOT_SIGNATURES: Mutex>> = Mutex::new(None); - -pub(super) fn note_root_changing_signature(sig: usize) { - ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig); -} - /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a -/// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root -/// arguments themselves cannot be – skipped, logged) +/// translated pipeline, on XCL's ABI with the kept root arguments and any per-command updates. pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); - let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); + let args_pc_off = args_off + super::real::buffer_delta(args); + let count_off = count_off + super::real::buffer_delta(count_buf); if !gfx && !compute { // A pipeline still being built (or whose build failed): its stand-in draws nothing, and // the list may hold XCL's ABI root signature from a translated draw before it – the PC @@ -257,20 +251,32 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { list.SetGraphicsRootSignature(r); } - return pc(this, sig, max, args, args_off, count_buf, count_off); - } - if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { - 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 that changes root arguments with a translated pipeline skipped"); - } - return; + return pc(this, sig, max, args, args_pc_off, count_buf, count_off); } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - match bind_abi(this, list, pso, gfx) { + let result = match indirect::lookup(sig) { + Some(Some(signature)) => { + let repack = indirect::Repack { signature: &signature, resource: args, offset: args_off, max, gfx }; + bind_abi_before(this, list, pso, gfx, |layout, inline, shadow, io, root| { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + repack.record(list, root, layout.ok_or("no bound console root layout")?, inline, shadow, io, |size| { + with(this, |s| s.arena.take(u, size, 16, &mut s.uma)).map(|p| p as usize) + }) + }).map(|packed| { + pc(this, packed.signature.as_raw() as usize, max, packed.arguments.as_raw() as usize, 0, count_buf, count_off); + packed.finish_gpu(list); + with(this, |s| { + let shadow = if gfx { &mut s.args_gfx } else { &mut s.args }; + packed.retain_and_clear(s.allocator, shadow); + }); + }) + } + Some(None) => Err("unsupported root-changing command signature".into()), + None => bind_abi(this, list, pso, gfx).map(|()| pc(this, sig, max, args, args_pc_off, count_buf, count_off)), + }; + match result { Ok(()) => { count(if gfx { DRAWS } else { DISPATCHES }); - pc(this, sig, max, args, args_off, count_buf, count_off) } Err(e) => { count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); @@ -854,6 +860,13 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { + bind_abi_before(this, list, pso, gfx, |_, _, _, _, _| Ok(())) +} + +unsafe fn bind_abi_before( + this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, + before: impl FnOnce(Option<&Layout>, usize, &[u8], &[u32], &ID3D12RootSignature) -> Result, +) -> Result { let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; @@ -883,6 +896,9 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; let rs = rs as *mut c_void; let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; + let pc = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pc).ok_or("pipeline")?; + let value = before(layout.as_deref(), inline, &args, &io, rs)?; let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); if gfx { list.SetGraphicsRootSignature(rs); @@ -895,10 +911,8 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi list.SetComputeRootUnorderedAccessView(k as u32, v); } } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; list.SetPipelineState(pc); - Ok(()) + Ok(value) } #[cfg(test)] @@ -1124,7 +1138,7 @@ mod tests { let standin_ok = 0x7200_0001usize; let real_ok = 0x7200_0002usize; let sig_root_changing = 0x7200_00F0usize; - note_root_changing_signature(sig_root_changing); + indirect::register(sig_root_changing, 0, &[]); pso_async::submit( standin_ok, @@ -1140,8 +1154,8 @@ mod tests { reset(list_ptr, 0x7200_0100, standin_ok); unsafe { - // With `sig_root_changing`, a translated compute PSO is caught by the root-changing - // guard instead of falling through to `pc` (which happened when `R` wasn't registered). + // A translated compute PSO rejects this unsupported signature. Missing the + // resolved translation would send it through the PC path. execute_indirect(list_ptr, sig_root_changing, 1, 0, 0, 0, 0); } assert_eq!( @@ -1184,6 +1198,7 @@ mod tests { ); forget(list_ptr); + indirect::forget(sig_root_changing); let _ = pso_async::released(standin_ok); let _ = pso_async::released(standin_fail); real::forget_pso_for_test(real_ok); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 2af03a02d..746a153b8 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1015,8 +1015,13 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); - if hr >= 0 && !ppv.is_null() && needs_root { - super::bind::note_root_changing_signature(*ppv as usize); + if hr >= 0 && !(*ppv).is_null() { + if needs_root { + let stride = u32::from_le_bytes(pc[..4].try_into().unwrap()); + super::indirect::register(*ppv as usize, stride, &list); + } else { + super::indirect::forget(*ppv as usize); + } } hr } diff --git a/crates/xcl/src/hle/d3d12x/indirect.rs b/crates/xcl/src/hle/d3d12x/indirect.rs new file mode 100644 index 000000000..dd233b89d --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indirect.rs @@ -0,0 +1,479 @@ +//! Repack root-changing indirect draws and dispatches on the GPU. The native signature +//! consumes an ABI io UAV address followed by the draw or dispatch arguments for each item. +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::{Arc, Mutex}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::{console_list::{Layout, Param}, real}; +use crate::gpu::recomp::{self, KERNEL_SGPRS}; + +const IO_BYTES: u32 = 4 * KERNEL_SGPRS as u32; +const THREADS: u32 = 64; +const CONFIG_WORDS: u32 = 13; + +#[derive(Clone, Copy)] +enum RootArg { + Constants { index: usize, offset: u32, words: u32 }, + Descriptor { index: usize }, +} + +pub(super) struct Signature { + stride: u32, + root: Vec<(u32, RootArg)>, + action: D3D12_INDIRECT_ARGUMENT_TYPE, + action_offset: u32, + action_bytes: u32, +} + +// An entry without a layout still identifies a root-changing signature. Its original +// signature can only be run with the title's root signature. +static SIGNATURES: Mutex>>>> = Mutex::new(None); + +pub(super) fn register(sig: usize, stride: u32, args: &[[u32; 4]]) { + SIGNATURES.lock().unwrap().get_or_insert_with(HashMap::new) + .insert(sig, Signature::parse(stride, args).map(Arc::new)); +} + +pub(super) fn lookup(sig: usize) -> Option>> { + SIGNATURES.lock().unwrap().as_ref()?.get(&sig).cloned() +} + +pub(super) fn forget(sig: usize) { + if let Some(sigs) = SIGNATURES.lock().unwrap().as_mut() { + sigs.remove(&sig); + } +} + +impl Signature { + fn parse(stride: u32, args: &[[u32; 4]]) -> Option { + let ([action, ..], root_args) = args.split_last()?; + let action = D3D12_INDIRECT_ARGUMENT_TYPE(*action as i32); + let action_bytes = match action { + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW => 16, + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED => 20, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH => 12, + _ => return None, + }; + let mut root = Vec::with_capacity(root_args.len()); + let mut at = 0u32; + for &[kind, index, offset, words] in root_args { + let index = index as usize; + let (arg, bytes) = match D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32) { + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT if words != 0 => (RootArg::Constants { index, offset, words }, words.checked_mul(4)?), + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW + | D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW + | D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW => (RootArg::Descriptor { index }, 8), + _ => return None, + }; + root.push((at, arg)); + at = at.checked_add(bytes)?; + } + if root.is_empty() || stride % 4 != 0 || at.checked_add(action_bytes)? > stride { + return None; + } + Some(Self { stride, root, action, action_offset: at, action_bytes }) + } + + fn patches(&self, layout: &Layout, inline: u32, gfx: bool) -> Option> { + let mut result = Vec::new(); + for &(source, arg) in &self.root { + let (at, bytes) = match arg { + RootArg::Constants { index, offset, words } => { + let Param::Constants { at, count } = *layout.params.get(index)? else { return None }; + if offset.checked_add(words)? > count { + return None; + } + (at.checked_add(offset.checked_mul(4)?)?, words.checked_mul(4)?) + } + RootArg::Descriptor { index } => { + let Param::Descriptor { at } = *layout.params.get(index)? else { return None }; + (at, 8) + } + }; + let end = at.checked_add(bytes)?; + if end > layout.size || (at < inline && end > inline) { + return None; + } + let dest = if at < inline { at + if gfx { 32 } else { 16 } } else { IO_BYTES + (at - inline) }; + for off in (0..bytes).step_by(4) { + result.push(Patch { source: source + off, dest: dest + off, shadow: (at + off) as usize }); + } + } + Some(result) + } +} + +#[derive(Debug, PartialEq, Eq)] +struct Patch { + source: u32, + dest: u32, + shadow: usize, +} + +struct Repacker { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +type SignatureKey = (usize, i32); +type RepackerKey = (usize, bool); +static REPACKERS: Mutex>>> = Mutex::new(None); +static PACKED_SIGNATURES: Mutex>> = Mutex::new(None); +static PENDING: Mutex>>> = Mutex::new(None); + +pub(super) fn allocator_reset(allocator: usize) { + let buffers = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + drop(buffers); +} + +unsafe fn repacker(dev: &ID3D12Device, upload: bool) -> Result, String> { + let mut g = REPACKERS.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let key = (dev.as_raw() as usize, upload); + if let Some(p) = map.get(&key) { + return Ok(p.clone()); + } + let src = include_str!("indirect_repack.hlsl"); + let extra: &[&str] = if upload { &["-DINPUT_UPLOAD=1"] } else { &[] }; + let dxil = recomp::dxc::compile(src, "main", "cs_6_0", extra)?; + let descriptor = |kind, reg| D3D12_ROOT_PARAMETER { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: reg, RegisterSpace: 0 } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let params = [ + if upload { descriptor(D3D12_ROOT_PARAMETER_TYPE_SRV, 0) } else { descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 0) }, + descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 1), + descriptor(D3D12_ROOT_PARAMETER_TYPE_UAV, 2), + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: CONFIG_WORDS } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }, + ]; + let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }; + let mut blob = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob, None).map_err(|e| format!("serialize the indirect repacker root signature: {e}"))?; + let blob = blob.ok_or("no indirect repacker root signature blob")?; + let root: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer().cast(), blob.GetBufferSize())) + .map_err(|e| format!("create the indirect repacker root signature: {e}"))?; + let pso = compute_pso(dev, &root, &dxil).map_err(|e| format!("create the indirect repacker PSO: {e}"))?; + let p = Arc::new(Repacker { root, pso }); + map.insert(key, p.clone()); + Ok(p) +} + +unsafe fn compute_pso(dev: &ID3D12Device, root: &ID3D12RootSignature, dxil: &[u8]) -> windows::core::Result { + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(root.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }; + let pso = dev.CreateComputePipelineState(&desc); + ManuallyDrop::drop(&mut desc.pRootSignature); + pso +} + +unsafe fn packed_signature(dev: &ID3D12Device, root: &ID3D12RootSignature, sig: &Signature) -> Result { + let mut g = PACKED_SIGNATURES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let key = (root.as_raw() as usize, sig.action.0); + if let Some(signature) = map.get(&key) { + return Ok(signature.clone()); + } + let params = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { UnorderedAccessView: D3D12_INDIRECT_ARGUMENT_DESC_0_4 { RootParameterIndex: 0 } }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { Type: sig.action, ..Default::default() }, + ]; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 8 + sig.action_bytes, NumArgumentDescs: 2, pArgumentDescs: params.as_ptr(), NodeMask: 0 }; + let mut out = None; + dev.CreateCommandSignature(&desc, root, &mut out).map_err(|e| format!("create the packed indirect signature: {e}"))?; + let out: ID3D12CommandSignature = out.ok_or("no packed indirect signature")?; + map.insert(key, out.clone()); + Ok(out) +} + +/// Read a title's GPU-produced buffer through its UMA window, or read a native upload +/// buffer as an SRV (already in GENERIC_READ). The console offset excludes placement delta. +unsafe fn source(resource: usize, offset: u64, bytes: u64) -> Option<(bool, u64, u32)> { + let end = offset.checked_add(bytes)?; + if offset % 4 != 0 { + return None; + } + if let Some((p, len)) = real::console_buffer(resource) { + if end > len as u64 { + return None; + } + let (window, at) = real::uma_window_buffer(p.checked_add(usize::try_from(offset).ok()?)?, usize::try_from(bytes).ok()?)?; + u32::try_from(at.checked_add(bytes - 1)?).ok()?; + let window = window as *mut c_void; + let window = ID3D12Resource::from_raw_borrowed(&window)?; + return Some((false, window.GetGPUVirtualAddress(), at as u32)); + } + let raw = resource as *mut c_void; + let r = ID3D12Resource::from_raw_borrowed(&raw)?; + let mut props = D3D12_HEAP_PROPERTIES::default(); + r.GetHeapProperties(Some(&mut props), None).ok()?; + let d = r.GetDesc(); + if d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER + || d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) + || !matches!(props.Type, D3D12_HEAP_TYPE_UPLOAD | D3D12_HEAP_TYPE_GPU_UPLOAD) + || end > d.Width + { + return None; + } + // Root SRV addresses must be 16-byte aligned. Rebase to keep byte offsets in 32 bits. + u32::try_from((offset & 15).checked_add(bytes - 1)?).ok()?; + Some((true, r.GetGPUVirtualAddress().checked_add(offset & !15)?, (offset & 15) as u32)) +} + +unsafe fn transition(list: &ID3D12GraphicsCommandList, resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: ManuallyDrop::new(Some(resource.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }) }, + ..Default::default() + }; + list.ResourceBarrier(std::slice::from_ref(&barrier)); + let mut t = ManuallyDrop::into_inner(barrier.Anonymous.Transition); + ManuallyDrop::drop(&mut t.pResource); +} + +pub(super) struct Recorded { + pub(super) signature: ID3D12CommandSignature, + pub(super) arguments: ID3D12Resource, + patches: Vec, +} + +impl Recorded { + pub(super) unsafe fn finish_gpu(&self, list: &ID3D12GraphicsCommandList) { + // A list can execute more than once. Leave the scratch resource in its creation state. + transition(list, &self.arguments, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + + pub(super) fn retain_and_clear(self, allocator: usize, shadow: &mut [u8]) { + PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().push(self.arguments); + for p in self.patches { + shadow[p.shadow..p.shadow + 4].fill(0); + } + } +} + +pub(super) struct Repack<'a> { + pub(super) signature: &'a Signature, + pub(super) resource: usize, + pub(super) offset: u64, + pub(super) max: u32, + pub(super) gfx: bool, +} + +impl Repack<'_> { + pub(super) unsafe fn record( + &self, list: &ID3D12GraphicsCommandList, root: &ID3D12RootSignature, layout: &Layout, + inline: usize, args: &[u8], io: &[u32], alloc: impl FnOnce(usize) -> Option, + ) -> Result { + let sig = self.signature; + if self.gfx == (sig.action == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH) { + return Err("indirect action does not match the translated pipeline".into()); + } + let groups = self.max.div_ceil(THREADS); + if groups == 0 || groups > D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION { + return Err("indirect command count is outside the repacker's dispatch range".into()); + } + let patches = sig.patches(layout, inline as u32, self.gfx).ok_or("indirect root arguments do not match the bound layout")?; + let (upload, input, input_offset) = source(self.resource, self.offset, u64::from(self.max) * u64::from(sig.stride)) + .ok_or("indirect arguments are outside a GPU-readable UMA or upload buffer")?; + let spill = &args[inline..]; + let template_bytes = IO_BYTES + spill.len() as u32; + let scratch_stride = (template_bytes + 15) & !15; + let template_at = scratch_stride.checked_mul(self.max).ok_or("indirect root data is too large")?; + let patch_at = template_at.checked_add(template_bytes).ok_or("indirect root data is too large")?; + let size = patch_at.checked_add(8 * patches.len() as u32).ok_or("indirect root data is too large")?; + let scratch = alloc(size as usize).ok_or("unified memory is full")?; + let scratch_va = real::uma_va_of(scratch).ok_or("indirect scratch is outside GPU-visible UMA")?; + let raw = scratch as *mut u8; + std::ptr::copy_nonoverlapping(io.as_ptr().cast(), raw.add(template_at as usize), IO_BYTES as usize); + std::ptr::copy_nonoverlapping(spill.as_ptr(), raw.add(template_at as usize + IO_BYTES as usize), spill.len()); + for (i, patch) in patches.iter().enumerate() { + raw.add(patch_at as usize + 8 * i).cast::<[u32; 2]>().write([patch.source, patch.dest]); + } + let mut dev = None; + list.GetDevice(&mut dev).map_err(|e| format!("get the indirect list device: {e}"))?; + let dev = dev.ok_or("no indirect list device")?; + let repack = repacker(&dev, upload)?; + let signature = packed_signature(&dev, root, sig)?; + let mut arguments = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: u64::from(self.max) * u64::from(8 + sig.action_bytes), + 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() + }, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut arguments, + ).map_err(|e| format!("allocate packed indirect arguments: {e}"))?; + let arguments: ID3D12Resource = arguments.ok_or("no packed indirect argument buffer")?; + let config: [u32; CONFIG_WORDS as usize] = [ + self.max, input_offset, sig.stride, sig.action_offset, sig.action_bytes, scratch_stride, + template_bytes, patches.len() as u32, scratch as u32, (scratch >> 32) as u32, + scratch_va as u32, (scratch_va >> 32) as u32, IO_BYTES, + ]; + repack.dispatch(list, upload, input, scratch_va, &arguments, &config, groups); + Ok(Recorded { signature, arguments, patches }) + } +} + +impl Repacker { + unsafe fn dispatch( + &self, list: &ID3D12GraphicsCommandList, upload: bool, input: u64, scratch_va: u64, + arguments: &ID3D12Resource, config: &[u32; CONFIG_WORDS as usize], groups: u32, + ) { + let uav = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() }; + list.ResourceBarrier(&[uav.clone()]); + list.SetPipelineState(&self.pso); + list.SetComputeRootSignature(&self.root); + if upload { + list.SetComputeRootShaderResourceView(0, input); + } else { + list.SetComputeRootUnorderedAccessView(0, input); + } + list.SetComputeRootUnorderedAccessView(1, scratch_va); + list.SetComputeRootUnorderedAccessView(2, arguments.GetGPUVirtualAddress()); + list.SetComputeRoot32BitConstants(3, config.len() as u32, config.as_ptr().cast(), 0); + list.Dispatch(groups, 1, 1); + list.ResourceBarrier(&[uav]); + transition(list, arguments, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn root_offsets_follow_inline_registers_and_the_spilled_table() { + let key = 0x217_1A00; + let desc = [[5, 0, 1, 2], [8, 1, 0, 0], [1, 0, 0, 0]]; + register(key, 40, &desc); + let sig = lookup(key).unwrap().unwrap(); + assert_eq!((sig.stride, sig.action_offset, sig.action_bytes), (40, 16, 20)); + let layout = Layout { params: vec![Param::Constants { at: 0, count: 3 }, Param::Descriptor { at: 12 }], size: 20, inline: 12, inline_gfx: 12 }; + let patches = sig.patches(&layout, 12, true).unwrap(); + assert_eq!( + patches.iter().map(|p| (p.source, p.dest, p.shadow)).collect::>(), + vec![(0, 36, 4), (4, 40, 8), (8, IO_BYTES, 12), (12, IO_BYTES + 4, 16)], + ); + assert_eq!(sig.patches(&layout, 12, false).unwrap()[0].dest, 20); + assert!(sig.patches(&layout, 8, true).is_none()); + assert!(Signature::parse(32, &desc).is_none()); + assert!(Signature::parse(40, &[[5, 0, 0, 1], [3, 0, 0, 0], [1, 0, 0, 0]]).is_none()); + forget(key); + assert!(lookup(key).is_none()); + } + + #[test] + fn gpu_repack_preserves_per_dispatch_values_and_the_count_buffer() { + use windows::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + if recomp::dxc::create_instance().is_none() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let buffer = |bytes, heap, state, flags| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, 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: flags, ..Default::default() + }; + let mut out = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out).unwrap(); + out.unwrap() + }; + let gpu_buffer = |size, state| buffer(size, D3D12_HEAP_TYPE_DEFAULT, state, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let (count, stride, record_bytes, max) = (2u32, 20u32, 20u32, 3u32); + let template_at = max * IO_BYTES; + let scratch_bytes = template_at + IO_BYTES + 16; + let src = gpu_buffer(u64::from(max * stride), D3D12_RESOURCE_STATE_COPY_DEST); + let scratch = gpu_buffer(u64::from(scratch_bytes), D3D12_RESOURCE_STATE_COPY_DEST); + let packed = gpu_buffer(u64::from(max * record_bytes), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + let results = gpu_buffer(16, D3D12_RESOURCE_STATE_COPY_DEST); + let readback = buffer(16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE); + let upload = buffer(u64::from(scratch_bytes) + 128, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_RESOURCE_FLAG_NONE); + let mut data = vec![0u32; (scratch_bytes as usize + 128) / 4]; + data[..15].copy_from_slice(&[0, 4, 1, 1, 1, 1, 9, 1, 1, 1, 2, 50, 1, 1, 1]); + data[16] = count; + let t = (128 + template_at as usize) / 4; + data[t + 4] = 7; + data[t + KERNEL_SGPRS..t + KERNEL_SGPRS + 4].copy_from_slice(&[0, 20, 4, 24]); + + list.CopyBufferRegion(&src, 0, &upload, 0, u64::from(max * stride)); + list.CopyBufferRegion(&scratch, 0, &upload, 128, u64::from(scratch_bytes)); + list.CopyBufferRegion(&results, 0, &upload, 80, 16); + for resource in [&src, &scratch, &results] { + transition(&list, resource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + + let prep = repacker(&dev, false).unwrap(); + let sig = Signature::parse(stride, &[[5, 0, 1, 2], [2, 0, 0, 0]]).unwrap(); + let native_sig = packed_signature(&dev, &prep.root, &sig).unwrap(); + let work = recomp::dxc::compile( + "RWByteAddressBuffer io : register(u0); RWByteAddressBuffer result : register(u1); + [numthreads(1,1,1)] void main() { result.Store(io.Load(20) * 4, io.Load(24) + io.Load(16)); }", + "main", "cs_6_0", &[], + ).unwrap(); + let work = compute_pso(&dev, &prep.root, &work).unwrap(); + let va = scratch.GetGPUVirtualAddress(); + let config = [max, 0, stride, 8, 12, IO_BYTES, IO_BYTES, 2, 0, 0, va as u32, (va >> 32) as u32, IO_BYTES]; + prep.dispatch(&list, false, src.GetGPUVirtualAddress(), va, &packed, &config, 1); + list.SetPipelineState(&work); + list.SetComputeRootSignature(&prep.root); + list.SetComputeRootUnorderedAccessView(1, results.GetGPUVirtualAddress()); + list.ExecuteIndirect(&native_sig, max, &packed, 0, &upload, 64); + transition(&list, &results, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&readback, 0, &results, 0, 16); + list.Close().unwrap(); + // Contents written after recording. The repacker can only see them at GPU execution. + let mut mapped: *mut c_void = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut mapped)).unwrap(); + std::ptr::copy_nonoverlapping(data.as_ptr(), mapped.cast(), data.len()); + upload.Unmap(0, None); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, event).unwrap(); + let waited = WaitForSingleObject(event, 10_000); + CloseHandle(event).unwrap(); + assert_eq!(waited, WAIT_OBJECT_0); + readback.Map(0, None, Some(&mut mapped)).unwrap(); + let actual = mapped.cast::<[u32; 4]>().read(); + readback.Unmap(0, None); + assert_eq!(actual, [11, 16, 0, 0]); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl b/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl new file mode 100644 index 000000000..4612354d3 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indirect_repack.hlsl @@ -0,0 +1,41 @@ +#ifdef INPUT_UPLOAD +ByteAddressBuffer source : register(t0); +#else +RWByteAddressBuffer source : register(u0); +#endif +RWByteAddressBuffer data : register(u1); +RWByteAddressBuffer packed : register(u2); + +cbuffer Config : register(b0) { + uint count, input_offset, input_stride, action_offset; + uint action_bytes, scratch_stride, template_bytes, patch_count; + uint scratch_lo, scratch_hi, va_lo, va_hi; + uint io_bytes; +}; + +uint2 offset_address(uint lo, uint hi, uint offset) { + uint sum = lo + offset; + return uint2(sum, hi + uint(sum < lo)); +} + +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= count) + return; + uint src = input_offset + id.x * input_stride; + uint dst = id.x * scratch_stride; + uint template_offset = count * scratch_stride; + uint patch_offset = template_offset + template_bytes; + for (uint i = 8; i < template_bytes; i += 4) + data.Store(dst + i, data.Load(template_offset + i)); + data.Store2(dst, offset_address(scratch_lo, scratch_hi, dst + io_bytes)); + for (uint j = 0; j < patch_count; ++j) { + uint2 patch = data.Load2(patch_offset + j * 8); + data.Store(dst + patch.y, source.Load(src + patch.x)); + } + + uint record = id.x * (8 + action_bytes); + packed.Store2(record, offset_address(va_lo, va_hi, dst)); + for (uint k = 0; k < action_bytes; k += 4) + packed.Store(record + 8 + k, source.Load(src + action_offset + k)); +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 92f7bc928..7c26b2149 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -18,6 +18,7 @@ mod cpu_writes; mod fence_x; pub mod frame; pub mod guard; +mod indirect; mod late_release; pub mod layout; pub mod list_x; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9168a5d66..eee35778a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2436,6 +2436,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("WriteToSubresource", res_write_to_subresource as usize), ]), Kind::PipelineState => v.push(("Release", pso_release as usize)), + Kind::CommandSignature => v.push(("Release", signature_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), Kind::Heap => v.push(("Release", mem_heap_release as usize)), Kind::Fence => v.push(("Signal", fence_signal as usize)), @@ -4862,6 +4863,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let n = f(this); if n == 0 { super::list_x::on_allocator_release(this as usize); + super::indirect::allocator_reset(this as usize); } n } @@ -4873,10 +4875,20 @@ unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { if hr >= 0 { // the GPU is done with what lists recorded from this allocator used super::console_list::allocator_reset(this); + super::indirect::allocator_reset(this as usize); } hr } +unsafe extern "system" fn signature_release(this: *mut c_void) -> u32 { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let n = f(this); + if n == 0 { + super::indirect::forget(this as usize); + } + n +} + // --------------------------------------------------------------------------------------- // command queue layouts // ---------------------------------------------------------------------------------------