From e02b8850ad7f390e72be6bc7b7e4bbc4a8fb9759 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:24:05 -0800 Subject: [PATCH] D3D12.X: build indirect split pipelines on the CBV ABI Root-constant ExecuteIndirect costs about 15.3 us per piece step on the measured RTX 5070 Ti, versus 0.41 us for a Dispatch-only signature. Build a bounded, speculative indirect-only piece and whole set on one background lane, then share one 256-byte CBV command per round across its pieces. Direct dispatch keeps its existing constants ABI. Until the direct whole and complete indirect set are ready, ExecuteIndirect keeps the existing whole fallback. Source-plan retention and live duplicate admission are each capped at 64 MiB. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 72 +++--- crates/xcl/src/hle/d3d12x/bind.rs | 21 +- crates/xcl/src/hle/d3d12x/real.rs | 18 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 221 +++++++++++++++--- 4 files changed, 249 insertions(+), 83 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 0c56284a39..515e29d5df 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1472,20 +1472,10 @@ pub(crate) unsafe fn record_dispatch_chain<'a>( } } -/// Bytes of one indirect chain command: eight slab constants followed by Dispatch arguments. -pub(crate) const CHAIN_COMMAND_BYTES: u32 = 44; - -pub(crate) fn chain_command_signature(dev: &ID3D12Device, rs: &ID3D12RootSignature) -> Result { - let args = [ - D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { - Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { RootParameterIndex: 7, DestOffsetIn32BitValues: 0, Num32BitValuesToSet: 8 } } }, - D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }, - ]; - let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: CHAIN_COMMAND_BYTES, NumArgumentDescs: 2, pArgumentDescs: args.as_ptr(), NodeMask: 0 }; - let mut sig = None; - unsafe { dev.CreateCommandSignature(&desc, rs, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; - sig.ok_or_else(|| "CreateCommandSignature".into()) -} +/// One round's root-CBV constants, padded to D3D12's 256-byte CBV alignment. Its Dispatch +/// arguments begin after the eight words and are shared by every piece in that round. +pub(crate) const CHAIN_COMMAND_BYTES: u32 = 256; +pub(crate) const CHAIN_DISPATCH_AT: u64 = 32; pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result { static MADE: Mutex> = Mutex::new(None); @@ -1503,17 +1493,15 @@ pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result u64 { - (u64::from(rounds) * u64::from(pieces) * u64::from(CHAIN_COMMAND_BYTES)).next_multiple_of(8) +pub(crate) fn chain_tail_offset(rounds: u32) -> u64 { + u64::from(rounds) * u64::from(CHAIN_COMMAND_BYTES) } fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { @@ -1560,9 +1548,9 @@ fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12Pip } } -pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, pieces: u32) -> Option { +pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32) -> Option { let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_tail_offset(rounds, pieces) + 12, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_tail_offset(rounds) + 12, 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() }; @@ -1573,15 +1561,15 @@ pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, piec } pub(crate) unsafe fn record_indirect_slicer( - list: &ID3D12GraphicsCommandList, args: u64, rounds: u32, most: u64, pieces: u32, out: &ID3D12Resource, + list: &ID3D12GraphicsCommandList, args: u64, rounds: u32, most: u64, out: &ID3D12Resource, ) -> Result<(), String> { let mut dev = None; list.GetDevice(&mut dev).map_err(|e| e.to_string())?; let (rs, pso) = indirect_slicer(&dev.ok_or("device")?)?; - let constants = [rounds, most.min(u64::from(u32::MAX)) as u32, pieces]; + let constants = [rounds, most.min(u64::from(u32::MAX)) as u32]; list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); - list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0); list.SetComputeRootShaderResourceView(1, args); list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -1590,7 +1578,8 @@ pub(crate) unsafe fn record_indirect_slicer( 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 }) } }]); + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER }) } }]); Ok(()) } @@ -1598,15 +1587,15 @@ pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( list: &ID3D12GraphicsCommandList, sig: &ID3D12CommandSignature, commands: &ID3D12Resource, rounds: u32, scratch: &ID3D12Resource, pieces: impl IntoIterator + Clone, ) { - let n = pieces.clone().into_iter().count() as u32; list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); for r in 0..rounds { - for (i, piece) in pieces.clone().into_iter().enumerate() { + let offset = u64::from(r) * u64::from(CHAIN_COMMAND_BYTES); + list.SetComputeRootConstantBufferView(7, commands.GetGPUVirtualAddress() + offset); + for piece in pieces.clone() { 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.SetPipelineState(piece); - let offset = (u64::from(r) * u64::from(n) + i as u64) * u64::from(CHAIN_COMMAND_BYTES); - list.ExecuteIndirect(sig, 1, commands, offset, None::<&ID3D12Resource>, 0); + list.ExecuteIndirect(sig, 1, commands, offset + CHAIN_DISPATCH_AT, None::<&ID3D12Resource>, 0); } } } @@ -1690,7 +1679,7 @@ fn abi_signature( #[cfg(test)] mod slab_tests { - use super::{chain_slab_parameter, chain_tail_offset, dispatch_slabs, ChainSlabBinding, CHAIN_COMMAND_BYTES}; + use super::{chain_slab_parameter, chain_tail_offset, dispatch_slabs, ChainSlabBinding, CHAIN_COMMAND_BYTES, CHAIN_DISPATCH_AT}; use windows::Win32::Graphics::Direct3D12::{ D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, D3D12_ROOT_PARAMETER_TYPE_CBV, @@ -1714,12 +1703,11 @@ mod slab_tests { #[test] fn indirect_whole_arguments_follow_aligned_piece_commands() { - for (rounds, pieces) in [(1, 2), (16, 9), (1024, 64)] { - let commands = u64::from(rounds * pieces * CHAIN_COMMAND_BYTES); - let tail = chain_tail_offset(rounds, pieces); - assert!(tail >= commands); - assert_eq!(tail % 8, 0); - assert!(tail - commands < 8); + for rounds in [1, 16, 1024] { + let tail = chain_tail_offset(rounds); + assert_eq!(tail, u64::from(rounds * CHAIN_COMMAND_BYTES)); + assert_eq!(tail % 256, 0); + assert_eq!(CHAIN_DISPATCH_AT, 32); } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index f2c79a967e..80569779f8 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -393,7 +393,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if compute && max == 1 && count_buf == 0 && DISPATCH_ONLY.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&sig)) { let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { super::real::dispatch_chain::execute_indirect(list, pso, with(this, |s| s.allocator), address, - || bind_abi(this, list, pso, false)) + |root| bind_abi_with_root(this, list, pso, false, root)) }); match chained { Ok(true) => { @@ -1181,6 +1181,12 @@ 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_with_root(this, list, pso, gfx, 0) +} + +unsafe fn bind_abi_with_root( + this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, root: usize, +) -> Result<(), String> { super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); @@ -1213,7 +1219,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - 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 = (root != 0).then_some(root) + .or_else(|| 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 views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().filter(|&v| v != 0).unwrap_or(first))); @@ -1228,9 +1237,11 @@ 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); + if root == 0 { + let real = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; + list.SetPipelineState(pc); + } Ok(()) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bd22d432ea..57dad5dfa3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4955,7 +4955,8 @@ enum ComputeBuild { // through to building the pieces, whose cold build is cheaper. CachedWhole, // The chain root signature has a separate on-disk namespace. - Chain, + DirectChain, + IndirectChain, } unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, @@ -4970,7 +4971,13 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let key = compute_blob_key_for(dxil, rs as usize, copy.Flags.0, copy.NodeMask); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path_for_root_node(dxil, copy.Flags.0, mode == ComputeBuild::Chain, samplers, copy.NodeMask); + let disk = match mode { + ComputeBuild::DirectChain => driver_cache::path_for_chain_root_node( + dxil, copy.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, copy.NodeMask), + ComputeBuild::IndirectChain => driver_cache::path_for_chain_root_node( + dxil, copy.Flags.0, driver_cache::ChainRoot::IndirectCbv, samplers, copy.NodeMask), + _ => driver_cache::path_for_root_node(dxil, copy.Flags.0, false, samplers, copy.NodeMask), + }; let from_disk = cached.is_none(); let mut loaded = None; if from_disk { @@ -5187,6 +5194,13 @@ pub(crate) mod driver_cache { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for_root_node(dxil, flags, chained, samplers, node_mask))) } + pub fn path_for_chain_root_node( + dxil: &[u8], flags: i32, root: ChainRoot, samplers: &[StaticSampler], node_mask: u32, + ) -> Option { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver") + .join(name_for_chain_root_node(dxil, flags, root, samplers, node_mask))) + } + pub fn graphics_path(hash: u64, bytes: usize) -> Option { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index c146cfa335..9986c135c2 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -2,7 +2,7 @@ //! to the caller. Other pieces and the lazily built whole form belong to it. use super::*; use crate::gpu::{dxil::kernel::DispatchChain, recomp::pso}; -use std::sync::{Arc, LazyLock, OnceLock}; +use std::sync::{Arc, LazyLock, OnceLock, Weak}; static PROGRAMS: AtomicU64 = AtomicU64::new(0); static PIECES: AtomicU64 = AtomicU64::new(0); @@ -37,6 +37,7 @@ struct PipelineBuilder { flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, + mode: ComputeBuild, } impl PipelineBuilder { @@ -44,7 +45,7 @@ impl PipelineBuilder { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), - dxil, &self.samplers, self.record, iid, &mut raw, ComputeBuild::Chain); + dxil, &self.samplers, self.record, iid, &mut raw, self.mode); if hr >= 0 && !raw.is_null() { Ok(ID3D12PipelineState::from_raw(raw)) } else { Err(hr) } } } @@ -98,7 +99,34 @@ struct Chain { words: u32, whole_code: Vec, whole: WholeBuild, - indirect_signature: OnceLock, + plan: Weak, + indirect: IndirectBuild, +} + +struct IndirectChain { + signature: ID3D12RootSignature, + whole: ID3D12PipelineState, + pieces: Vec, + _charge: IndirectCharge, +} + +struct IndirectCharge(usize); + +impl Drop for IndirectCharge { + fn drop(&mut self) { + INDIRECT_VARIANT_SOURCE.fetch_sub(self.0, Ordering::AcqRel); + } +} + +struct IndirectBuild { + requested: AtomicBool, + result: OnceLock, HRESULT>>, +} + +impl IndirectBuild { + fn new() -> Self { + Self { requested: AtomicBool::new(false), result: OnceLock::new() } + } } impl Chain { @@ -111,18 +139,106 @@ impl Chain { static CHAINS: LazyLock>>> = LazyLock::new(Default::default); /// Shared for the process lifetime so chains with a common piece also share its driver blob. -static SIGNATURES: LazyLock), ID3D12RootSignature>>> = LazyLock::new(Default::default); +static SIGNATURES: LazyLock), ID3D12RootSignature>>> = LazyLock::new(Default::default); fn sampler_key(samplers: &[pso::StaticSampler]) -> Vec { samplers.iter().flat_map(|(words, comparison)| words.iter().copied().chain([*comparison as u32])).collect() } -unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler]) -> Option { - let key = (dev.as_raw() as usize, sampler_key(samplers)); +const INDIRECT_PLAN_BYTES: usize = 64 << 20; +const INDIRECT_VARIANT_BYTES: usize = 64 << 20; +static INDIRECT_VARIANT_SOURCE: AtomicUsize = AtomicUsize::new(0); + +fn reserve_indirect_source(used: &AtomicUsize, bytes: usize, limit: usize) -> bool { + used.fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { + current.checked_add(bytes).filter(|&next| next <= limit) + }).is_ok() +} + +#[derive(Default)] +struct PlanCache { + bytes: usize, + plans: std::collections::VecDeque<(usize, Arc)>, +} + +impl PlanCache { + fn insert(&mut self, plan: Arc, limit: usize) { + let key = Arc::as_ptr(&plan) as usize; + if let Some(at) = self.plans.iter().position(|p| p.0 == key) { + self.plans.remove(at); + } else { + self.bytes = self.bytes.saturating_add(plan.pieces.iter().map(Vec::capacity).sum::()); + } + self.plans.push_back((key, plan)); + while self.bytes > limit { + let Some((_, old)) = self.plans.pop_front() else { break }; + self.bytes = self.bytes.saturating_sub(old.pieces.iter().map(Vec::capacity).sum::()); + } + } +} + +fn retain_indirect_plan(plan: Arc) { + static PLANS: LazyLock> = LazyLock::new(Default::default); + PLANS.lock().unwrap().insert(plan, INDIRECT_PLAN_BYTES); +} + +fn build_indirect(chain: &Arc) -> Result, HRESULT> { + let plan = chain.plan.upgrade().ok_or(E_INVALIDARG)?; + let source_bytes = plan.pieces.iter().map(Vec::len).sum::().saturating_add(chain.whole_code.len()); + if !reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, source_bytes, INDIRECT_VARIANT_BYTES) { + return Err(E_OUTOFMEMORY); + } + let charge = IndirectCharge(source_bytes); + let signature = unsafe { signature_for(&chain.builder.device, &chain.builder.samplers, true) }.ok_or(E_INVALIDARG)?; + let builder = Arc::new(PipelineBuilder { + device: chain.builder.device.clone(), + create: chain.builder.create, + signature: signature.clone(), + samplers: chain.builder.samplers.clone(), + flags: chain.builder.flags, + node: chain.builder.node, + record: chain.builder.record, + mode: ComputeBuild::IndirectChain, + }); + // These variants are speculative: the ready direct whole form remains correct. Keep their + // cold driver compiles on this one low-impact lane instead of fanning out across PSO workers. + let mut pieces = Vec::with_capacity(plan.pieces.len()); + for code in &plan.pieces { + pieces.push(unsafe { builder.pipeline(code, &pc_iid(Kind::PipelineState))? }); + } + let whole = unsafe { builder.pipeline(&chain.whole_code, &pc_iid(Kind::PipelineState))? }; + Ok(Arc::new(IndirectChain { signature, whole, pieces, _charge: charge })) +} + +fn request_indirect(chain: &Arc) { + if chain.indirect.requested.swap(true, Ordering::AcqRel) { + return; + } + static BUILDS: LazyLock>>> = LazyLock::new(|| { + let (tx, rx) = std::sync::mpsc::channel::>(); + std::thread::Builder::new().name("xcl-pso-chain-indirect".into()).stack_size(64 << 20).spawn(move || { + while let Ok(weak) = rx.recv() { + let Some(chain) = weak.upgrade() else { continue }; + let result = build_indirect(&chain); + let _ = chain.indirect.result.set(result); + } + }).ok().map(|_| tx) + }); + if BUILDS.as_ref().is_none_or(|queue| queue.send(Arc::downgrade(chain)).is_err()) { + chain.indirect.requested.store(false, Ordering::Release); + } +} + +unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler], indirect: bool) -> Option { + let key = (dev.as_raw() as usize, indirect, sampler_key(samplers)); if let Some(signature) = SIGNATURES.lock().unwrap().get(&key).cloned() { return Some(signature); } - let created = match pso::dispatch_chain_root_signature(dev, samplers) { + let created = match if indirect { + pso::dispatch_chain_indirect_root_signature(dev, samplers) + } else { + pso::dispatch_chain_root_signature(dev, samplers) + } { Ok(signature) => signature, Err(e) => { note_translation_error(format!("dispatch-chain root signature: {e}")); @@ -137,10 +253,10 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT plan: Arc) -> Option { if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } let dev = ID3D12Device::from_raw_borrowed(&this)?; - let signature = signature_for(dev, samplers)?; + let signature = signature_for(dev, samplers, false)?; let rs = signature.as_raw() as usize; let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, samplers: samplers.to_vec(), - flags: desc.Flags, node: desc.NodeMask, record }); + flags: desc.Flags, node: desc.NodeMask, record, mode: ComputeBuild::DirectChain }); let jobs = (0..plan.pieces.len()).map(|i| { let plan = plan.clone(); let builder = builder.clone(); @@ -153,7 +269,8 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let mut pieces = built.into_iter().collect::>>()?.into_iter(); let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: WholeBuild::new(), indirect_signature: OnceLock::new() }); + whole_code: whole.to_vec(), whole: WholeBuild::new(), plan: Arc::downgrade(&plan), indirect: IndirectBuild::new() }); + retain_indirect_plan(plan.clone()); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -184,6 +301,8 @@ impl Drop for Scratch { struct Recording { scratch: Arc, + /// Keep the title-visible direct first piece alive while this recording may still execute. + /// Indirect execution uses its separate CBV-compatible duplicates. first: ID3D12PipelineState, chain: Arc, _indirect_commands: Option, @@ -335,13 +454,21 @@ fn indirect_rounds() -> u32 { /// slicer writes either bounded piece commands or the whole-form command, never a partial chain. pub(in crate::hle::d3d12x) unsafe fn execute_indirect( list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, args: u64, - bind: impl FnOnce() -> Result<(), String>, + bind: impl FnOnce(usize) -> Result<(), String>, ) -> Result { let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(false) }; - let whole = match chain.whole.ready() { + match chain.whole.ready() { None => return Ok(false), - Some(Ok(pso)) => pso, + Some(Ok(_)) => {} Some(Err(hr)) => return Err(format!("whole compute pipeline ({hr:#x})")), + } + let indirect = match chain.indirect.result.get() { + Some(Ok(indirect)) => indirect.clone(), + Some(Err(_)) => return Ok(false), + None => { + request_indirect(&chain); + return Ok(false); + } }; let allocator = if super::super::alloc_pool::enabled() { super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) @@ -351,27 +478,19 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( let Some((scratch, _)) = scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, scratch_budget(), group) else { return Ok(false); }; - let signature = match chain.indirect_signature.get() { - Some(sig) => sig.clone(), - None => { - let sig = pso::chain_command_signature(&chain.builder.device, &chain.builder.signature)?; - chain.indirect_signature.get_or_init(|| sig).clone() - } - }; - let whole_signature = pso::dispatch_command_signature(&chain.builder.device)?; + let signature = pso::dispatch_command_signature(&chain.builder.device)?; let rounds = indirect_rounds(); - let pieces = chain.tail.len() as u32 + 1; - let commands = pso::chain_commands_buffer(&chain.builder.device, rounds, pieces) + let commands = pso::chain_commands_buffer(&chain.builder.device, rounds) .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(list, args, rounds, (scratch.bytes / group).max(1), pieces, &commands)?; - let bound = bind(); + pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), &commands)?; + let bound = bind(indirect.signature.as_raw() as usize); if bound.is_ok() { - list.SetPipelineState(&whole); - list.ExecuteIndirect(&whole_signature, 1, &commands, - pso::chain_tail_offset(rounds, pieces), None::<&ID3D12Resource>, 0); + list.SetPipelineState(&indirect.whole); + list.ExecuteIndirect(&signature, 1, &commands, + pso::chain_tail_offset(rounds), None::<&ID3D12Resource>, 0); pso::record_dispatch_chain_indirect(list, &signature, &commands, rounds, &scratch.buffer, - std::iter::once(&first).chain(&chain.tail)); + indirect.pieces.iter()); } RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { scratch, first, chain, _indirect_commands: Some(commands), @@ -386,6 +505,33 @@ mod tests { const MB: u64 = 1 << 20; + #[test] + fn retained_indirect_plans_are_deduplicated_and_bounded() { + let plan = |byte: u8| Arc::new(DispatchChain { + pieces: vec![vec![byte; 40], vec![byte; 40]], + dwords_per_group: 4, + }); + let (first, second) = (plan(1), plan(2)); + let first_weak = Arc::downgrade(&first); + let mut cache = PlanCache::default(); + cache.insert(first.clone(), 100); + cache.insert(first, 100); + assert_eq!((cache.plans.len(), cache.bytes), (1, 80)); + cache.insert(second, 100); + assert_eq!((cache.plans.len(), cache.bytes), (1, 80)); + assert!(first_weak.upgrade().is_none(), "the oldest plan was released at the cap"); + } + + #[test] + fn indirect_variant_source_admission_never_exceeds_its_cap() { + let used = AtomicUsize::new(0); + assert!(reserve_indirect_source(&used, 60, 100)); + assert!(!reserve_indirect_source(&used, 41, 100)); + assert_eq!(used.load(Ordering::Relaxed), 60); + assert!(reserve_indirect_source(&used, 40, 100)); + assert_eq!(used.load(Ordering::Relaxed), 100); + } + #[test] fn signature_identity_includes_sampler_words_order_and_comparison() { let a = ([1, 2, 3, 4], false); @@ -508,18 +654,25 @@ mod tests { let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); let whole = WholeBuild::new(); whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap(); - let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs, samplers: Vec::new(), - flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); + 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; + let plan = Arc::new(DispatchChain { pieces: vec![dxil.clone(), dxil.clone()], dwords_per_group: 4 }); + assert!(reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, 1, INDIRECT_VARIANT_BYTES)); + let indirect = Arc::new(IndirectChain { signature: rs.clone(), whole: first.clone(), + pieces: vec![first.clone(), first.clone()], _charge: IndirectCharge(1) }); + let indirect_build = IndirectBuild::new(); + indirect_build.requested.store(true, Ordering::Relaxed); + indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!()); CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, - whole_code: Vec::new(), whole, indirect_signature: OnceLock::new() })); + whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); 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, 1).unwrap(); - assert_eq!(execute_indirect(&list, key, allocator, args.GetGPUVirtualAddress(), || Err("bind failed".into())), Err("bind failed".into())); + let args = pso::chain_commands_buffer(&dev, 1).unwrap(); + assert_eq!(execute_indirect(&list, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into())), Err("bind failed".into())); assert!(RECORDINGS.lock().unwrap().get(&allocator).is_some_and(|r| r.iter().any(|r| r._indirect_commands.is_some()))); list.Close().unwrap(); allocator_reset(allocator);