diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index cd7b234bf8..1ef9ef0d7d 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1696,10 +1696,39 @@ pub(crate) unsafe fn record_dispatch_chain<'a>( } } -/// 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. +/// One round of an indirect chain (written by `INDIRECT_SLICER`): the eight words a direct +/// dispatch sets as its root constants, then its Dispatch arguments, shared by every piece in +/// that round (`chain_command_signature`). pub(crate) const CHAIN_COMMAND_BYTES: u32 = 256; pub(crate) const CHAIN_DISPATCH_AT: u64 = 32; +// (`chain_command_signature` reads the Dispatch arguments right after its eight root constants) +const _: () = assert!(CHAIN_DISPATCH_AT == 8 * 4); + +/// The command signature of a chain piece's indirect dispatch under the chain root signature +/// `rs` (`dispatch_chain_root_signature`): a round's eight words go to the root constants a +/// direct dispatch sets (parameter 7, `record_dispatch_chain`), then its Dispatch arguments. So +/// direct and indirect dispatches run the same pieces, built once under one root signature. +pub(crate) fn chain_command_signature(dev: &ID3D12Device, rs: &ID3D12RootSignature) -> Result { + // (by root signature, kept alive here so its address names no other) + static MADE: Mutex> = Mutex::new(Vec::new()); + let mut made = MADE.lock().unwrap(); + if let Some((_, sig)) = made.iter().find(|m| windows::core::Interface::as_raw(&m.0) == windows::core::Interface::as_raw(rs)) { + return Ok(sig.clone()); + } + 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 (chain): {e}"))?; + let sig: ID3D12CommandSignature = sig.ok_or("CreateCommandSignature (chain)")?; + made.push((rs.clone(), sig.clone())); + Ok(sig) +} pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result { static MADE: Mutex> = Mutex::new(None); @@ -1823,6 +1852,8 @@ pub(crate) unsafe fn restore_indirect_commands(list: &ID3D12GraphicsCommandList, StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS }) } }]); } +/// The pieces of a chain for the `rounds` the slicer wrote into `commands`, under the chain root +/// signature: `sig` is its `chain_command_signature`. pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( list: &ID3D12GraphicsCommandList, sig: &ID3D12CommandSignature, commands: &ID3D12Resource, rounds: u32, scratch: &ID3D12Resource, pieces: impl IntoIterator + Clone, @@ -1831,12 +1862,11 @@ pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); for r in 0..rounds { 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) }) } }]); bind_pipeline(piece); - list.ExecuteIndirect(sig, 1, commands, offset + CHAIN_DISPATCH_AT, None::<&ID3D12Resource>, 0); + list.ExecuteIndirect(sig, 1, commands, offset, None::<&ID3D12Resource>, 0); } } } diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index bdebc51704..e71ac1975a 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1710,10 +1710,28 @@ pub(crate) fn dispatch_split_by( dispatch_split_samples(chain, groups, &[], mem, most, 1, false).map(|(m, _)| m) } +/// `dispatch_split_by` as an indirect dispatch (`dispatch_chain::execute_indirect`): the groups +/// in an argument buffer, the slicer's rounds (one for each slab) run by the same pieces. +#[cfg(test)] +pub(crate) fn dispatch_split_indirect_by( + chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], mem: &[u32], most: u64, +) -> Result, String> { + dispatch_split_forms(chain, groups, &[], mem, most, 1, false, true).map(|(m, _)| m) +} + #[cfg(test)] pub(crate) fn dispatch_split_samples( chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], sgprs: &[u32], mem: &[u32], most: u64, reps: usize, timed: bool, +) -> Result<(Vec, Vec), String> { + dispatch_split_forms(chain, groups, sgprs, mem, most, reps, timed, false) +} + +#[cfg(test)] +#[allow(clippy::too_many_arguments)] +fn dispatch_split_forms( + chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], sgprs: &[u32], mem: &[u32], + most: u64, reps: usize, timed: bool, indirect: bool, ) -> Result<(Vec, Vec), String> { let mut g = GPU.lock().unwrap(); let gpu = g.get_or_insert_with(init).as_mut().map_err(|e| e.clone())?; @@ -1726,7 +1744,7 @@ pub(crate) fn dispatch_split_samples( }).map_err(e) }).collect::>()?; dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pieces[0], &rs, groups, sgprs, mem, reps, timed, - Some((&pieces, chain.dwords_per_group, most))) + Some((&pieces, chain.dwords_per_group, most, indirect))) } /// `dispatch` run `reps` times in one command list (a UAV barrier between them, memory not @@ -1781,7 +1799,7 @@ pub(crate) fn profile_buffer_forms( let i = variant - 1; let words = chains[i].dwords_per_group; let most = (budget / (u64::from(words) * 4)).max(1); - (&pieces[i][0], &rs, Some((pieces[i].as_slice(), words, most))) + (&pieces[i][0], &rs, Some((pieces[i].as_slice(), words, most, false))) }; let (out, times) = dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, pso, signature, groups, sgprs, mem, 12, true, chain)?; @@ -1822,7 +1840,8 @@ fn dispatch_with( mem: &[u32], reps: usize, timed: bool, - chain: Option<(&[ID3D12PipelineState], u32, u64)>, + // (pieces, scratch words per group, groups at once, dispatched indirectly) + chain: Option<(&[ID3D12PipelineState], u32, u64, bool)>, ) -> Result<(Vec, Vec), String> { let mut io = sgprs.to_vec(); io.resize(KERNEL_SGPRS, 0); @@ -1875,14 +1894,32 @@ fn dispatch_with( dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(4)), h); } list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]); - list.SetComputeRootSignature(rs); - list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); - // every window (u2..u5) is `mem`, as in the heap above - for k in 2..6 { - list.SetComputeRootUnorderedAccessView(k, mem_buf.GetGPUVirtualAddress()); - } - let scratch = chain.map(|(_, words, most)| { + let bind_root = || { + list.SetComputeRootSignature(rs); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); + // every window (u2..u5) is `mem`, as in the heap above + for k in 2..6 { + list.SetComputeRootUnorderedAccessView(k, mem_buf.GetGPUVirtualAddress()); + } + }; + bind_root(); + // an indirect chain: the groups in an argument buffer, the slicer's commands (a round for + // each slab) and the pieces' command signature + let indirect = match chain { + Some((_, _, most, true)) => { + let rounds = super::pso::dispatch_slabs(groups, most).len() as u32; + let args = buffer(dev, 12, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let mut a = std::ptr::null_mut(); + args.Map(0, None, Some(&mut a)).map_err(e)?; + std::ptr::copy_nonoverlapping(groups.as_ptr(), a as *mut u32, 3); + args.Unmap(0, None); + let commands = super::pso::chain_commands_storage(dev, super::pso::chain_tail_offset(rounds) + 12).ok_or("chain commands")?; + Some((rounds, args, commands, super::pso::chain_command_signature(dev, rs)?)) + } + _ => None, + }; + let scratch = chain.map(|(_, words, most, _)| { let first = super::pso::dispatch_slabs(groups, most)[0].1; let bytes = first.iter().fold(4 * u64::from(words), |n, &g| n * u64::from(g)); buffer(dev, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true) @@ -1905,7 +1942,12 @@ fn dispatch_with( if let Some((heap, _)) = &queries { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k); } - if let (Some((pieces, _, most)), Some(scratch)) = (chain, &scratch) { + if let (Some((pieces, _, most, _)), Some(scratch), Some((rounds, args, commands, sig))) = (chain, &scratch, &indirect) { + super::pso::record_indirect_slicer(&list, args.GetGPUVirtualAddress(), *rounds, most, commands, |slicer| list.SetPipelineState(slicer))?; + bind_root(); + super::pso::record_dispatch_chain_indirect(&list, sig, commands, *rounds, scratch, pieces, |piece| list.SetPipelineState(piece)); + super::pso::restore_indirect_commands(&list, commands); + } else if let (Some((pieces, _, most, _)), Some(scratch)) = (chain, &scratch) { super::pso::record_dispatch_chain( &list, groups, most, scratch, k > 0, pieces, |piece| list.SetPipelineState(piece), diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7938495b9f..cf5575650d 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3800,17 +3800,18 @@ unsafe fn execute_indirect_snapshot( } // 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() { - let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { + 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(|_| ())) }); match chained { - Ok(true) => { + Ok(Indirect::Ran) => { ei_work(this, dispatches, super::targets::RAN); count(DISPATCHES); return; } - Ok(false) => {} + Ok(Indirect::Whole) => {} Err(e) => { ei_work(this, dispatches, super::targets::SKIPPED); count(DISPATCHES_SKIPPED); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 8867abf86b..e11c9689d8 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6209,7 +6209,6 @@ enum ComputeBuild { CachedWhole, // The chain root signature has a separate on-disk namespace. DirectChain, - IndirectChain, } unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, @@ -6222,8 +6221,6 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let library_name = match mode { ComputeBuild::DirectChain => driver_cache::name_for_chain_root_node( dxil, copy.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, copy.NodeMask), - ComputeBuild::IndirectChain => driver_cache::name_for_chain_root_node( - dxil, copy.Flags.0, driver_cache::ChainRoot::IndirectCbv, samplers, copy.NodeMask), _ => driver_cache::name_for_root_node(dxil, copy.Flags.0, false, samplers, copy.NodeMask), }; if !ppv.is_null() { @@ -6240,8 +6237,6 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL 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(); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index ed17b4df3a..b1e65746ee 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -113,10 +113,7 @@ impl PipelineBuilder { dxil, &self.samplers, self.record, iid, &mut raw, self.mode); // (as `translated_compute_pso_once` logs a huge whole program the driver refuses) if hr < 0 && dxil.len() >= huge_pso_bytes() { - let root = match self.mode { - ComputeBuild::IndirectChain => driver_cache::ChainRoot::IndirectCbv, - _ => driver_cache::ChainRoot::DirectConstants, - }; + let root = driver_cache::ChainRoot::DirectConstants; crate::xlog_warn!( "D3D12.X: the driver refused a dispatch chain's compute PSO of record {:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver", self.record, @@ -178,39 +175,11 @@ struct Chain { words: u32, whole_code: Vec, whole: WholeBuild, - plan: Weak, - indirect: IndirectBuild, indirect_noted: AtomicBool, /// a thread of its own builds the whole form (`whole_ready`) whole_sent: AtomicBool, } -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() } - } -} - /// A chain for the thread that builds its whole form (D3D12 objects are free-threaded). struct ChainRef(Arc); unsafe impl Send for ChainRef {} @@ -288,120 +257,18 @@ fn enqueue_whole(job: WholeJob) -> bool { 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() } -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 indirect_blobs_present(chain: &Chain, plan: &DispatchChain) -> bool { - plan.pieces.iter().map(Vec::as_slice).chain([chain.whole_code.as_slice()]).all(|dxil| { - super::driver_cache::path_for_chain_root_node( - dxil, - chain.builder.flags.0, - super::driver_cache::ChainRoot::IndirectCbv, - &chain.builder.samplers, - chain.builder.node, - ) - .and_then(|path| std::fs::metadata(path).ok()) - .is_some_and(|metadata| metadata.len() != 0) - }) -} - -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)); +unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler]) -> Option { + let key = (dev.as_raw() as usize, sampler_key(samplers)); if let Some(signature) = SIGNATURES.lock().unwrap().get(&key).cloned() { return Some(signature); } - let created = match if indirect { - pso::dispatch_chain_indirect_root_signature(dev, samplers) - } else { - pso::dispatch_chain_root_signature(dev, samplers) - } { + let created = match pso::dispatch_chain_root_signature(dev, samplers) { Ok(signature) => signature, Err(e) => { note_translation_error(format!("dispatch-chain root signature: {e}")); @@ -416,7 +283,7 @@ 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, false)?; + let signature = signature_for(dev, samplers)?; 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, mode: ComputeBuild::DirectChain }); @@ -432,14 +299,10 @@ 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(), plan: Arc::downgrade(&plan), - indirect: IndirectBuild::new(), indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) }); - retain_indirect_plan(plan.clone()); + whole_code: whole.to_vec(), whole: WholeBuild::new(), + indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) }); // Initialize the journal on this preparation worker, never on the first recording call. let _ = indirect_used(); - if EARLIER_INDIRECT_USED.contains(&record) && indirect_blobs_present(&chain, &plan) { - request_indirect(&chain); - } PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -479,29 +342,34 @@ pub(in crate::hle::d3d12x) unsafe fn whole_ready(pso: usize) -> Result guard.finish(), - // out of memory (`WholeBuild`): no result is kept, and the guard lets a later - // dispatch queue it again after `WHOLE_RETRY` - Err(_) if guard.job.0.whole.ready().is_none() => drop(guard), - Err(e) => { - crate::xlog_warn!("D3D12.X: the whole form of a split compute program was not built ({e}): its indirect dispatches stay left out"); - guard.finish(); - } + Ok(Whole::Late) +} + +/// Queue `chain`'s whole form onto the `xcl-pso-whole` worker, once; false: it could not be. +fn queue_whole(chain: &Arc) -> bool { + if chain.whole_sent.swap(true, Ordering::AcqRel) { + return true; + } + let guard = WholeSentGuard { job: ChainRef(chain.clone()), finished: false }; + let queued = enqueue_whole(Box::new(move || { + match unsafe { guard.job.0.whole(false) } { + Ok(_) => guard.finish(), + // out of memory (`WholeBuild`): no result is kept, and the guard lets a later + // dispatch queue it again after `WHOLE_RETRY` + Err(_) if guard.job.0.whole.ready().is_none() => drop(guard), + Err(e) => { + crate::xlog_warn!("D3D12.X: the whole form of a split compute program was not built ({e}): its indirect dispatches stay left out"); + guard.finish(); } - })); - if !queued { - chain.whole_sent.store(false, Ordering::Release); - return chain.whole(true).map(Whole::Ready); } + })); + if !queued { + chain.whole_sent.store(false, Ordering::Release); } - Ok(Whole::Late) + queued } struct Scratch { @@ -517,8 +385,7 @@ 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. + /// Keep the title-visible first piece alive while this recording may still execute. first: ID3D12PipelineState, chain: Arc, _indirect_commands: Option>, @@ -705,60 +572,44 @@ fn indirect_rounds() -> u32 { .filter(|&n| n > 0).unwrap_or(16u32).min(1024)) } +/// What `execute_indirect` did with a split program's indirect dispatch. #[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum IndirectReadiness { - Run, - Request, - Fallback, - Fail(HRESULT), -} - -fn indirect_readiness( - whole: Option>, - indirect: Option>, -) -> IndirectReadiness { - match (whole, indirect) { - (_, Some(Ok(()))) => IndirectReadiness::Run, - (Some(Err(hr)), _) => IndirectReadiness::Fail(hr), - (Some(Ok(())), None) => IndirectReadiness::Request, - _ => IndirectReadiness::Fallback, - } -} - -/// Run one Dispatch-only indirect command through an existing split chain. A complete indirect -/// set is independent of the direct whole-form build. Otherwise preserve the synchronous fallback; -/// the slicer writes either bounded piece commands or the whole-form command, never a partial chain. +pub(in crate::hle::d3d12x) enum Indirect { + /// its chain ran + Ran, + /// not a split program, or one whose chain cannot run here: the whole form (`whole_ready`) + Whole, +} + +/// Run one Dispatch-only indirect command through an existing split chain: the pieces a direct +/// dispatch runs, each round's root constants and groups from the slicer's commands +/// (`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). 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>, -) -> Result { - let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(false) }; +) -> Result { + let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(Indirect::Whole) }; note_indirect_use(&chain); - let whole = chain.whole.ready().map(|result| result.map(|_| ())); - let indirect = chain.indirect.result.get().map(|result| match result { - Ok(_) => Ok(()), - Err(hr) => Err(*hr), - }); - match indirect_readiness(whole, indirect) { - IndirectReadiness::Run => {} - IndirectReadiness::Request => { - request_indirect(&chain); - return Ok(false); - } - IndirectReadiness::Fallback => return Ok(false), - IndirectReadiness::Fail(hr) => return Err(format!("whole compute pipeline ({hr:#x})")), - }; - let Some(Ok(indirect)) = chain.indirect.result.get() else { unreachable!() }; - let indirect = indirect.clone(); let allocator = if super::super::alloc_pool::enabled() { super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) } else { allocator }; - if allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { return Ok(false); } + if allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { return Ok(Indirect::Whole); } let group = u64::from(chain.words) * 4; let Some((scratch, _)) = scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, scratch_budget(), group) else { - return Ok(false); + return Ok(Indirect::Whole); + }; + let signature = pso::chain_command_signature(&chain.builder.device, &chain.builder.signature)?; + let tail_signature = pso::dispatch_command_signature(&chain.builder.device)?; + // for a dispatch whose groups do not fit the slicer's rounds + let whole = match chain.whole.ready() { + Some(result) => result.ok(), + None => { + queue_whole(&chain); + None + } }; - let signature = pso::dispatch_command_signature(&chain.builder.device)?; let rounds = indirect_rounds(); let command_bytes = pso::chain_tail_offset(rounds) + 12; let commands = commands_for( @@ -769,13 +620,15 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( list, args, rounds, (scratch.bytes / group).max(1), &commands.buffer, |slicer| super::bind_pipeline_exact(list.as_raw(), original, slicer.as_raw() as usize), )?; - let bound = bind(indirect.signature.as_raw() as usize); + let bound = bind(chain.builder.signature.as_raw() as usize); if bound.is_ok() { - super::bind_pipeline_exact(list.as_raw(), original, indirect.whole.as_raw() as usize); - list.ExecuteIndirect(&signature, 1, &commands.buffer, - pso::chain_tail_offset(rounds), None::<&ID3D12Resource>, 0); + if let Some(whole) = &whole { + super::bind_pipeline_exact(list.as_raw(), original, whole.as_raw() as usize); + list.ExecuteIndirect(&tail_signature, 1, &commands.buffer, + pso::chain_tail_offset(rounds), None::<&ID3D12Resource>, 0); + } pso::record_dispatch_chain_indirect( - list, &signature, &commands.buffer, rounds, &scratch.buffer, indirect.pieces.iter(), + list, &signature, &commands.buffer, rounds, &scratch.buffer, std::iter::once(&first).chain(&chain.tail), |piece| super::bind_pipeline_exact(list.as_raw(), original, piece.as_raw() as usize), ); } @@ -784,7 +637,7 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( scratch, first, chain, _indirect_commands: Some(commands), })); bound?; - Ok(true) + Ok(Indirect::Ran) } #[cfg(test)] @@ -796,25 +649,6 @@ mod tests { assert_eq!(parse_used("1\n0000000000000002\ninvalid\n0\n1\n"), [1, 2].into()); } - #[test] - fn ready_indirect_set_does_not_wait_for_direct_whole() { - assert_eq!(indirect_readiness(None, Some(Ok(()))), IndirectReadiness::Run); - assert_eq!( - indirect_readiness(Some(Err(E_INVALIDARG)), Some(Ok(()))), - IndirectReadiness::Run, - ); - assert_eq!(indirect_readiness(Some(Ok(())), None), IndirectReadiness::Request); - assert_eq!(indirect_readiness(None, None), IndirectReadiness::Fallback); - assert_eq!( - indirect_readiness(Some(Ok(())), Some(Err(E_INVALIDARG))), - IndirectReadiness::Fallback, - ); - assert_eq!( - indirect_readiness(Some(Err(E_INVALIDARG)), Some(Err(E_OUTOFMEMORY))), - IndirectReadiness::Fail(E_INVALIDARG), - ); - } - const MB: u64 = 1 << 20; #[test] @@ -825,33 +659,6 @@ mod tests { >= pso::chain_tail_offset(1024) + 12); } - #[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); @@ -977,19 +784,14 @@ mod tests { 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, plan: Arc::downgrade(&plan), indirect: indirect_build, - indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) })); + whole_code: Vec::new(), whole, indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; 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: the slicer is bound through the PC call) + super::super::adopt(list.as_raw(), Kind::CommandList); + super::super::super::list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); 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(); @@ -1000,7 +802,64 @@ mod tests { list_reset(raw_list); let next_recording = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); assert!(!Arc::ptr_eq(&recorded, &next_recording)); - list.Close().unwrap(); + type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT; + let close: Close = std::mem::transmute(super::super::orig_fn(list.as_raw(), 9)); + assert!(close(list.as_raw()) >= 0); + allocator_reset(allocator); + list_reset(raw_list); + forget(key); + super::super::super::alloc_pool::forget_list(raw_list); + } + } + + /// An indirect dispatch of a split program runs the chain's own pieces under its root signature + /// at once, with no other build and no whole form there: it never waits for the whole form + /// (only queues it, for the slicer's overflow tail). + #[test] + fn an_indirect_dispatch_runs_its_chain_without_any_whole_form() { + 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 } + unsafe { + 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 = dev.unwrap(); + let Ok(dxil) = crate::gpu::recomp::dxc::compile("[numthreads(1,1,1)] void main() {}", "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 }); + // (marked as queued: no whole-form job runs here) + let chain = Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, whole_code: Vec::new(), whole: WholeBuild::new(), + indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(true) }); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + 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: the chain binds its pieces through the PC calls) + super::super::adopt(list.as_raw(), Kind::CommandList); + super::super::super::list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); + 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(); + let key = first.as_raw() as usize; + // the chain's own root signature, which `bind` sets as the title's binding does + let bind = |root: usize| { + assert_eq!(root, rs.as_raw() as usize, "the chain's root signature, as for a direct dispatch"); + list.SetComputeRootSignature(&rs); + Ok(()) + }; + CHAINS.lock().unwrap().insert(key, chain); + assert_eq!(execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), bind), Ok(Indirect::Ran)); + 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; + let close: Close = std::mem::transmute(super::super::orig_fn(list.as_raw(), 9)); + assert!(close(list.as_raw()) >= 0, "the recorded chain closes"); allocator_reset(allocator); list_reset(raw_list); forget(key);