From c79e41fd5f4bb09b807f7a837049e55849e2daeb Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:28:12 -0800 Subject: [PATCH] D3D12.X: reuse indirect commands within one recording list ExecuteIndirect command storage was a committed resource per call. Keep one weakly indexed resource per command-list recording and reuse offset zero after a complete UAV-to-read-to-UAV state cycle. Recordings retain it through the native allocator reset, including bind failures, while list reset and release invalidate future reuse. Assisted-by: Codex (GPT-5.6-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 17 ++++- crates/xcl/src/hle/d3d12x/list_x.rs | 2 + .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 62 ++++++++++++++++--- 3 files changed, 73 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 515e29d5df..5d45a85e88 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1548,9 +1548,14 @@ fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12Pip } } +#[cfg(test)] pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32) -> Option { + chain_commands_storage(dev, chain_tail_offset(rounds) + 12) +} + +pub(crate) unsafe fn chain_commands_storage(dev: &ID3D12Device, bytes: u64) -> Option { let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_tail_offset(rounds) + 12, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + 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: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() }; @@ -1583,6 +1588,16 @@ pub(crate) unsafe fn record_indirect_slicer( Ok(()) } +/// Complete the command-storage state cycle. A closed list can then be submitted repeatedly, and +/// another indirect dispatch recorded later on this list can overwrite the same commands at zero. +pub(crate) unsafe fn restore_indirect_commands(list: &ID3D12GraphicsCommandList, commands: &ID3D12Resource) { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(commands), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS }) } }]); +} + pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( list: &ID3D12GraphicsCommandList, sig: &ID3D12CommandSignature, commands: &ID3D12Resource, rounds: u32, scratch: &ID3D12Resource, pieces: impl IntoIterator + Clone, diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index cdff2814db..31990f78dc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1245,6 +1245,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C let key = list as usize; // (of a list that was here before and whose release was not seen: the GPU may still use it) release_copy_scratch(key); + super::real::dispatch_chain::list_reset(key); let old = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -1279,6 +1280,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C pub(super) fn on_release(list: usize) { super::alloc_pool::forget_list(list); release_copy_scratch(list); + super::real::dispatch_chain::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { if !old.sparse_writes.is_empty() { diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 29db8ef012..ef101018f4 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -356,17 +356,49 @@ struct Recording { /// Indirect execution uses its separate CBV-compatible duplicates. first: ID3D12PipelineState, chain: Arc, - _indirect_commands: Option, + _indirect_commands: Option>, } static RECORDINGS: LazyLock>>>> = LazyLock::new(Default::default); /// list → the allocator it records on and the scratch its chains share: they are dispatched one /// after another, with a barrier between them (the recordings keep it alive) static SHARED: LazyLock)>>> = LazyLock::new(Default::default); +/// One recording list reuses indirect commands at offset zero. Buffer state transitions are +/// resource-wide, so storage is deliberately never shared across lists. +static COMMANDS: LazyLock)>>> = LazyLock::new(Default::default); + +struct CommandStorage { + buffer: ID3D12Resource, + bytes: u64, +} + +const COMMAND_STORAGE_BYTES: u64 = 64 << 10; + +fn command_storage_bytes(bytes: u64) -> u64 { + bytes.max(COMMAND_STORAGE_BYTES).next_multiple_of(COMMAND_STORAGE_BYTES) +} + +unsafe fn commands_for( + dev: &ID3D12Device, list: usize, allocator: usize, bytes: u64, +) -> Option> { + { + let commands = COMMANDS.lock().unwrap(); + if let Some((_, storage)) = commands.get(&list).filter(|entry| entry.0 == allocator) { + if let Some(storage) = storage.upgrade().filter(|storage| storage.bytes >= bytes) { + return Some(storage); + } + } + } + let size = command_storage_bytes(bytes); + let storage = Arc::new(CommandStorage { buffer: pso::chain_commands_storage(dev, size)?, bytes: size }); + COMMANDS.lock().unwrap().insert(list, (allocator, Arc::downgrade(&storage))); + Some(storage) +} /// `list` begins another recording, which the GPU may run beside the last one. pub(in crate::hle::d3d12x) fn list_reset(list: usize) { SHARED.lock().unwrap().remove(&list); + COMMANDS.lock().unwrap().remove(&list); } /// `to` records right after `from` on the same allocator: its chains go on in `from`'s scratch. @@ -532,18 +564,21 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( }; let signature = pso::dispatch_command_signature(&chain.builder.device)?; let rounds = indirect_rounds(); - let commands = pso::chain_commands_buffer(&chain.builder.device, rounds) - .ok_or("no command buffer for split ExecuteIndirect")?; + let command_bytes = pso::chain_tail_offset(rounds) + 12; + let commands = commands_for( + &chain.builder.device, list.as_raw() as usize, allocator, command_bytes, + ).ok_or("no command buffer for split ExecuteIndirect")?; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), &commands)?; + pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), &commands.buffer)?; let bound = bind(indirect.signature.as_raw() as usize); if bound.is_ok() { list.SetPipelineState(&indirect.whole); - list.ExecuteIndirect(&signature, 1, &commands, + list.ExecuteIndirect(&signature, 1, &commands.buffer, pso::chain_tail_offset(rounds), None::<&ID3D12Resource>, 0); - pso::record_dispatch_chain_indirect(list, &signature, &commands, rounds, &scratch.buffer, + pso::record_dispatch_chain_indirect(list, &signature, &commands.buffer, rounds, &scratch.buffer, indirect.pieces.iter()); } + pso::restore_indirect_commands(list, &commands.buffer); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { scratch, first, chain, _indirect_commands: Some(commands), })); @@ -562,6 +597,14 @@ mod tests { const MB: u64 = 1 << 20; + #[test] + fn indirect_command_storage_covers_the_fixed_recording_at_64k_granularity() { + assert_eq!(command_storage_bytes(12), 64 << 10); + assert_eq!(command_storage_bytes((64 << 10) + 1), 128 << 10); + assert!(command_storage_bytes(pso::chain_tail_offset(1024) + 12) + >= pso::chain_tail_offset(1024) + 12); + } + #[test] fn retained_indirect_plans_are_deduplicated_and_bounded() { let plan = |byte: u8| Arc::new(DispatchChain { @@ -730,7 +773,12 @@ mod tests { super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); let args = pso::chain_commands_buffer(&dev, 1).unwrap(); assert_eq!(execute_indirect(&list, key, 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()))); + let recorded = RECORDINGS.lock().unwrap().get(&allocator).unwrap()[0]._indirect_commands.clone().unwrap(); + let reused = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); + assert!(Arc::ptr_eq(&recorded, &reused)); + 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(); allocator_reset(allocator); list_reset(raw_list);