From 4aadaab12e9237a76d8ad99494b1777de418f76e Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:34:33 -0500 Subject: [PATCH 01/15] D3D12.X: an ExecuteIndirect of a split program runs its pieces An ExecuteIndirect of a compute program that the recompiler split into pieces fell back to the program's whole form, and that form was compiled on the recording thread when first needed. On an RTX 5070 Ti with XCL_DIRECT_DXIL=1 a retail title stalls its world load on it: 11 per-material programs, 9-14 pieces each, each dispatched through ExecuteIndirect, each whole form 690-950 KB of DXIL taking 16-40 s to compile, one after another from 326 s to past 600 s. The title's ExecuteIndirects of split programs all have one command signature: one Dispatch, stride 12, MaxCommandCount 1, no count buffer (150 of them in 360 s). Their group counts are written on the GPU, so the CPU cannot slice them when recording. The ExecuteIndirect now runs the chain on the GPU. A small compute pass (pso::record_slicer) reads the title's arguments (and count) and writes, for a fixed number of rounds, one command per piece of each slab of dispatch_slabs (the root constants of record_dispatch_chain, then the slab's group counts); unused rounds get empty dispatches. Each piece then runs one ExecuteIndirect per round with the chain's command signature, with UAV barriers between them, in the bounded scratch. The rounds come from the arguments the CPU sees now and the most slabs an earlier ExecuteIndirect of the program had, plus a quarter (2 to XCL_SPLIT_INDIRECT_ROUNDS, 16). When the arguments need more slabs and the whole form is built already, the slicer leaves the rounds empty and writes the title's Dispatch arguments after them, and the whole form runs on those through a command signature of one Dispatch; otherwise it leaves those empty. So one of the two runs, without predication: under one predicate, two NVIDIA Ampere cards (RTX 3080 Ti, RTX 3070) ran some of the rounds and not the whole form (#2404). The whole form's ExecuteIndirect is recorded first, and the rounds' UAV barriers follow it: on the RTX 3080 Ti it ran right after the slicer alone but not after the pieces' ExecuteIndirects. If the whole form is not built, the rounds run, the lost slabs are counted and warned about once per program, the whole form is built on another thread for the next ones, and the next rounds are sized from the count. The title's own predication holds for the slicer too, so the same choice is made under it. Bundles, lists without scratch and other command signatures keep the whole form. The 'compute split' line counts chained, whole and lost ExecuteIndirects. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/pso.rs | 200 ++++++++++++++++++ crates/xcl/src/hle/d3d12x/bind.rs | 63 ++++++ crates/xcl/src/hle/d3d12x/device_x.rs | 3 + .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 187 +++++++++++++++- 4 files changed, 448 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b8b0cde0f1..2ea059dfb1 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1306,6 +1306,16 @@ pub(crate) fn dispatch_slabs(grid: [u32; 3], most: u64) -> Vec<([u32; 3], [u32; out } +/// How many slabs `dispatch_slabs` makes of `grid` (without making them) +pub(crate) fn slab_count(grid: [u32; 3], most: u64) -> u64 { + let [x, y, z] = grid.map(u64::from); + if x * y * z == 0 { return 0; } + let sx = x.min((most).max(1)); + let sy = if sx == x { y.min((most / x).max(1)) } else { 1 }; + let sz = if sx == x && sy == y { z.min((most / (x * y)).max(1)) } else { 1 }; + x.div_ceil(sx) * y.div_ceil(sy) * z.div_ceil(sz) +} + /// A chain's dispatch of `grid` groups, `most` of them at once (`dispatch_slabs`). `used`: the /// list (or one before it) has used `scratch`. pub(crate) unsafe fn record_dispatch_chain<'a>( @@ -1332,6 +1342,191 @@ pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[Stat abi_signature(dev, false, samplers, true) } +/// Bytes of one command of a chain's ExecuteIndirect (`chain_command_signature`): the eight +/// root constants of `record_dispatch_chain` and the slab's Dispatch. +pub(crate) const CHAIN_COMMAND_BYTES: u32 = 44; + +/// The command signature of a chain's ExecuteIndirect on the chain's root signature `rs`. +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: Option = None; + unsafe { dev.CreateCommandSignature(&desc, rs, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; + sig.ok_or_else(|| "CreateCommandSignature".into()) +} + +/// One thread that turns a title's Dispatch arguments into a chain's commands: each command's +/// groups in the slabs of `dispatch_slabs`, one slab a round, `rounds` rounds of `pieces` +/// commands (`CHAIN_COMMAND_BYTES` each; unused rounds dispatch nothing). After them +/// (`chain_tail_offset`): 1 when the rounds did not hold every slab, 0, the slabs there were (at +/// most 2^32 - 256), 0; then `commands` Dispatch arguments for the whole form. With `whole` set +/// and more slabs than rounds, those are the title's and the rounds dispatch nothing; else they +/// are empty. So one of the two runs without predication (on NVIDIA Ampere cards, under one +/// predicate both ran in part, #2404). +const SLICER: &str = r#" +#define RS "RootConstants(num32BitConstants=7, b0), SRV(t0), SRV(t1), UAV(u0)" +cbuffer C : register(b0) { uint rounds; uint most; uint commands; uint stride; uint counted; uint pieces; uint whole; }; +ByteAddressBuffer args : register(t0); +ByteAddressBuffer count : register(t1); +RWByteAddressBuffer cmds : register(u0); +void put(uint r, uint3 n, uint3 o) { + for (uint i = 0; i < pieces; i++) { + uint at = (r * pieces + i) * 44; + cmds.Store4(at, uint4(n, i)); + cmds.Store4(at + 16, uint4(o, 0)); + cmds.Store3(at + 32, n); + } +} +uint3 slab(uint3 g) { + uint3 s; + s.x = min(g.x, max(most, 1)); + s.y = s.x == g.x ? min(g.y, max(most / g.x, 1)) : 1; + s.z = s.x == g.x && s.y == g.y ? min(g.z, max(most / g.x / g.y, 1)) : 1; + return s; +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint n = counted != 0 ? min(count.Load(0), commands) : commands; + float slabs = 0; + for (uint k = 0; k < n; k++) { + uint3 g = min(args.Load3(k * stride), 65535); + if (any(g == 0)) continue; + uint3 c = (g + slab(g) - 1) / slab(g); + slabs += (float)c.x * c.y * c.z; + } + bool partial = slabs > (float)rounds; + bool full = partial && whole != 0; + uint r = 0; + for (uint k = 0; k < n && !full; k++) { + uint3 g = min(args.Load3(k * stride), 65535); + if (any(g == 0)) continue; + uint3 s = slab(g); + for (uint oz = 0; oz < g.z && r < rounds; oz += s.z) + for (uint oy = 0; oy < g.y && r < rounds; oy += s.y) + for (uint ox = 0; ox < g.x && r < rounds; ox += s.x) { + uint3 o = uint3(ox, oy, oz); + put(r++, min(s, g - o), o); + } + } + for (; r < rounds; r++) put(r, 0, 0); + uint at = (rounds * pieces * 44 + 7) & ~7u; + cmds.Store4(at, uint4(partial ? 1 : 0, 0, (uint)min(slabs, 4294967040.0), 0)); + for (uint k = 0; k < commands; k++) cmds.Store3(at + 16 + k * 12, full && k < n ? args.Load3(k * stride) : 0); +} +"#; + +/// Where the slicer's words after the rounds are in a chain's command buffer; the whole form's +/// Dispatch arguments follow 16 bytes later +pub(crate) fn chain_tail_offset(rounds: u32, pieces: u32) -> u64 { + u64::from(rounds * pieces * CHAIN_COMMAND_BYTES).next_multiple_of(8) +} + +/// Bytes of a chain's command buffer (`SLICER`) for `commands` of the title's +pub(crate) fn chain_commands_bytes(rounds: u32, pieces: u32, commands: u32) -> u64 { + chain_tail_offset(rounds, pieces) + 16 + 12 * u64::from(commands) +} + +/// A command signature of one Dispatch (12 bytes), for the whole form's arguments (made once per +/// device). +pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result { + static MADE: Mutex> = Mutex::new(None); + let mut g = MADE.lock().unwrap(); + if let Some((_, sig)) = g.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) { + return Ok(sig.clone()); + } + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }; + let mut sig: Option = None; + unsafe { dev.CreateCommandSignature(&desc, None, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; + let sig = sig.ok_or("CreateCommandSignature")?; + *g = Some((windows::core::Interface::as_raw(dev) as usize, sig.clone())); + Ok(sig) +} + +/// The slicer's root signature and pipeline (made once per device). +fn slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static MADE: Mutex> = Mutex::new(None); + let mut g = MADE.lock().unwrap(); + if let Some((_, rs, pso)) = g.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) { + return Ok((rs.clone(), pso.clone())); + } + let dxil = super::dxc::compile(SLICER, "main", "cs_6_0", &[])?; + unsafe { + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("slicer root signature: {e}"))?; + 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 pso: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).map_err(|e| format!("slicer pipeline: {e}"))?; + *g = Some((windows::core::Interface::as_raw(dev) as usize, rs.clone(), pso.clone())); + Ok((rs, pso)) + } +} + +/// A chain's command buffer (`chain_commands_bytes`) in the UNORDERED_ACCESS state: the slicer +/// writes it, ExecuteIndirect reads it, and the CPU reads the slabs back. +pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, pieces: u32, commands: u32) -> Option { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: chain_commands_bytes(rounds, pieces, commands), Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, CreationNodeMask: 1, VisibleNodeMask: 1 }; + let mut resource = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?; + resource +} + +/// The slicer's dispatch: the title's `commands` commands of `stride` bytes at `args` (GPU +/// address; the count at `count` when there is one) into `out` (`chain_commands_bytes`, in the +/// UNORDERED_ACCESS state, left in INDIRECT_ARGUMENT); `whole`: the whole form runs when the +/// rounds cannot hold the slabs. It sets the list's compute root signature: the caller binds its +/// own again. +#[allow(clippy::too_many_arguments)] +pub(crate) unsafe fn record_slicer(list: &ID3D12GraphicsCommandList, args: u64, stride: u32, commands: u32, count: Option, + rounds: u32, most: u64, pieces: u32, whole: bool, out: &ID3D12Resource) -> Result<(), String> { + let dev: ID3D12Device = { let mut d: Option = None; list.GetDevice(&mut d).map_err(|e| e.to_string())?; d.ok_or("device")? }; + let (rs, pso) = slicer(&dev)?; + let constants = [rounds, most.min(u64::from(u32::MAX)) as u32, commands, stride, count.is_some() as u32, pieces, whole as u32]; + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, 7, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, args); + list.SetComputeRootShaderResourceView(2, count.unwrap_or(args)); + list.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); + // after the dispatches that wrote the arguments + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); + list.Dispatch(1, 1, 1); + 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 }) } }]); + Ok(()) +} + +/// `record_dispatch_chain` from the slicer's commands in `commands` (`rounds` rounds), after the +/// six common root views have been bound. +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() { + 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); + list.ExecuteIndirect(sig, 1, commands, u64::from((r * n + i as u32) * CHAIN_COMMAND_BYTES), None::<&ID3D12Resource>, 0); + } + } +} + fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: bool) -> Result { let statics: Vec = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { @@ -1408,6 +1603,11 @@ mod slab_tests { } } assert_eq!(dispatch_slabs([240, 135, 1], 1400).len(), 27, "five rows of 240 at once"); + for grid in [[1, 1, 1], [2, 3, 2], [240, 135, 1], [65_535, 2, 1], [5, 1, 7], [0, 4, 4]] { + for most in [0, 1, 3, 239, 240, 1000, u64::MAX] { + assert_eq!(super::slab_count(grid, most), dispatch_slabs(grid, most).len() as u64, "{grid:?} {most}"); + } + } assert!(dispatch_slabs([0, 4, 4], 8).is_empty()); } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..88dcf50f3a 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -263,6 +263,19 @@ fn signature_dispatches(sig: usize) -> bool { DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } +/// command signatures of one Dispatch argument → their stride (a split program runs them as its +/// chain, `chained_indirect`) +static DISPATCH_ONLY: Mutex>> = Mutex::new(None); + +pub(super) fn note_dispatch_only_signature(sig: usize, stride: Option) { + let mut s = DISPATCH_ONLY.lock().unwrap(); + let s = s.get_or_insert_with(Default::default); + match stride { + Some(n) => s.insert(sig, n), + None => s.remove(&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) @@ -276,6 +289,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } let pso = super::pso_async::resolve_wait(raw_pso); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + let (args_off_title, count_off_title) = (args_off, count_off); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), 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 @@ -335,6 +349,21 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + if compute { + // a split program: its chain (it binds the ABI itself) + match chained_indirect(this, list, pso, sig, max, (args, args_off_title, args_off), (count_buf, count_off_title, count_off)) { + Ok(true) => return count(DISPATCHES), + Ok(false) => {} + Err(e) => { + count(DISPATCHES_SKIPPED); + 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 of a split program skipped: {e}"); + } + return; + } + } + } match bind_abi(this, list, pso, gfx) { Ok(()) => { if compute { @@ -361,6 +390,40 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } +/// An ExecuteIndirect of split program `pso` with a command signature of one Dispatch, run as its +/// chain (`dispatch_chain::execute_indirect`); the buffers as (resource, title's offset, PC's). +/// Ok(false): nothing recorded – run it as the whole form. +#[allow(clippy::too_many_arguments)] +unsafe fn chained_indirect(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, sig: usize, max: u32, + (args, args_title, args_pc): (usize, u64, u64), (count_buf, count_title, count_pc): (usize, u64, u64)) -> Result { + let Some(stride) = DISPATCH_ONLY.lock().unwrap().as_ref().and_then(|m| m.get(&sig).copied()) else { return Ok(false) }; + let Some(args_va) = indirect_address(args, args_title, args_pc) else { return Ok(false) }; + let count_va = match count_buf { + 0 => None, + c => match indirect_address(c, count_title, count_pc) { Some(v) => Some(v), None => return Ok(false) }, + }; + // the arguments there now (the GPU's last ones) size the rounds + let read = |res: usize, off: u64, n: usize| -> Option> { + let (p, size) = super::real::console_buffer(res)?; + let at = p + off as usize; + (off as usize + 4 * n <= size && crate::gpu::shader::readable(at, 4 * n)) + .then(|| (0..n).map(|i| std::ptr::read_volatile((at as *const u32).add(i))).collect()) + }; + let n = if count_buf == 0 { max } else { read(count_buf, count_title, 1).map_or(max, |c| c[0].min(max)) }; + let seen: Vec<[u32; 3]> = (0..n.min(64)).filter_map(|k| read(args, args_title + u64::from(k * stride), 3)).map(|v| [v[0], v[1], v[2]]).collect(); + super::real::dispatch_chain::execute_indirect(list, pso, with(this, |s| s.allocator), args_va, stride, max, count_va, &seen, + || bind_abi(this, list, pso, false)) +} + +/// The GPU address of a title's buffer `res` at its offset `title` (a buffer in unified memory) or +/// `pc` (another) +unsafe fn indirect_address(res: usize, title: u64, pc: u64) -> Option { + match super::real::console_buffer(res) { + Some((p, _)) => super::real::uma_va_of(p + title as usize), + None => Some(ID3D12Resource::from_raw_borrowed(&(res as *mut c_void))?.GetGPUVirtualAddress()).filter(|&va| va != 0).map(|va| va + pc), + } +} + /// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses static ARGUMENT_ORDER: Mutex> = Mutex::new(None); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 57c30e0ffe..3586d4db25 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1259,6 +1259,9 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); + let stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let dispatch_only = list.len() == 1 && list[0][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32 && stride >= 12 && stride % 4 == 0; + super::bind::note_dispatch_only_signature(*ppv as usize, dispatch_only.then_some(stride)); } hr } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6fa76b4cbf..d5b272b2e4 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -13,12 +13,20 @@ static SLABS: AtomicU64 = AtomicU64::new(0); static LIVE: AtomicU64 = AtomicU64::new(0); static PEAK: AtomicU64 = AtomicU64::new(0); static WANTED: AtomicU64 = AtomicU64::new(0); +/// ExecuteIndirects run as chains, those of them that ran the whole form instead (more slabs than +/// rounds), and the slabs lost when there was no whole form yet +static INDIRECT: AtomicU64 = AtomicU64::new(0); +static INDIRECT_WHOLE: AtomicU64 = AtomicU64::new(0); +static INDIRECT_LOST: AtomicU64 = AtomicU64::new(0); +/// ExecuteIndirects that ran the whole form (not chainable) +static WHOLE_INDIRECT: AtomicU64 = AtomicU64::new(0); pub(crate) fn log_counts() { let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; - crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab)", - PROGRAMS.load(Ordering::Relaxed), PIECES.load(Ordering::Relaxed), DISPATCHES.load(Ordering::Relaxed), SLABS.load(Ordering::Relaxed), - mib(&LIVE), mib(&PEAK), mib(&WANTED)); + let n = |a: &AtomicU64| a.load(Ordering::Relaxed); + crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab); ExecuteIndirect: {} chained ({} of them whole, {} slabs lost), {} whole", + n(&PROGRAMS), n(&PIECES), n(&DISPATCHES), n(&SLABS), mib(&LIVE), mib(&PEAK), mib(&WANTED), + n(&INDIRECT), n(&INDIRECT_WHOLE), n(&INDIRECT_LOST), n(&WHOLE_INDIRECT)); } /// The scratch a dispatch uses at once, `XCL_SPLIT_SCRATCH_MB` (256): more groups than fit run in @@ -55,6 +63,13 @@ struct Chain { whole_code: Vec, whole: OnceLock, build_whole: Mutex<()>, + /// its command signature for ExecuteIndirect (`pso::chain_command_signature`) + signature: OnceLock, + /// the most slabs one of its ExecuteIndirects had + slabs: std::sync::atomic::AtomicU32, + /// its whole form was asked for in the background / a lost slab was reported + wanted: std::sync::atomic::AtomicBool, + warned: std::sync::atomic::AtomicBool, } impl Chain { @@ -66,6 +81,16 @@ impl Chain { let _ = self.whole.set(p.clone()); Ok(p) } + + /// The whole form built on another thread, for a later ExecuteIndirect with more slabs than rounds + fn want_whole(self: &Arc) { + if !self.wanted.swap(true, Ordering::Relaxed) { + let chain = self.clone(); + std::thread::Builder::new().name("xcl-chain-whole".into()).spawn(move || unsafe { + if let Err(e) = chain.whole() { crate::xlog_warn!("D3D12.X: whole form of a split program: {e}"); } + }).ok(); + } + } } static CHAINS: LazyLock>>> = LazyLock::new(Default::default); @@ -91,7 +116,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: OnceLock::new(), build_whole: Mutex::new(()) }); + whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()), signature: OnceLock::new(), + slabs: Default::default(), wanted: Default::default(), warned: Default::default() }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -106,6 +132,7 @@ pub(super) fn forget(pso: usize) { pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result, String> { let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + if chain.is_some() { WHOLE_INDIRECT.fetch_add(1, Ordering::Relaxed); } chain.map(|c| c.whole()).transpose() } @@ -124,6 +151,49 @@ struct Recording { scratch: Arc, first: ID3D12PipelineState, chain: Arc, + indirect: Option, +} + +/// The commands of a chained ExecuteIndirect (`pso::record_slicer`), read when the GPU is done +/// with them (the allocator is reset): with more slabs than rounds, the next ExecuteIndirect of +/// the program records more, and the whole form is built for it +struct Indirect { + commands: ID3D12Resource, + at: u64, + rounds: u32, + /// the whole form ran instead (the slicer gave it the arguments); `checked`: the chain was + /// recorded (under the title's predication the slicer may not run: its words stay 0) + whole: bool, + checked: bool, +} + +impl Recording { + fn read_back(&self) { + let Some(i) = self.indirect.as_ref().filter(|i| i.checked) else { return }; + let mut p = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: i.at as usize, End: i.at as usize + 16 }; + if unsafe { i.commands.Map(0, Some(&range), Some(&mut p)) }.is_err() { return; } + let [partial, _, slabs, _] = unsafe { std::ptr::read_volatile((p as *const u8).add(i.at as usize) as *const [u32; 4]) }; + unsafe { i.commands.Unmap(0, Some(&D3D12_RANGE::default())) }; + if partial == 0 { return; } + self.chain.slabs.fetch_max(slabs, Ordering::Relaxed); + if i.whole { + INDIRECT_WHOLE.fetch_add(1, Ordering::Relaxed); + return; + } + INDIRECT_LOST.fetch_add(u64::from(slabs.saturating_sub(i.rounds)), Ordering::Relaxed); + if !self.chain.warned.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: ExecuteIndirect of a split program ({:#x}) had {slabs} slabs for {} rounds: {} lost; its whole form is built for the next ones", + self.first.as_raw() as usize, i.rounds, slabs - i.rounds); + } + self.chain.want_whole(); + } +} + +impl Drop for Recording { + fn drop(&mut self) { + self.read_back(); + } } static RECORDINGS: LazyLock>>>> = LazyLock::new(Default::default); @@ -225,7 +295,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, return Ok(()); }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - let held = Arc::new(Recording { scratch, first, chain }); + let held = Arc::new(Recording { scratch, first, chain, indirect: None }); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); DISPATCHES.fetch_add(1, Ordering::Relaxed); SLABS.fetch_add(slabs.len() as u64, Ordering::Relaxed); @@ -233,6 +303,72 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, Ok(()) } +/// The rounds a chained ExecuteIndirect records at most, `XCL_SPLIT_INDIRECT_ROUNDS` (16): each +/// is one ExecuteIndirect and one barrier per piece, also when the title's arguments leave it empty. +fn most_rounds() -> u32 { + static B: OnceLock = OnceLock::new(); + *B.get_or_init(|| std::env::var("XCL_SPLIT_INDIRECT_ROUNDS").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(16u32).min(1024)) +} + +/// The rounds for slabs of `most` groups: as many as the arguments there now (`seen`, the GPU's +/// last ones) or an earlier ExecuteIndirect of the program (`before`) had, a quarter more, at +/// least two and at most `cap`. +fn indirect_rounds(seen: &[[u32; 3]], most: u64, before: u32, cap: u32) -> u32 { + let now: u64 = seen.iter().map(|&g| pso::slab_count(g, most)).sum(); + let want = now.max(u64::from(before)); + (want + want.div_ceil(4)).clamp(2, u64::from(cap.max(2))) as u32 +} + +/// An ExecuteIndirect of split program `pso` whose command signature is one Dispatch of `stride` +/// bytes: `commands` of them at GPU address `args` (their count at `count`, when given), run as +/// the chain. `seen`: the arguments the CPU sees there now. `bind` binds the ABI after the +/// slicer. The whole form (built already) runs instead when the arguments have more slabs than +/// the rounds, also under the title's predication (which then holds for the slicer too). +/// Ok(false): nothing recorded (no chain, a bundle, no scratch) – the caller runs the whole form. +#[allow(clippy::too_many_arguments)] +pub(in crate::hle::d3d12x) unsafe fn execute_indirect(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, args: u64, stride: u32, + commands: u32, count: Option, seen: &[[u32; 3]], bind: impl FnOnce() -> Result<(), String>) -> Result { + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + let Some(chain) = chain else { 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) + } else { allocator }; + if allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { return Ok(false); } + let dev = &chain.builder.device; + let group = u64::from(chain.words) * 4; + let Some((scratch, _)) = scratch_for(dev, list.as_raw() as usize, allocator, scratch_budget(), group) else { return Ok(false) }; + let most = (scratch.bytes / group).max(1); + let sig = match chain.signature.get() { + Some(s) => s.clone(), + None => { let s = pso::chain_command_signature(dev, &chain.builder.signature)?; chain.signature.get_or_init(|| s).clone() } + }; + let rounds = indirect_rounds(seen, most, chain.slabs.load(Ordering::Relaxed), most_rounds()); + let pieces = chain.tail.len() as u32 + 1; + let buffer = pso::chain_commands_buffer(dev, rounds, pieces, commands).ok_or("no buffer for the commands of a chained ExecuteIndirect")?; + let full = chain.whole.get().cloned().map(|p| pso::dispatch_command_signature(dev).map(|s| (p, s))).transpose()?; + let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); + pso::record_slicer(list, args, stride, commands, count, rounds, most, pieces, full.is_some(), &buffer)?; + // the list uses `buffer` from here: the recording keeps it until the allocator is reset, also + // when binding fails and nothing more is recorded + let bound = bind(); + let at = pso::chain_tail_offset(rounds, pieces); + if bound.is_ok() { + // the slicer left either these arguments or the rounds empty. The whole form goes first + // (each round's pieces start after a UAV barrier), with nothing of the chain before it: + // after the pieces' ExecuteIndirects it did not run right on an RTX 3080 Ti (#2404) + if let Some((full, sig)) = &full { + list.SetPipelineState(full); + list.ExecuteIndirect(sig, commands, &buffer, at + 16, None::<&ID3D12Resource>, 0); + } + pso::record_dispatch_chain_indirect(list, &sig, &buffer, rounds, &scratch.buffer, std::iter::once(&first).chain(&chain.tail)); + } + let indirect = Indirect { commands: buffer, at, rounds, whole: full.is_some(), checked: bound.is_ok() }; + RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { scratch, first, chain, indirect: Some(indirect) })); + bound?; + INDIRECT.fetch_add(1, Ordering::Relaxed); + Ok(true) +} + #[cfg(test)] mod tests { use super::{scratch_bytes, LEAST}; @@ -284,4 +420,45 @@ mod tests { assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true)); assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true)); } + + #[test] + fn a_chained_execute_indirect_keeps_its_commands_when_binding_fails() { + use super::*; + unsafe extern "system" fn never(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } + unsafe { + let mut dev: Option = 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 first: ID3D12PipelineState = dev.CreateComputePipelineState(&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() }).unwrap(); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs, flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); + let pso = first.as_raw() as usize; + CHAINS.lock().unwrap().insert(pso, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, whole_code: Vec::new(), whole: OnceLock::new(), + build_whole: Mutex::new(()), signature: OnceLock::new(), slabs: Default::default(), wanted: Default::default(), warned: Default::default() })); + 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, 1).unwrap(); + let r = execute_indirect(&list, pso, allocator, args.GetGPUVirtualAddress(), 12, 1, None, &[[1, 1, 1]], + || Err("unified memory is full".to_string())); + assert_eq!(r, Err("unified memory is full".to_string())); + // the slicer's dispatch is recorded: its command buffer lives until the allocator is + // reset, and the read-back does not take the rounds that were not recorded + let kept = RECORDINGS.lock().unwrap().get(&allocator).map(|v| v.iter().filter_map(|r| r.indirect.as_ref().map(|i| i.checked)).collect::>()); + assert_eq!(kept, Some(vec![false])); + list.Close().unwrap(); + allocator_reset(allocator); + list_reset(raw_list); + forget(pso); + super::super::super::alloc_pool::forget_list(raw_list); + } + } } From dbc793d5b85d5aa8bff179eb56f8a05c3440ce66 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:34:34 -0500 Subject: [PATCH 02/15] Tests: a split program's ExecuteIndirect matches the whole program runner::dispatch_split_indirect records a chain's ExecuteIndirect the way the runtime does: the slicer, the whole form on the slicer's arguments when there is one, then the rounds' ExecuteIndirects. dispatch_chain_divergent_forward_edges_3d runs it with one command, several with empty commands and a count buffer that leaves the last out, and a stride of 20 bytes, in slabs of 1 to 12 groups and 1 to 16 rounds, each without and with a whole form. It checks the memory against the whole program and the slicer's slab count. With more slabs than rounds it checks that the slicer says so and that the whole form runs instead (the memory would not match if the rounds had run too). Without a whole form it checks that only the rounds' groups run. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module/split.rs | 35 ++++++++++ crates/xcl/src/gpu/recomp/runner.rs | 93 +++++++++++++++++++++++-- 2 files changed, 121 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 7a88b9ae11..eea89acd17 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -1150,6 +1150,41 @@ mod tests { let result = runner::dispatch_split_by(&chain, [2, 3, 2], &initial, most).unwrap(); assert_eq!(result, expected, "split {threads}, {most} groups at once"); } + // through ExecuteIndirect (`pso::record_slicer`): one command, several with empty ones + // and a count that leaves the last out, a stride with other words, in slabs; and with + // the whole form built, as a program has it from its first ExecuteIndirect on: its + // arguments are then empty and recorded before the rounds + let one = [2, 3, 2]; + let several = [0, 1, 1, 2, 3, 2, 2, 3, 2]; + let wide = [2, 3, 2, 7, 7, 0, 0, 0, 7, 7]; + let runs: [(&[u32], u32, u32, Option); 3] = [(&one, 12, 1, None), (&several, 12, 3, Some(2)), (&wide, 20, 2, None)]; + for (args, stride, commands, count) in runs { + for (most, rounds) in [(12, 1), (12, 3), (5, 4), (2, 6), (1, 12), (1, 16)] { + for built in [None, Some(&whole[..])] { + let ind = runner::ChainIndirect { args, stride, commands, count, rounds, whole: built }; + let (result, tail) = runner::dispatch_split_indirect(&chain, &ind, &initial, most).unwrap(); + let slabs = crate::gpu::recomp::pso::slab_count([2, 3, 2], most) as u32; + let what = format!("split {threads}, {args:?}, {most} groups, {rounds} rounds, whole form {}", built.is_some()); + assert_eq!(tail, [0, 0, slabs, 0], "{what}"); + assert_eq!(result, expected, "{what}"); + } + } + } + // more slabs than rounds: the slicer says so, the rounds dispatch nothing, and the whole + // form runs instead on the slicer's arguments + for (most, rounds) in [(1, 11), (2, 2), (5, 2)] { + let slabs = crate::gpu::recomp::pso::slab_count([2, 3, 2], most) as u32; + let ind = runner::ChainIndirect { args: &one, stride: 12, commands: 1, count: None, rounds, whole: Some(&whole) }; + let (result, tail) = runner::dispatch_split_indirect(&chain, &ind, &initial, most).unwrap(); + assert_eq!(tail, [1, 0, slabs, 0], "split {threads}, {most} groups, {rounds} rounds"); + assert_eq!(result, expected, "split {threads}, whole form for {most} groups, {rounds} rounds"); + // … and without one the rounds still run: their groups are done, the others not + let ind = runner::ChainIndirect { whole: None, ..ind }; + let (result, _) = runner::dispatch_split_indirect(&chain, &ind, &initial, most).unwrap(); + let done: usize = crate::gpu::recomp::pso::dispatch_slabs([2, 3, 2], most).iter().take(rounds as usize).map(|s| s.1.iter().product::() as usize).sum(); + let changed = result.iter().zip(&initial).filter(|(a, b)| a != b).count(); + assert!(changed > 0 && changed < words && done < 12, "split {threads}, {most} groups, {rounds} rounds: {changed} words changed for {done} groups"); + } println!("CHAIN_BRANCH threads={threads} pieces={} scratch_words_per_group={} checked_words={words} guards=16", chain.pieces.len(), chain.dwords_per_group); } } diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 34b5c65201..92b1b5edaa 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1617,7 +1617,7 @@ pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Re }) } .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false, None).map(|(m, _)| m) + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false, None, None).map(|(m, _)| m) } #[cfg(test)] @@ -1651,9 +1651,85 @@ 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)), None) } +/// A split program's ExecuteIndirect: the title's commands (one Dispatch, `stride` bytes each, as +/// words), their count, the rounds, and the whole form for more slabs than rounds. +#[cfg(test)] +pub(crate) struct ChainIndirect<'a> { + pub args: &'a [u32], + pub stride: u32, + pub commands: u32, + pub count: Option, + pub rounds: u32, + pub whole: Option<&'a [u8]>, +} + +/// `dispatch_split_by` through ExecuteIndirect as the runtime records it (`pso::record_slicer`, +/// the ABI bound again, the whole form on the slicer's arguments, `record_dispatch_chain_indirect`): +/// the memory and the slicer's words after its commands (partial, 0, slabs, 0). +#[cfg(test)] +pub(crate) fn dispatch_split_indirect( + chain: &crate::gpu::dxil::kernel::DispatchChain, ind: &ChainIndirect, mem: &[u32], most: u64, +) -> Result<(Vec, [u32; 4]), String> { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init).as_mut().map_err(|e| e.clone())?; + let dev = gpu.dev.clone(); + let rs = super::pso::dispatch_chain_root_signature(&dev, &[])?; + let make = |dxil: &[u8]| unsafe { + dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }).map_err(e) + }; + let pieces: Vec = chain.pieces.iter().map(|d| make(d)).collect::>()?; + let whole = ind.whole.map(make).transpose()?; + let n = pieces.len() as u32; + let mut words = ind.args.to_vec(); + words.push(ind.count.unwrap_or(0)); + let count_at = ind.args.len() as u64 * 4; + let args = buffer(&dev, words.len() as u64 * 4, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?; + let commands = unsafe { super::pso::chain_commands_buffer(&dev, ind.rounds, n, ind.commands) }.ok_or("chain command buffer")?; + let sig = super::pso::chain_command_signature(&dev, &rs)?; + let one = super::pso::dispatch_command_signature(&dev)?; + let at = super::pso::chain_tail_offset(ind.rounds, n); + unsafe { + let mut p = std::ptr::null_mut(); + args.Map(0, None, Some(&mut p)).map_err(e)?; + std::ptr::copy_nonoverlapping(words.as_ptr(), p as *mut u32, words.len()); + args.Unmap(0, None); + } + let mut record = |list: &ID3D12GraphicsCommandList, scratch: &ID3D12Resource, views: [u64; 3]| unsafe { + let va = args.GetGPUVirtualAddress(); + super::pso::record_slicer(list, va, ind.stride, ind.commands, ind.count.map(|_| va + count_at), ind.rounds, most, n, whole.is_some(), &commands)?; + list.SetComputeRootSignature(&rs); + for (i, v) in views.into_iter().enumerate() { + list.SetComputeRootUnorderedAccessView(i as u32, v); + } + if let Some(whole) = &whole { + list.SetPipelineState(whole); + list.ExecuteIndirect(&one, ind.commands, &commands, at + 16, None::<&ID3D12Resource>, 0); + } + super::pso::record_dispatch_chain_indirect(list, &sig, &commands, ind.rounds, scratch, &pieces); + Ok(()) + }; + let mem = dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pieces[0], &rs, [1, 1, 1], &[], mem, 1, false, + Some((&pieces, chain.dwords_per_group, most)), Some(&mut record)).map(|(m, _)| m)?; + unsafe { + let mut p = std::ptr::null_mut(); + commands.Map(0, None, Some(&mut p)).map_err(e)?; + let tail = std::ptr::read_volatile((p as *const u8).add(at as usize) as *const [u32; 4]); + commands.Unmap(0, None); + Ok((mem, tail)) + } +} + +/// Records a chain's dispatch in `dispatch_with` instead of `record_dispatch_chain`: the list, +/// the scratch (`most` groups) and the addresses of root views 0-2. +type RecordChain<'a> = &'a mut dyn FnMut(&ID3D12GraphicsCommandList, &ID3D12Resource, [u64; 3]) -> Result<(), String>; + /// `dispatch` run `reps` times in one command list (a UAV barrier between them, memory not /// reset), each between two GPU timestamps: GPU milliseconds per dispatch – no pipeline, /// buffer, upload, submission or CPU wait time in them. For benchmarks. @@ -1668,7 +1744,7 @@ pub fn dispatch_timed(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32], }) } .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true, None).map(|(_, t)| t) + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true, None, None).map(|(_, t)| t) } #[cfg(test)] @@ -1709,7 +1785,7 @@ pub(crate) fn profile_buffer_forms( (&pieces[i][0], &rs, Some((pieces[i].as_slice(), words, most))) }; let (out, times) = dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, pso, signature, - groups, sgprs, mem, 12, true, chain)?; + groups, sgprs, mem, 12, true, chain, None)?; if out != expected { return Err(format!("replay readback differs for form {variant}")); } if round >= 3 { samples[variant].extend_from_slice(×[2..]); } } @@ -1730,7 +1806,7 @@ pub fn dispatch_on(dev: &ID3D12Device, pso: &ID3D12PipelineState, rs: &ID3D12Roo unsafe { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; - dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem, 1, false, None).map(|(m, _)| m) + dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem, 1, false, None, None).map(|(m, _)| m) } } @@ -1748,6 +1824,7 @@ fn dispatch_with( reps: usize, timed: bool, chain: Option<(&[ID3D12PipelineState], u32, u64)>, + mut record: Option, ) -> Result<(Vec, Vec), String> { let mut io = sgprs.to_vec(); io.resize(KERNEL_SGPRS, 0); @@ -1803,7 +1880,7 @@ fn dispatch_with( } 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)); + let bytes = if record.is_some() { most * 4 * u64::from(words) } else { 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) }).transpose()?; // `reps` dispatches, each between two timestamps when `timed` @@ -1824,7 +1901,9 @@ 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(record), Some(scratch)) = (record.as_mut(), &scratch) { + record(&list, scratch, [io_buf.GetGPUVirtualAddress(), res_buf.GetGPUVirtualAddress(), mem_buf.GetGPUVirtualAddress()])?; + } else if let (Some((pieces, _, most)), Some(scratch)) = (chain, &scratch) { super::pso::record_dispatch_chain(&list, groups, most, scratch, k > 0, pieces); } else { list.Dispatch(groups[0], groups[1], groups[2]); From 9125edb04538c5beee850d06c3a9fd4866cd35b8 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:34:14 -0500 Subject: [PATCH 03/15] D3D12.X: a chained ExecuteIndirect drops slabs only past 32 before its whole form A chained ExecuteIndirect whose arguments have more slabs than its rounds runs the program's whole form instead, but only when that form is built already. Until then the slabs past the rounds are lost, counted and warned about. Across ten title runs of the earlier version, 158 slabs were lost in six, in 73,714 chained ExecuteIndirects. In each run it was one program with 17 slabs: 15 at its first ExecuteIndirect, whose arguments read 0 when it was recorded and which so got 2 rounds, then 1 at each later one (at most 16 rounds) until its whole form was built. - An ExecuteIndirect of a program none of whose ExecuteIndirects has been read back yet gets the most rounds. After that, the most slabs any of them had (not only those that lost some) size the rounds. This costs the empty rounds of a program's first ExecuteIndirects: one ExecuteIndirect and one UAV barrier per piece and round. The scratch does not grow with the rounds; the command buffer does, by 44 bytes a piece and round. - XCL_SPLIT_INDIRECT_ROUNDS defaults to 32, not 16. Rounds are sized from the slabs read back, so the cap matters only for programs that need more. With both, none of those runs would have lost a slab. - The whole form is asked for at the program's first chained ExecuteIndirect, not after a loss is read back. It is built on an xcl-pso-chain-whole thread, so a huge whole form waits for its turn (driver_compile) as the workers' builds do. Before, it was built on a thread named xcl-chain-whole, which the huge-build gate did not hold (pvfreis, #2404). It is bound only when an ExecuteIndirect has more slabs than its rounds. More than 32 slabs before the whole form is built are still lost, counted and warned about. Waiting for the whole form when the ExecuteIndirect is recorded would make it exact. But the precompile does not build the whole forms of split programs, so that wait is a cold compile on the title's thread: the 16-40 s stalls this chain removes. Co-Authored-By: Claude Opus 5.5 --- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 65 ++++++++++++++++--- 1 file changed, 55 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index d5b272b2e4..e381dd448f 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -65,8 +65,9 @@ struct Chain { build_whole: Mutex<()>, /// its command signature for ExecuteIndirect (`pso::chain_command_signature`) signature: OnceLock, - /// the most slabs one of its ExecuteIndirects had + /// the most slabs one of its ExecuteIndirects had, and whether one was read back yet slabs: std::sync::atomic::AtomicU32, + measured: std::sync::atomic::AtomicBool, /// its whole form was asked for in the background / a lost slab was reported wanted: std::sync::atomic::AtomicBool, warned: std::sync::atomic::AtomicBool, @@ -86,13 +87,19 @@ impl Chain { fn want_whole(self: &Arc) { if !self.wanted.swap(true, Ordering::Relaxed) { let chain = self.clone(); - std::thread::Builder::new().name("xcl-chain-whole".into()).spawn(move || unsafe { + whole_thread().spawn(move || unsafe { if let Err(e) = chain.whole() { crate::xlog_warn!("D3D12.X: whole form of a split program: {e}"); } }).ok(); } } } +/// The thread of `want_whole`: an `xcl-pso*` one, so a huge whole form waits for its turn +/// (`driver_compile`) as the workers' builds do +fn whole_thread() -> std::thread::Builder { + std::thread::Builder::new().name("xcl-pso-chain-whole".into()) +} + static CHAINS: LazyLock>>> = LazyLock::new(Default::default); pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, @@ -117,7 +124,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()), signature: OnceLock::new(), - slabs: Default::default(), wanted: Default::default(), warned: Default::default() }); + slabs: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -175,8 +182,9 @@ impl Recording { if unsafe { i.commands.Map(0, Some(&range), Some(&mut p)) }.is_err() { return; } let [partial, _, slabs, _] = unsafe { std::ptr::read_volatile((p as *const u8).add(i.at as usize) as *const [u32; 4]) }; unsafe { i.commands.Unmap(0, Some(&D3D12_RANGE::default())) }; - if partial == 0 { return; } self.chain.slabs.fetch_max(slabs, Ordering::Relaxed); + self.chain.measured.store(true, Ordering::Relaxed); + if partial == 0 { return; } if i.whole { INDIRECT_WHOLE.fetch_add(1, Ordering::Relaxed); return; @@ -303,17 +311,19 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, Ok(()) } -/// The rounds a chained ExecuteIndirect records at most, `XCL_SPLIT_INDIRECT_ROUNDS` (16): each +/// The rounds a chained ExecuteIndirect records at most, `XCL_SPLIT_INDIRECT_ROUNDS` (32): each /// is one ExecuteIndirect and one barrier per piece, also when the title's arguments leave it empty. fn most_rounds() -> u32 { static B: OnceLock = OnceLock::new(); - *B.get_or_init(|| std::env::var("XCL_SPLIT_INDIRECT_ROUNDS").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(16u32).min(1024)) + *B.get_or_init(|| std::env::var("XCL_SPLIT_INDIRECT_ROUNDS").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(32u32).min(1024)) } /// The rounds for slabs of `most` groups: as many as the arguments there now (`seen`, the GPU's /// last ones) or an earlier ExecuteIndirect of the program (`before`) had, a quarter more, at -/// least two and at most `cap`. -fn indirect_rounds(seen: &[[u32; 3]], most: u64, before: u32, cap: u32) -> u32 { +/// least two and at most `cap`. Before one was read back (`before` None), `cap`: the arguments +/// seen when recording can be 0 while the GPU's are not (a title's first ones had 17 slabs). +fn indirect_rounds(seen: &[[u32; 3]], most: u64, before: Option, cap: u32) -> u32 { + let Some(before) = before else { return cap.max(2) }; let now: u64 = seen.iter().map(|&g| pso::slab_count(g, most)).sum(); let want = now.max(u64::from(before)); (want + want.div_ceil(4)).clamp(2, u64::from(cap.max(2))) as u32 @@ -342,10 +352,16 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(list: &ID3D12GraphicsComma Some(s) => s.clone(), None => { let s = pso::chain_command_signature(dev, &chain.builder.signature)?; chain.signature.get_or_init(|| s).clone() } }; - let rounds = indirect_rounds(seen, most, chain.slabs.load(Ordering::Relaxed), most_rounds()); + let before = chain.measured.load(Ordering::Relaxed).then(|| chain.slabs.load(Ordering::Relaxed)); + let rounds = indirect_rounds(seen, most, before, most_rounds()); let pieces = chain.tail.len() as u32 + 1; let buffer = pso::chain_commands_buffer(dev, rounds, pieces, commands).ok_or("no buffer for the commands of a chained ExecuteIndirect")?; let full = chain.whole.get().cloned().map(|p| pso::dispatch_command_signature(dev).map(|s| (p, s))).transpose()?; + // not built: asked for now, so that it is there before an ExecuteIndirect of the program + // needs more slabs than its rounds (until then those are lost) + if full.is_none() { + chain.want_whole(); + } let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); pso::record_slicer(list, args, stride, commands, count, rounds, most, pieces, full.is_some(), &buffer)?; // the list uses `buffer` from here: the recording keeps it until the allocator is reset, also @@ -421,6 +437,33 @@ mod tests { assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true)); } + #[test] + fn a_programs_first_execute_indirect_gets_the_most_rounds() { + use super::indirect_rounds; + // none read back yet: the arguments seen when recording (0 while a title loads) don't count + assert_eq!(indirect_rounds(&[[0, 0, 0]], 8, None, 32), 32); + assert_eq!(indirect_rounds(&[[2, 3, 2]], 1, None, 32), 32); + assert_eq!(indirect_rounds(&[], 1, None, 1), 2); + // then the slabs seen or read back, a quarter more, 2 to the cap + assert_eq!(indirect_rounds(&[[0, 0, 0]], 8, Some(0), 32), 2); + assert_eq!(indirect_rounds(&[[2, 3, 2]], 1, Some(0), 32), 15); + assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, Some(17), 32), 22); + assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, Some(40), 32), 32); + } + + #[test] + fn the_whole_form_built_in_the_background_waits_for_a_huge_compiles_turn() { + use super::super::{big_compile_turn, driver_compile, huge_pso_bytes, huge_pso_concurrency, BIG_COMPILES, GIANT_COMPILES}; + // every slot taken: a huge compile on `want_whole`'s thread waits for one + let mut held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false)).collect(); + held.push(big_compile_turn(&GIANT_COMPILES, || true, || false)); + let t = super::whole_thread().spawn(|| driver_compile("test", huge_pso_bytes(), true, || 7)).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert!(!t.is_finished(), "a huge compile on the whole form's thread did not wait for a slot"); + drop(held); + assert_eq!(t.join().unwrap(), 7); + } + #[test] fn a_chained_execute_indirect_keeps_its_commands_when_binding_fails() { use super::*; @@ -440,7 +483,7 @@ mod tests { let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs, flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); let pso = first.as_raw() as usize; CHAINS.lock().unwrap().insert(pso, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, whole_code: Vec::new(), whole: OnceLock::new(), - build_whole: Mutex::new(()), signature: OnceLock::new(), slabs: Default::default(), wanted: Default::default(), warned: Default::default() })); + build_whole: Mutex::new(()), signature: OnceLock::new(), slabs: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); @@ -450,6 +493,8 @@ mod tests { let r = execute_indirect(&list, pso, allocator, args.GetGPUVirtualAddress(), 12, 1, None, &[[1, 1, 1]], || Err("unified memory is full".to_string())); assert_eq!(r, Err("unified memory is full".to_string())); + // the program's first ExecuteIndirect asks for its whole form, before any slab is lost + assert!(CHAINS.lock().unwrap()[&pso].wanted.load(Ordering::Relaxed)); // the slicer's dispatch is recorded: its command buffer lives until the allocator is // reset, and the read-back does not take the rounds that were not recorded let kept = RECORDINGS.lock().unwrap().get(&allocator).map(|v| v.iter().filter_map(|r| r.indirect.as_ref().map(|i| i.checked)).collect::>()); From f0cef78a50ea149829a77db3c419c8d855f8443a Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:00:28 -0500 Subject: [PATCH 04/15] D3D12.X: a chained ExecuteIndirect under the title's predication is not read back The slicer's words after the rounds size the next ExecuteIndirects of the program: the most slabs one had, and whether any had been measured at all. Under the title's predication (SetPredicationBufferX) the slicer's Dispatch may be skipped, and its words then stay as the buffer was created, all 0. read_back still took them as a count: the program counted as measured with 0 slabs, so its next ExecuteIndirect whose arguments read 0 on the CPU got 2 rounds instead of the 32 of one never measured. A chained ExecuteIndirect recorded while the title's predication is set is no longer read back, as one whose binding failed. Its slicer still runs the same choice under the predicate. Reported by @thehollowedone (#2404). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 2 +- crates/xcl/src/hle/d3d12x/list_x.rs | 10 ++++++++++ .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 19 +++++++++++++------ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 88dcf50f3a..814f1692fe 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -412,7 +412,7 @@ unsafe fn chained_indirect(this: *mut c_void, list: &ID3D12GraphicsCommandList, let n = if count_buf == 0 { max } else { read(count_buf, count_title, 1).map_or(max, |c| c[0].min(max)) }; let seen: Vec<[u32; 3]> = (0..n.min(64)).filter_map(|k| read(args, args_title + u64::from(k * stride), 3)).map(|v| [v[0], v[1], v[2]]).collect(); super::real::dispatch_chain::execute_indirect(list, pso, with(this, |s| s.allocator), args_va, stride, max, count_va, &seen, - || bind_abi(this, list, pso, false)) + super::list_x::predicated(this), || bind_abi(this, list, pso, false)) } /// The GPU address of a title's buffer `res` at its offset `title` (a buffer in unified memory) or diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..52bc2a8af4 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3167,6 +3167,12 @@ pub(super) fn on_pc_reset(list: *mut c_void) { } } +/// The title's predication (`SetPredicationBufferX`) is set on `list`: what it records now may not run. +pub(super) fn predicated(list: *mut c_void) -> bool { + PREDICATION_USED.load(Ordering::Acquire) + && LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.predication.is_some()) +} + /// Copy 8 predicate bytes from `(uma_buf, off)` into `pb` with exact barrier transitions and /// bind `SetPredication(pb, 0, op)` on `this`. unsafe fn apply_predication_copy(this: *mut c_void, uma_buf: usize, off: u64, pb: usize, op: D3D12_PREDICATION_OP) { @@ -5795,6 +5801,7 @@ mod tests { PredEvent::SetPred(pb_raw, 0, D3D12_PREDICATION_OP_EQUAL_ZERO), ] ); + assert!(predicated(list_ptr)); // Rejections while a predicate is active must neither emit events nor disturb tracked state. for ty in [D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE] { @@ -5867,11 +5874,14 @@ mod tests { ); set_predication_buffer_x(list_ptr, std::ptr::null()); assert_eq!(take_events(), vec![PredEvent::SetPred(0, 0, D3D12_PREDICATION_OP_EQUAL_ZERO)]); + assert!(!predicated(list_ptr)); // (g) on_pc_reset clears predication & pred_in_state so subsequent before_close emits 0 barriers. apply_predication_copy(list_ptr, uma_buf, 0x100, pb_raw, D3D12_PREDICATION_OP_EQUAL_ZERO); take_events(); + assert!(predicated(list_ptr)); on_pc_reset(list_ptr); + assert!(!predicated(list_ptr)); before_close(list_ptr); assert!(take_events().is_empty(), "on_pc_reset must clear pred_in_state before before_close"); } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index e381dd448f..80f929beb2 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -169,7 +169,8 @@ struct Indirect { at: u64, rounds: u32, /// the whole form ran instead (the slicer gave it the arguments); `checked`: the chain was - /// recorded (under the title's predication the slicer may not run: its words stay 0) + /// recorded and the title's predication was not set (it may skip the slicer, whose words are + /// then no count) whole: bool, checked: bool, } @@ -333,11 +334,12 @@ fn indirect_rounds(seen: &[[u32; 3]], most: u64, before: Option, cap: u32) /// bytes: `commands` of them at GPU address `args` (their count at `count`, when given), run as /// the chain. `seen`: the arguments the CPU sees there now. `bind` binds the ABI after the /// slicer. The whole form (built already) runs instead when the arguments have more slabs than -/// the rounds, also under the title's predication (which then holds for the slicer too). +/// the rounds, also under the title's predication (`predicated`, which then holds for the slicer +/// too). /// Ok(false): nothing recorded (no chain, a bundle, no scratch) – the caller runs the whole form. #[allow(clippy::too_many_arguments)] pub(in crate::hle::d3d12x) unsafe fn execute_indirect(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, args: u64, stride: u32, - commands: u32, count: Option, seen: &[[u32; 3]], bind: impl FnOnce() -> Result<(), String>) -> Result { + commands: u32, count: Option, seen: &[[u32; 3]], predicated: bool, bind: impl FnOnce() -> Result<(), String>) -> Result { let chain = CHAINS.lock().unwrap().get(&pso).cloned(); let Some(chain) = chain else { return Ok(false) }; let allocator = if super::super::alloc_pool::enabled() { @@ -378,7 +380,7 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(list: &ID3D12GraphicsComma } pso::record_dispatch_chain_indirect(list, &sig, &buffer, rounds, &scratch.buffer, std::iter::once(&first).chain(&chain.tail)); } - let indirect = Indirect { commands: buffer, at, rounds, whole: full.is_some(), checked: bound.is_ok() }; + let indirect = Indirect { commands: buffer, at, rounds, whole: full.is_some(), checked: bound.is_ok() && !predicated }; RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { scratch, first, chain, indirect: Some(indirect) })); bound?; INDIRECT.fetch_add(1, Ordering::Relaxed); @@ -490,15 +492,20 @@ mod tests { let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); let args = pso::chain_commands_buffer(&dev, 1, 1, 1).unwrap(); - let r = execute_indirect(&list, pso, allocator, args.GetGPUVirtualAddress(), 12, 1, None, &[[1, 1, 1]], + let r = execute_indirect(&list, pso, allocator, args.GetGPUVirtualAddress(), 12, 1, None, &[[1, 1, 1]], false, || Err("unified memory is full".to_string())); assert_eq!(r, Err("unified memory is full".to_string())); // the program's first ExecuteIndirect asks for its whole form, before any slab is lost assert!(CHAINS.lock().unwrap()[&pso].wanted.load(Ordering::Relaxed)); // the slicer's dispatch is recorded: its command buffer lives until the allocator is // reset, and the read-back does not take the rounds that were not recorded + // under the title's predication the slicer may not run, so its words are not read back + // (reported by @thehollowedone, #2404); without it they are + for predicated in [true, false] { + assert_eq!(execute_indirect(&list, pso, allocator, args.GetGPUVirtualAddress(), 12, 1, None, &[[1, 1, 1]], predicated, || Ok(())), Ok(true)); + } let kept = RECORDINGS.lock().unwrap().get(&allocator).map(|v| v.iter().filter_map(|r| r.indirect.as_ref().map(|i| i.checked)).collect::>()); - assert_eq!(kept, Some(vec![false])); + assert_eq!(kept, Some(vec![false, false, true])); list.Close().unwrap(); allocator_reset(allocator); list_reset(raw_list); From 70f687a7ee362313aec3ea16b147d07c37ca2ee6 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:21:04 -0500 Subject: [PATCH 05/15] Tests: the predicated ExecuteIndirect test binds the chain's root signature a_chained_execute_indirect_keeps_its_commands_when_binding_fails records two chained ExecuteIndirects whose binding succeeds, but its bind closure did not set the chain's root signature, as bind_abi does. The pieces' ExecuteIndirects then ran under the slicer's root signature: with the D3D12 debug layer and GPU-based validation, 258 messages (953, 744 and 712). The test still passed; the runtime's path sets the root signature. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 80f929beb2..69e4ca35ec 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -482,7 +482,7 @@ mod tests { let rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); let first: ID3D12PipelineState = dev.CreateComputePipelineState(&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() }).unwrap(); - let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs, flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); let pso = first.as_raw() as usize; CHAINS.lock().unwrap().insert(pso, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, whole_code: Vec::new(), whole: OnceLock::new(), build_whole: Mutex::new(()), signature: OnceLock::new(), slabs: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() })); @@ -501,8 +501,13 @@ mod tests { // reset, and the read-back does not take the rounds that were not recorded // under the title's predication the slicer may not run, so its words are not read back // (reported by @thehollowedone, #2404); without it they are + // (`bind` sets the chain's root signature, as `bind_abi` does) for predicated in [true, false] { - assert_eq!(execute_indirect(&list, pso, allocator, args.GetGPUVirtualAddress(), 12, 1, None, &[[1, 1, 1]], predicated, || Ok(())), Ok(true)); + let bind = || { + list.SetComputeRootSignature(&rs); + Ok(()) + }; + assert_eq!(execute_indirect(&list, pso, allocator, args.GetGPUVirtualAddress(), 12, 1, None, &[[1, 1, 1]], predicated, bind), Ok(true)); } let kept = RECORDINGS.lock().unwrap().get(&allocator).map(|v| v.iter().filter_map(|r| r.indirect.as_ref().map(|i| i.checked)).collect::>()); assert_eq!(kept, Some(vec![false, false, true])); From 3ca907170fd97a24ad26a583bbfab51ce19b885f Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:25:15 -0500 Subject: [PATCH 06/15] D3D12.X: once a split program's whole form is built, its last ExecuteIndirect sizes the rounds A chained ExecuteIndirect records rounds x pieces ExecuteIndirects, each after a UAV barrier, also when the slicer leaves them empty. On an RTX 5070 Ti (NVIDIA 610.74) such a step takes 14.4 us of GPU time with the chain's command signature (eight root constants and a Dispatch): 144 us a round for 10 pieces, 2.3 ms for 16 rounds, 4.6 ms for 32, empty or not. Without the barrier it is 0.17 us, and with a Dispatch-only signature 0.41 us; a count buffer of 0 makes it 11.5 us. The rounds came from the most slabs any ExecuteIndirect of the program had, so one large one kept every later one at that size. Until the whole form is built that is needed, since the slabs past the rounds are lost. Once it is built, an ExecuteIndirect with more slabs than its rounds runs the whole form, so the rounds now follow the last one read back (and the arguments seen when recording), not the most. Co-Authored-By: Claude Opus 5.5 --- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 34 ++++++++++++++++--- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 69e4ca35ec..4914980bab 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -65,8 +65,10 @@ struct Chain { build_whole: Mutex<()>, /// its command signature for ExecuteIndirect (`pso::chain_command_signature`) signature: OnceLock, - /// the most slabs one of its ExecuteIndirects had, and whether one was read back yet + /// the most slabs one of its ExecuteIndirects had, the last one read back, and whether one + /// was read back yet slabs: std::sync::atomic::AtomicU32, + last: std::sync::atomic::AtomicU32, measured: std::sync::atomic::AtomicBool, /// its whole form was asked for in the background / a lost slab was reported wanted: std::sync::atomic::AtomicBool, @@ -124,7 +126,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()), signature: OnceLock::new(), - slabs: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); + slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -184,6 +186,7 @@ impl Recording { let [partial, _, slabs, _] = unsafe { std::ptr::read_volatile((p as *const u8).add(i.at as usize) as *const [u32; 4]) }; unsafe { i.commands.Unmap(0, Some(&D3D12_RANGE::default())) }; self.chain.slabs.fetch_max(slabs, Ordering::Relaxed); + self.chain.last.store(slabs, Ordering::Relaxed); self.chain.measured.store(true, Ordering::Relaxed); if partial == 0 { return; } if i.whole { @@ -330,6 +333,14 @@ fn indirect_rounds(seen: &[[u32; 3]], most: u64, before: Option, cap: u32) (want + want.div_ceil(4)).clamp(2, u64::from(cap.max(2))) as u32 } +/// The slabs of an earlier ExecuteIndirect of the program for `indirect_rounds` (None: none was +/// read back yet). Until its whole form is built, the most any had: slabs past the rounds are +/// lost. Then the last one's, as more run the whole form: every round costs its pieces' +/// ExecuteIndirects, also when empty (each ~14 us of GPU after its barrier on an RTX 5070 Ti, #2404). +fn slabs_before(measured: bool, whole: bool, most: u32, last: u32) -> Option { + measured.then_some(if whole { last } else { most }) +} + /// An ExecuteIndirect of split program `pso` whose command signature is one Dispatch of `stride` /// bytes: `commands` of them at GPU address `args` (their count at `count`, when given), run as /// the chain. `seen`: the arguments the CPU sees there now. `bind` binds the ABI after the @@ -354,11 +365,11 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(list: &ID3D12GraphicsComma Some(s) => s.clone(), None => { let s = pso::chain_command_signature(dev, &chain.builder.signature)?; chain.signature.get_or_init(|| s).clone() } }; - let before = chain.measured.load(Ordering::Relaxed).then(|| chain.slabs.load(Ordering::Relaxed)); + let full = chain.whole.get().cloned().map(|p| pso::dispatch_command_signature(dev).map(|s| (p, s))).transpose()?; + let before = slabs_before(chain.measured.load(Ordering::Relaxed), full.is_some(), chain.slabs.load(Ordering::Relaxed), chain.last.load(Ordering::Relaxed)); let rounds = indirect_rounds(seen, most, before, most_rounds()); let pieces = chain.tail.len() as u32 + 1; let buffer = pso::chain_commands_buffer(dev, rounds, pieces, commands).ok_or("no buffer for the commands of a chained ExecuteIndirect")?; - let full = chain.whole.get().cloned().map(|p| pso::dispatch_command_signature(dev).map(|s| (p, s))).transpose()?; // not built: asked for now, so that it is there before an ExecuteIndirect of the program // needs more slabs than its rounds (until then those are lost) if full.is_none() { @@ -453,6 +464,19 @@ mod tests { assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, Some(40), 32), 32); } + #[test] + fn once_the_whole_form_is_built_the_last_execute_indirect_sizes_the_rounds() { + use super::{indirect_rounds, slabs_before}; + assert_eq!(slabs_before(false, true, 17, 1), None); + // not built: the most slabs any had, so that none are lost + assert_eq!(slabs_before(true, false, 17, 1), Some(17)); + assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, slabs_before(true, false, 17, 1), 32), 22); + // built: the last one's, an overflow runs the whole form + assert_eq!(slabs_before(true, true, 17, 1), Some(1)); + assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, slabs_before(true, true, 17, 1), 32), 2); + assert_eq!(indirect_rounds(&[[3, 1, 1]], 1, slabs_before(true, true, 17, 1), 32), 4); + } + #[test] fn the_whole_form_built_in_the_background_waits_for_a_huge_compiles_turn() { use super::super::{big_compile_turn, driver_compile, huge_pso_bytes, huge_pso_concurrency, BIG_COMPILES, GIANT_COMPILES}; @@ -485,7 +509,7 @@ mod tests { let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); let pso = first.as_raw() as usize; CHAINS.lock().unwrap().insert(pso, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, whole_code: Vec::new(), whole: OnceLock::new(), - build_whole: Mutex::new(()), signature: OnceLock::new(), slabs: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() })); + build_whole: Mutex::new(()), signature: OnceLock::new(), slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); From 0755bd71b4fb038067c0358bc9ad9f712f7281ea Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:04:42 -0500 Subject: [PATCH 07/15] Tests: the chained ExecuteIndirect device test binds descriptor heaps The chain's root signature indexes the descriptor heaps directly, so setting it on a list without heaps is a debug-layer error (1419, four of them under GPU-based validation at 809da30). A title's list has its heaps set when XCL binds the ABI; the test's `bind` now sets two shader-visible heaps before the root signature, as that list has. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 4914980bab..ed70fbc3ba 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -525,9 +525,14 @@ mod tests { // reset, and the read-back does not take the rounds that were not recorded // under the title's predication the slicer may not run, so its words are not read back // (reported by @thehollowedone, #2404); without it they are - // (`bind` sets the chain's root signature, as `bind_abi` does) + // (`bind` sets the chain's root signature, as `bind_abi` does, on a list with descriptor + // heaps, as a title's list has: the signature indexes them directly) + let heap = |ty| -> ID3D12DescriptorHeap { dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: ty, NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }).unwrap() }; + let heaps = [Some(heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)), Some(heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER))]; for predicated in [true, false] { let bind = || { + list.SetDescriptorHeaps(&heaps); list.SetComputeRootSignature(&rs); Ok(()) }; From 50205bc47ee7064cd68363cdfc426ad495162f88 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:53:23 -0500 Subject: [PATCH 08/15] D3D12.X: a chained ExecuteIndirect takes on a list the pool does not track With the allocator pool on, `execute_indirect` kept the recording with the PC allocator the list records on (`alloc_pool::recording_backing`). For a list the pool does not track it got 0, so it returned Ok(false) and the ExecuteIndirect ran its whole form. XCL makes such lists itself: a mid-list split's next list is created on `alloc_pool::current(alloc)` with no `created_on`. Under Wine + vkd3d-proton on an RTX 4060 Ti, this branch chained 2 ExecuteIndirects and ran 26-30 whole in three runs of a title, and the title presented nothing after its loading burst. In a fourth run with a log line, all 32 that declined did so for this reason. Such a list is now taken on by the pool, on the PC allocator the title's allocator stands for, which is the one the list was made on (`alloc_pool::recording_backing_or_take_on`), and the recording is kept there. #2333 keeps these recordings with the title's allocator instead (its `resolve_allocator`). The pool then knows nothing of the list, so it can take that allocator for free and release the recordings (scratch and commands buffer) while the list still records or runs on the GPU. Taken on, the list keeps its backing busy until it is reset elsewhere or released, and its submits mark the backing like any other list's. The title's allocator also gets the list's type, so that a Reset while the list holds its backing swaps it like the title's own lists. Reported by @Royalflamejlh (#2404). With #2333 merged under this branch and its fallback in `execute_indirect`, every ExecuteIndirect chained in four runs (22 to 70,341 of them, 0 whole). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 54 +++++++++++++++++++ .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 10 ++-- 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..6117bc465c 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -116,6 +116,28 @@ pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) hr } +/// The PC allocator `list` records on, also for a list this module has not seen: XCL's own (a +/// mid-list split's next list, made on `current(alloc)`) records on the PC allocator the title's +/// `alloc` stands for. Such a list is taken on there, so that its submits mark that allocator and +/// it stays busy until the list is reset elsewhere or released. Off: `alloc`. 0: none. +pub(super) fn recording_backing_or_take_on(list: usize, alloc: usize, ty: i32) -> usize { + if !enabled() { + return alloc; + } + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + if let Some(&b) = s.of_list.get(&list) { + return b; + } + if alloc == 0 { + return 0; + } + let b = s.cur.get(&alloc).copied().unwrap_or(alloc); + s.types.entry(alloc).or_insert(ty); + move_list(s, list, b); + b +} + #[cfg(test)] pub(super) use recording_backing as recording_backing_for_test; @@ -370,6 +392,38 @@ mod tests { assert_eq!((s.made, s.swaps), (0, 1)); } + /// A list the pool has not seen (XCL's own, made on the PC allocator the title's allocator + /// stands for) is taken on there by a chained ExecuteIndirect: that allocator is busy with it. + #[test] + fn a_list_the_pool_has_not_seen_is_taken_on_with_the_pc_allocator_it_records_on() { + let mut ids = Box::new([0u8; 4]); + let base = ids.as_mut_ptr() as usize; + let (title, backing, list, other) = (base, base + 1, base + 2, base + 3); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT.0; + STATE.lock().unwrap().get_or_insert_with(State::default).cur.insert(title, backing); + let taken = recording_backing_or_take_on(list, title, ty); + let again = recording_backing_or_take_on(list, other, ty); + let (busy, typed) = { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + (s.backings.get(&backing).is_some_and(|b| b.users.contains(&list) && !unsafe { b.free() }), s.types.get(&title) == Some(&ty)) + }; + let none = recording_backing_or_take_on(other, 0, ty); + forget_list(list); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.cur.remove(&title); + s.types.remove(&title); + s.backings.remove(&backing); + } + assert_eq!(taken, backing, "filed with the PC allocator the list records on, not the title's"); + assert_eq!(again, backing, "a list taken on keeps its backing"); + assert!(busy, "the backing is busy while the list records on it"); + assert!(typed, "the title's allocator can be swapped while the list holds its backing"); + assert_eq!(none, 0); + } + /// Final-release cleanup drops only the recording's hold: another live list and a pending /// GPU fence each still prevent reuse, then completion makes the backing reusable. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index ed70fbc3ba..1eb3b07666 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -353,10 +353,12 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(list: &ID3D12GraphicsComma commands: u32, count: Option, seen: &[[u32; 3]], predicated: bool, bind: impl FnOnce() -> Result<(), String>) -> Result { let chain = CHAINS.lock().unwrap().get(&pso).cloned(); let Some(chain) = chain else { 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) - } else { allocator }; - if allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { return Ok(false); } + if list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { return Ok(false); } + // kept with the PC allocator the list records on, also for a list the pool has not seen (#2333 + // keeps such a list's with the title's allocator: the pool knew nothing of the list, and could + // take that allocator for free while the list still recorded or ran on the GPU) + let allocator = super::super::alloc_pool::recording_backing_or_take_on(list.as_raw() as usize, allocator, list.GetType().0); + if allocator == 0 { return Ok(false); } let dev = &chain.builder.device; let group = u64::from(chain.words) * 4; let Some((scratch, _)) = scratch_for(dev, list.as_raw() as usize, allocator, scratch_budget(), group) else { return Ok(false) }; From 073f8ea7e61b1f898c91696c83c5374bf8490d7f Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:36:11 -0500 Subject: [PATCH 09/15] D3D12.X: a list made or released at an address drops the chain scratch The chains of one recording share one scratch, which `dispatch_chain` finds by the list's address (`SHARED`). Only a list's Reset forgot it. Addresses are reused (#2588). A list created at the address of a released one, on the same allocator while the old recordings were still held, found the old list's scratch and shared it with work the GPU may still be running. A chained ExecuteIndirect takes its scratch the same way. `list_x` now forgets the entry when a list is created and when it is released, with a unit test that fails without the change. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/list_x.rs | 17 +++++++++++++++++ .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 13 ++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 52bc2a8af4..08b8cc8104 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -809,6 +809,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); + real::dispatch_chain::list_reset(key); let old = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -847,6 +848,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); + real::dispatch_chain::list_reset(list); super::title_textures::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { @@ -4600,6 +4602,21 @@ mod tests { use super::*; use std::sync::Arc; + /// A list made at the address of a released one does not share the split programs' scratch + /// of the old one's recordings, which the GPU may still run (#2588: addresses are reused) + #[test] + fn a_list_at_a_released_lists_address_starts_without_its_chain_scratch() { + let list = 0x7a51_0000usize; + real::dispatch_chain::note_shared_for_test(list, 0x333); + on_release(list); + assert!(!real::dispatch_chain::shares_scratch_for_test(list), "kept after the release"); + // a release not seen: the create clears it + real::dispatch_chain::note_shared_for_test(list, 0x333); + unsafe { on_create(list as *mut c_void, 0x333, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + assert!(!real::dispatch_chain::shares_scratch_for_test(list), "kept by a list created at the address"); + on_release(list); + } + /// An internal wait shows in the watchdog's summary while its fence is short of the value, /// and is gone from it once the fence gets there. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 1eb3b07666..0b9e02b0f6 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -213,7 +213,8 @@ static RECORDINGS: LazyLock>>>> = LazyLo /// after another, with a barrier between them (the recordings keep it alive) static SHARED: LazyLock)>>> = LazyLock::new(Default::default); -/// `list` begins another recording, which the GPU may run beside the last one. +/// `list` begins another recording, which the GPU may run beside the last one: a Reset, or a +/// list created at the address of a released one (#2588). Also when it is released. pub(in crate::hle::d3d12x) fn list_reset(list: usize) { SHARED.lock().unwrap().remove(&list); } @@ -226,6 +227,16 @@ pub(in crate::hle::d3d12x) fn list_follows(from: usize, to: usize) { } } +#[cfg(test)] +pub(in crate::hle::d3d12x) fn note_shared_for_test(list: usize, allocator: usize) { + SHARED.lock().unwrap().insert(list, (allocator, std::sync::Weak::new())); +} + +#[cfg(test)] +pub(in crate::hle::d3d12x) fn shares_scratch_for_test(list: usize) -> bool { + SHARED.lock().unwrap().contains_key(&list) +} + /// The scratch of all recordings alive together, `XCL_SPLIT_SCRATCH_TOTAL_MB` (384). A recording /// keeps its scratch until its allocator is reset, and a title that records ahead of the GPU has /// many: with a bound on one dispatch alone a retail title's world took 1.2 GB and went on growing. From 551a75e518c95078c31c051511a121f2989cc9cb Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:59:50 -0500 Subject: [PATCH 10/15] D3D12.X: a PC allocator put aside lets go of its chain recordings once free A chained ExecuteIndirect keeps its slicer scratch and commands buffer with the recording of its PC allocator until that allocator is reset (dispatch_chain::allocator_reset, from reset_pc_allocator) or released. When the title resets an allocator whose recording is still held or on the GPU, alloc_pool puts the PC allocator aside and gives the title another. The one put aside is reset only when the same title allocator is reset again and reuses it, which may never happen. Until then its recordings, and the memory they keep, stay. dhillonjagdeep650-boop found it on an RTX 3080 Ti (#2404): 1,887 recordings under 48 allocators at 110 s, local and non-local memory growing about 150 MB/s, then a device removal at 110.8 s. The allocator log said 119 made and 119 put aside. Every title Reset now also releases the recordings of each PC allocator put aside that nothing holds any more: no list records on it and its submits are done. This happens outside the pool's lock. allocator_reset of an allocator without recordings does nothing, and the allocator is reset as before when it is reused. This relies on every chained recording being filed with the PC allocator its list records on, and on that list being known to the pool (an earlier commit here takes on the lists it had not seen). A recording filed with a title's allocator, as #2333's lines file one, would go when that allocator is free, while its list still records or runs on the GPU elsewhere. The first test fails without the sweep: the free allocator put aside still holds its recordings after another title allocator's Reset. Two more show that a taken-on list's recording stays while the list records on its allocator put aside and while its submit runs, and goes after both; and that a free title allocator put aside does not take a live list's recording with it. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 155 +++++++++++++++++- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 10 ++ 2 files changed, 164 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 6117bc465c..f13d5b2096 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -289,7 +289,22 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { } let mut g = STATE.lock().unwrap(); let s = g.get_or_insert_with(State::default); - title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)) + let hr = title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)); + let free = free_aside(s); + drop(g); + for b in free { + super::real::dispatch_chain::allocator_reset(b); + } + hr +} + +/// The PC allocators put aside that nothing holds any more: their lists have moved on and the GPU +/// is done with what they submitted. Their own Reset waits until the title's allocator they stood +/// for takes one of them again, which may not come, so the scratch and commands that chained +/// ExecuteIndirects kept with their recordings (`dispatch_chain::allocator_reset`) go now. Without +/// this a title held 1,887 recordings under 48 allocators 110 s in, and memory grew until removal. +unsafe fn free_aside(s: &State) -> Vec { + s.aside.values().flatten().copied().filter(|b| s.backings.get(b).is_none_or(|x| x.free())).collect() } /// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. @@ -424,6 +439,144 @@ mod tests { assert_eq!(none, 0); } + /// A PC allocator put aside lets go of what chains kept with its recordings once nothing holds + /// it, at the next title Reset of any allocator; one a list still records on keeps them. + #[test] + fn a_free_allocator_put_aside_lets_go_of_its_chain_recordings_at_the_next_title_reset() { + use super::super::real::dispatch_chain::{holds_recordings_for_test as holds, note_recordings_for_test as note}; + let mut ids = Box::new([0u8; 5]); + let base = ids.as_mut_ptr() as usize; + let (title, aside, busy, list, other) = (base, base + 1, base + 2, base + 3, base + 4); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.aside.insert(title, vec![aside, busy]); + s.backings.insert(aside, Backing::default()); + s.backings.entry(busy).or_default().users.insert(list); + } + note(aside); + note(busy); + // another title allocator that holds nothing: reset as it is + let hr = unsafe { title_reset(other as *mut c_void) }; + let (freed, kept) = (!holds(aside), holds(busy)); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.aside.remove(&title); + s.backings.remove(&aside); + s.backings.remove(&busy); + } + super::super::real::dispatch_chain::allocator_reset(aside); + super::super::real::dispatch_chain::allocator_reset(busy); + assert_eq!(hr, None); + assert!(freed, "a free allocator put aside still held its chain recordings"); + assert!(kept, "an allocator a list still records on lost its chain recordings"); + } + + /// A list the pool had not seen, taken on by a chained ExecuteIndirect, and its allocator put + /// aside: the recording stays while the list records there, then while its submit runs, and + /// goes once the list is reset elsewhere and that submit is done. + #[test] + fn a_taken_on_lists_chain_recording_stays_until_it_moves_on_and_its_submit_is_done() { + use super::super::real::dispatch_chain::{holds_recordings_for_test as holds, note_recordings_for_test as note}; + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct Fence { + vtable: *const usize, + value: Cell, + } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + (*this.cast::()).value.get() + } + unsafe extern "system" fn release(_: *mut c_void) -> u32 { + 0 + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::(); + let mut vtable = [unexpected_call as usize; size_of::() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut fence = Fence { vtable: vtable.as_ptr(), value: Cell::new(0) }; + let mut ids = Box::new([0u8; 6]); + let base = ids.as_mut_ptr() as usize; + let (title, backing, next, list, elsewhere, trigger) = (base, base + 1, base + 2, base + 3, base + 4, base + 5); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT.0; + STATE.lock().unwrap().get_or_insert_with(State::default).cur.insert(title, backing); + let taken = recording_backing_or_take_on(list, title, ty); + note(taken); + { + // its submit, and the title's Reset that put its allocator aside + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let f = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut fence).cast()) }; + s.backings.get_mut(&backing).unwrap().marks.insert(1, (f, 7)); + s.cur.insert(title, next); + s.aside.insert(title, vec![backing]); + } + let sweep = || unsafe { title_reset(trigger as *mut c_void) }; + sweep(); + let while_recording = holds(backing); + assert_eq!(reset_list(list, elsewhere, ty, |_| 0), 0); + sweep(); + let while_on_gpu = holds(backing); + fence.value.set(7); + sweep(); + let after = holds(backing); + forget_list(list); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.cur.remove(&title); + s.aside.remove(&title); + s.types.remove(&title); + s.types.remove(&elsewhere); + s.backings.remove(&backing); + s.backings.remove(&elsewhere); + } + super::super::real::dispatch_chain::allocator_reset(backing); + assert_eq!(taken, backing); + assert!(while_recording, "the recording went while the list still recorded on its allocator"); + assert!(while_on_gpu, "the recording went while its submit was on the GPU"); + assert!(!after, "the recording stayed after the list moved on and its submit was done"); + } + + /// The case #2333's lines leave open: a list the pool had not seen, whose title's allocator + /// was put aside and is free. Its recording is not with that allocator, so it does not go with it. + #[test] + fn a_free_title_allocator_put_aside_does_not_take_a_live_lists_chain_recording_with_it() { + use super::super::real::dispatch_chain::{holds_recordings_for_test as holds, note_recordings_for_test as note}; + let mut ids = Box::new([0u8; 4]); + let base = ids.as_mut_ptr() as usize; + let (title, backing, list, trigger) = (base, base + 1, base + 2, base + 3); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT.0; + { + // the title's Reset put its own allocator aside (free now) for `backing` + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.cur.insert(title, backing); + s.aside.insert(title, vec![title]); + } + let taken = recording_backing_or_take_on(list, title, ty); + note(taken); + unsafe { title_reset(trigger as *mut c_void) }; + let kept = holds(taken); + forget_list(list); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.cur.remove(&title); + s.aside.remove(&title); + s.types.remove(&title); + s.backings.remove(&backing); + } + super::super::real::dispatch_chain::allocator_reset(taken); + assert_ne!(taken, title, "filed with the title's allocator, which the sweep frees"); + assert!(kept, "a live list's chain recording went with a free allocator put aside"); + } + /// Final-release cleanup drops only the recording's hold: another live list and a pending /// GPU fence each still prevent reuse, then completion makes the backing reusable. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 0b9e02b0f6..a0fba68195 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -280,6 +280,16 @@ pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) { drop(recordings); } +#[cfg(test)] +pub(in crate::hle::d3d12x) fn note_recordings_for_test(allocator: usize) { + RECORDINGS.lock().unwrap().entry(allocator).or_default(); +} + +#[cfg(test)] +pub(in crate::hle::d3d12x) fn holds_recordings_for_test(allocator: usize) -> bool { + RECORDINGS.lock().unwrap().contains_key(&allocator) +} + unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option { let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, From 97a70a73c96ee39cadffe1baafbc6725091277f6 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:46:23 -0500 Subject: [PATCH 11/15] D3D12.X: a title thread does not wait behind a background whole build's turn `want_whole` builds a split program's whole form on `xcl-pso-chain-whole`, an `xcl-pso*` thread, so a huge one waits in `big_compile_turn` for a background slot and 3 GB of free commit, with no timeout. It waits holding `Chain::build_whole`, and nothing on that thread says a title thread waits for it (`pso_async::build_is_wanted` reads only a worker's build). So a title thread that needs the same whole form meanwhile (`bind.rs` for an ExecuteIndirect it cannot chain, `dispatch` without scratch) blocked on the mutex until the background turn came. It got neither the wanted cap nor the commit skip of a build the title waits for, where before `want_whole` it compiled at once (found by @pvfreis in the review of #2404). A title thread now counts itself in `Chain::waiting` while it waits for the whole form, and `want_whole`'s build runs in `pso_async::build_waited_on`, so `build_is_wanted` is true on that thread while one does. The background build then goes as one the title waits for, and the title thread gets the form when it is built. The test fills the background slots, starts the build and asks for the form on another thread: without the count it waited until the slots were freed ("the title thread waited for the background build's turn"). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/pso_async.rs | 15 ++++- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 62 ++++++++++++++++++- 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..bc73d407c0 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -49,12 +49,25 @@ struct Demand { thread_local! { /// what this worker is building static BUILDING: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + /// a build on this thread that is not a worker's: whether one of the title's threads waits for it (`build_waited_on`) + static WAITED: std::cell::RefCell bool>>> = const { std::cell::RefCell::new(None) }; } /// This thread is a worker and one of the title's threads waits for what it is building: the -/// build must not stand back for the title's sake (`real::big_compile_turn`). +/// build must not stand back for the title's sake (`real::big_compile_turn`). The same for a +/// build in `build_waited_on` once its `waited` says so. pub(super) fn build_is_wanted() -> bool { BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.demand.lock().unwrap().wanted)) + || WAITED.with(|w| w.borrow().as_ref().is_some_and(|f| f())) +} + +/// `build` on a thread that is not a worker, for a pipeline the title may come to wait for: while +/// `waited` says one of the title's threads does, `build_is_wanted` says so on this thread. +pub(super) fn build_waited_on(waited: impl Fn() -> bool + 'static, build: impl FnOnce() -> R) -> R { + WAITED.with(|w| *w.borrow_mut() = Some(Box::new(waited))); + let r = build(); + WAITED.with(|w| *w.borrow_mut() = None); + r } /// Whether one of the title's threads waits for what this thread is doing, to be asked later and diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index a0fba68195..33dfea45a8 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -63,6 +63,8 @@ struct Chain { whole_code: Vec, whole: OnceLock, build_whole: Mutex<()>, + /// threads other than `want_whole`'s waiting for the whole form + waiting: std::sync::atomic::AtomicUsize, /// its command signature for ExecuteIndirect (`pso::chain_command_signature`) signature: OnceLock, /// the most slabs one of its ExecuteIndirects had, the last one read back, and whether one @@ -78,6 +80,15 @@ struct Chain { impl Chain { unsafe fn whole(&self) -> Result { if let Some(p) = self.whole.get() { return Ok(p.clone()); } + // `want_whole`'s build may hold `build_whole` while it waits for its turn + // (`big_compile_turn`): while this thread waits, that build is one the title waits for + self.waiting.fetch_add(1, Ordering::AcqRel); + let built = self.build_whole_form(); + self.waiting.fetch_sub(1, Ordering::AcqRel); + built + } + + unsafe fn build_whole_form(&self) -> Result { let _guard = self.build_whole.lock().unwrap(); if let Some(p) = self.whole.get() { return Ok(p.clone()); } let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; @@ -90,7 +101,11 @@ impl Chain { if !self.wanted.swap(true, Ordering::Relaxed) { let chain = self.clone(); whole_thread().spawn(move || unsafe { - if let Err(e) = chain.whole() { crate::xlog_warn!("D3D12.X: whole form of a split program: {e}"); } + let waited = chain.clone(); + let built = super::super::pso_async::build_waited_on(move || waited.waiting.load(Ordering::Acquire) > 0, || { + if chain.whole.get().is_some() { Ok(()) } else { chain.build_whole_form().map(drop) } + }); + if let Err(e) = built { crate::xlog_warn!("D3D12.X: whole form of a split program: {e}"); } }).ok(); } } @@ -125,7 +140,7 @@ 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: OnceLock::new(), build_whole: Mutex::new(()), signature: OnceLock::new(), + whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()), waiting: Default::default(), signature: OnceLock::new(), slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); @@ -532,7 +547,7 @@ mod tests { let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); let pso = first.as_raw() as usize; CHAINS.lock().unwrap().insert(pso, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, whole_code: Vec::new(), whole: OnceLock::new(), - build_whole: Mutex::new(()), signature: OnceLock::new(), slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() })); + build_whole: Mutex::new(()), waiting: Default::default(), signature: OnceLock::new(), slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); @@ -570,4 +585,45 @@ mod tests { super::super::super::alloc_pool::forget_list(raw_list); } } + + /// A title thread that needs the whole form while `want_whole`'s build of it waits for its + /// turn (`big_compile_turn`, every background slot taken) does not wait behind that turn: the + /// build is then one the title waits for, with the wanted cap and no commit wait (#2404) + #[test] + fn a_title_thread_does_not_wait_behind_a_background_whole_build_waiting_for_its_turn() { + use super::*; + use std::time::{Duration, Instant}; + unsafe extern "system" fn refused(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } + unsafe { + let mut dev: Option = 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 rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let builder = Arc::new(PipelineBuilder { device: dev, create: refused, signature: rs, flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); + // a huge whole form no cache has: its build on `want_whole`'s thread is gated + let mut code = vec![0u8; huge_pso_bytes()]; + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + code[..16].copy_from_slice(&nonce.to_le_bytes()); + let chain = Arc::new(Chain { builder, tail: Vec::new(), words: 4, whole_code: code, whole: OnceLock::new(), + build_whole: Mutex::new(()), waiting: Default::default(), signature: OnceLock::new(), slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); + let held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false)).collect(); + chain.want_whole(); + let started = Instant::now(); + while chain.build_whole.try_lock().is_ok() { + assert!(started.elapsed() < Duration::from_secs(10), "the background build did not start"); + std::thread::sleep(Duration::from_millis(10)); + } + let (done, waited) = std::sync::mpsc::channel(); + let title = chain.clone(); + std::thread::spawn(move || { + let _ = title.whole(); + let _ = done.send(()); + }); + let waited = waited.recv_timeout(Duration::from_secs(5)); + drop(held); + assert!(waited.is_ok(), "the title thread waited for the background build's turn"); + } + } } From 99ca688d67206059eea82ee1bb63a57d2aac0e0a Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:06:25 -0500 Subject: [PATCH 12/15] D3D12.X: the split-program counter line says what holds chain recordings A chained dispatch or ExecuteIndirect keeps its scratch and commands until the PC allocator it recorded on is reset or, put aside, is free. Two runs on other machines held thousands of them (7,410 under 115 allocators at 270 s, 2,297 of them under ones put aside) while memory grew, and neither log says why the rest were not let go. Every 10 s, with the counter line, a second line gives the recordings held and made, and splits the held ones by their allocator: put aside with a list still recording on it, with submits on the GPU, or free; in use for a title's allocator, busy or free; or one the pool does not know. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 57 +++++++++++++++++++ .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 14 +++++ 2 files changed, 71 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index f13d5b2096..d08a3ca290 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -249,6 +249,34 @@ pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { busy } +/// Of chain recordings held under PC allocators (`(allocator, recordings)`), how many are under +/// one put aside that a list still records on, that the GPU has not finished, that is free; under +/// one a title's allocator stands for now that is busy, that is free; under one the pool does not +/// know (the split-program counter line, `dispatch_chain::log_counts`). +pub(super) fn holds(keys: &[(usize, usize)]) -> [usize; 6] { + let mut k = [0; 6]; + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { + k[5] = keys.iter().map(|&(_, n)| n).sum(); + return k; + }; + let aside: HashSet = s.aside.values().flatten().copied().collect(); + let in_use: HashSet = s.cur.values().copied().chain(s.types.keys().filter(|a| !s.cur.contains_key(a)).copied()).collect(); + for &(b, n) in keys { + let backing = s.backings.get(&b); + let free = backing.is_none_or(|x| unsafe { x.free() }); + let i = if aside.contains(&b) { + if backing.is_some_and(|x| !x.users.is_empty()) { 0 } else if !free { 1 } else { 2 } + } else if in_use.contains(&b) { + if free { 4 } else { 3 } + } else { + 5 + }; + k[i] += n; + } + k +} + /// The title's allocator `alloc` is gone (its last Release): nothing of it stays here – a later /// allocator may get its address, and must not go on with this one's PC allocators. The ones /// made here go with it (those lists still record on are left alone: not freed, not tracked). @@ -543,6 +571,35 @@ mod tests { assert!(!after, "the recording stayed after the list moved on and its submit was done"); } + /// The counter line's split of the chain recordings held: by what holds the PC allocator + /// they are under. + #[test] + fn the_recordings_held_are_split_by_what_holds_their_allocator() { + let mut ids = Box::new([0u8; 8]); + let base = ids.as_mut_ptr() as usize; + let (title, used, free, busy, idle, other, list, list2) = (base, base + 1, base + 2, base + 3, base + 4, base + 5, base + 6, base + 7); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.aside.insert(title, vec![used, free]); + s.cur.insert(title, busy); + s.types.insert(idle, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.backings.entry(used).or_default().users.insert(list); + s.backings.entry(busy).or_default().users.insert(list2); + } + let k = holds(&[(used, 1), (free, 2), (busy, 3), (idle, 4), (other, 5)]); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.aside.remove(&title); + s.cur.remove(&title); + s.types.remove(&idle); + s.backings.remove(&used); + s.backings.remove(&busy); + } + assert_eq!(k, [1, 0, 2, 3, 4, 5]); + } + /// The case #2333's lines leave open: a list the pool had not seen, whose title's allocator /// was put aside and is free. Its recording is not with that allocator, so it does not go with it. #[test] diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 33dfea45a8..cfd8805cfa 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -20,6 +20,8 @@ static INDIRECT_WHOLE: AtomicU64 = AtomicU64::new(0); static INDIRECT_LOST: AtomicU64 = AtomicU64::new(0); /// ExecuteIndirects that ran the whole form (not chainable) static WHOLE_INDIRECT: AtomicU64 = AtomicU64::new(0); +/// recordings made (`RECORDINGS`) +static RECORDED: AtomicU64 = AtomicU64::new(0); pub(crate) fn log_counts() { let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; @@ -27,6 +29,16 @@ pub(crate) fn log_counts() { crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab); ExecuteIndirect: {} chained ({} of them whole, {} slabs lost), {} whole", n(&PROGRAMS), n(&PIECES), n(&DISPATCHES), n(&SLABS), mib(&LIVE), mib(&PEAK), mib(&WANTED), n(&INDIRECT), n(&INDIRECT_WHOLE), n(&INDIRECT_LOST), n(&WHOLE_INDIRECT)); + // what holds the recordings still kept: they go when their PC allocator is reset or, put aside, is free + let (keys, held) = { + let r = RECORDINGS.lock().unwrap(); + let keys: Vec<(usize, usize)> = r.iter().map(|(&a, v)| (a, v.len())).collect(); + let held = keys.iter().map(|&(_, n)| n).sum::(); + (keys, held) + }; + let [users, gpu, free, busy, idle, unknown] = super::super::alloc_pool::holds(&keys); + crate::xlog_info!("compute split: {held} of {} recordings held, under {} PC allocators: put aside with a list on it {users}, put aside with submits on the GPU {gpu}, put aside and free {free}; in use and busy {busy}, in use and free {idle}; not the pool's {unknown}", + n(&RECORDED), keys.len()); } /// The scratch a dispatch uses at once, `XCL_SPLIT_SCRATCH_MB` (256): more groups than fit run in @@ -344,6 +356,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); let held = Arc::new(Recording { scratch, first, chain, indirect: None }); + RECORDED.fetch_add(1, Ordering::Relaxed); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); DISPATCHES.fetch_add(1, Ordering::Relaxed); SLABS.fetch_add(slabs.len() as u64, Ordering::Relaxed); @@ -430,6 +443,7 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(list: &ID3D12GraphicsComma pso::record_dispatch_chain_indirect(list, &sig, &buffer, rounds, &scratch.buffer, std::iter::once(&first).chain(&chain.tail)); } let indirect = Indirect { commands: buffer, at, rounds, whole: full.is_some(), checked: bound.is_ok() && !predicated }; + RECORDED.fetch_add(1, Ordering::Relaxed); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { scratch, first, chain, indirect: Some(indirect) })); bound?; INDIRECT.fetch_add(1, Ordering::Relaxed); From c9904d7cb89a63773987102029c689d926787c91 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:07:59 -0500 Subject: [PATCH 13/15] D3D12.X: whole forms of split programs are built in turn, not a thread each `want_whole` started a thread for each split program whose whole form it asked for. A huge whole form on it waits for its turn (`driver_compile`), so the threads piled up: a run on Linux + NVIDIA had 200 of them at 280 s, 199 waiting. The whole forms now queue on one thread for each slot set of `driver_compile` (small, huge, giant), which builds them one after another and ends when its queue is empty. Small ones are never gated, and at the default of one huge compile at a time (`XCL_HUGE_PSO_CONCURRENCY`) huge or giant ones took their turns one by one already. A title thread that needs a whole form still builds it itself. A program released before its turn is not built. Co-Authored-By: Claude Opus 5.5 --- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 79 ++++++++++++++++++- 1 file changed, 76 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index cfd8805cfa..e584a02aee 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -111,14 +111,17 @@ impl Chain { /// The whole form built on another thread, for a later ExecuteIndirect with more slabs than rounds fn want_whole(self: &Arc) { if !self.wanted.swap(true, Ordering::Relaxed) { - let chain = self.clone(); - whole_thread().spawn(move || unsafe { + let len = self.whole_code.len(); + let lane = if len >= GIANT_DRIVER_COMPILE { 2 } else if len >= huge_pso_bytes() { 1 } else { 0 }; + WHOLE_BUILDS[lane].push(Arc::downgrade(self), |chain| unsafe { + // (a program released before its turn is not built) + let Some(chain) = chain.upgrade() else { return }; let waited = chain.clone(); let built = super::super::pso_async::build_waited_on(move || waited.waiting.load(Ordering::Acquire) > 0, || { if chain.whole.get().is_some() { Ok(()) } else { chain.build_whole_form().map(drop) } }); if let Err(e) = built { crate::xlog_warn!("D3D12.X: whole form of a split program: {e}"); } - }).ok(); + }); } } } @@ -129,6 +132,44 @@ fn whole_thread() -> std::thread::Builder { std::thread::Builder::new().name("xcl-pso-chain-whole".into()) } +/// Work done one item after another on one thread of `whole_thread`'s, started when there is +/// some and none is running. +struct InTurn { + queue: Mutex<(std::collections::VecDeque, bool)>, + /// threads started so far + started: AtomicU64, +} + +impl InTurn { + const fn new() -> Self { + Self { queue: Mutex::new((std::collections::VecDeque::new(), false)), started: AtomicU64::new(0) } + } + + fn push(&'static self, item: T, run: fn(T)) { + let mut q = self.queue.lock().unwrap(); + q.0.push_back(item); + if std::mem::replace(&mut q.1, true) { return; } + drop(q); + self.started.fetch_add(1, Ordering::Relaxed); + let spawned = whole_thread().spawn(move || loop { + let next = { + let mut q = self.queue.lock().unwrap(); + let next = q.0.pop_front(); + q.1 = next.is_some(); + next + }; + match next { Some(item) => run(item), None => return } + }); + // (the next push tries again) + if spawned.is_err() { self.queue.lock().unwrap().1 = false; } + } +} + +/// The whole forms `want_whole` asked for, one lane for each slot set of `driver_compile` (small +/// ones are never gated, huge and giant ones take their turns): a thread of their own for each +/// would wait for its turn as well, and a title had 200 such threads, 199 of them waiting (#2404). +static WHOLE_BUILDS: [InTurn>; 3] = [InTurn::new(), InTurn::new(), InTurn::new()]; + static CHAINS: LazyLock>>> = LazyLock::new(Default::default); pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, @@ -603,6 +644,38 @@ mod tests { /// A title thread that needs the whole form while `want_whole`'s build of it waits for its /// turn (`big_compile_turn`, every background slot taken) does not wait behind that turn: the /// build is then one the title waits for, with the wanted cap and no commit wait (#2404) + #[test] + fn whole_forms_wanted_together_are_built_one_after_another_on_one_thread() { + use super::InTurn; + use std::sync::{atomic::Ordering, Mutex}; + static TURNS: InTurn = InTurn::new(); + static GATE: Mutex<()> = Mutex::new(()); + static RAN: Mutex)>> = Mutex::new(Vec::new()); + let gate = GATE.lock().unwrap(); + for i in 0..5 { + TURNS.push(i, |i| { + drop(GATE.lock().unwrap()); + RAN.lock().unwrap().push((i, std::thread::current().name().map(String::from))); + }); + } + let started = TURNS.started.load(Ordering::Relaxed); + drop(gate); + let t = std::time::Instant::now(); + while RAN.lock().unwrap().len() < 5 && t.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let ran = RAN.lock().unwrap().clone(); + assert_eq!(started, 1, "a thread for each of 5 whole forms"); + assert_eq!(ran, (0..5).map(|i| (i, Some("xcl-pso-chain-whole".to_string()))).collect::>()); + // the thread ends with the queue; the next one starts another + let t = std::time::Instant::now(); + while TURNS.queue.lock().unwrap().1 && t.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + TURNS.push(5, |i| RAN.lock().unwrap().push((i, None))); + assert_eq!(TURNS.started.load(Ordering::Relaxed), 2); + } + #[test] fn a_title_thread_does_not_wait_behind_a_background_whole_build_waiting_for_its_turn() { use super::*; From 5b9d4ff6f5f4a2142c3c633bb1e0d700f6be5e22 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:09:03 -0500 Subject: [PATCH 14/15] D3D12.X: a chained ExecuteIndirect keeps the most rounds until the whole form is built Until a split program's whole form is built, slabs past a chained ExecuteIndirect's rounds are lost. The rounds were sized by the most slabs one of its ExecuteIndirects had read back, so the 32 of 9125edb held only until the first read-back: a program whose first ones had a slab got 2 rounds, and a later one with 22 slabs lost 20 (two runs on Linux + NVIDIA). Before the whole form is built a chained ExecuteIndirect now records the most rounds (`XCL_SPLIT_INDIRECT_ROUNDS`, 32) whatever was read back; once it is built, the last one read back sizes them as before. The whole form is asked for at the program's first chained ExecuteIndirect, so the empty rounds last until it is built. Co-Authored-By: Claude Opus 5.5 --- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 41 +++++++++---------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index e584a02aee..d37feb4003 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -79,9 +79,7 @@ struct Chain { waiting: std::sync::atomic::AtomicUsize, /// its command signature for ExecuteIndirect (`pso::chain_command_signature`) signature: OnceLock, - /// the most slabs one of its ExecuteIndirects had, the last one read back, and whether one - /// was read back yet - slabs: std::sync::atomic::AtomicU32, + /// the slabs of the last of its ExecuteIndirects read back, and whether one was read back yet last: std::sync::atomic::AtomicU32, measured: std::sync::atomic::AtomicBool, /// its whole form was asked for in the background / a lost slab was reported @@ -194,7 +192,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()), waiting: Default::default(), signature: OnceLock::new(), - slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); + last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -253,7 +251,6 @@ impl Recording { if unsafe { i.commands.Map(0, Some(&range), Some(&mut p)) }.is_err() { return; } let [partial, _, slabs, _] = unsafe { std::ptr::read_volatile((p as *const u8).add(i.at as usize) as *const [u32; 4]) }; unsafe { i.commands.Unmap(0, Some(&D3D12_RANGE::default())) }; - self.chain.slabs.fetch_max(slabs, Ordering::Relaxed); self.chain.last.store(slabs, Ordering::Relaxed); self.chain.measured.store(true, Ordering::Relaxed); if partial == 0 { return; } @@ -423,12 +420,13 @@ fn indirect_rounds(seen: &[[u32; 3]], most: u64, before: Option, cap: u32) (want + want.div_ceil(4)).clamp(2, u64::from(cap.max(2))) as u32 } -/// The slabs of an earlier ExecuteIndirect of the program for `indirect_rounds` (None: none was -/// read back yet). Until its whole form is built, the most any had: slabs past the rounds are -/// lost. Then the last one's, as more run the whole form: every round costs its pieces' -/// ExecuteIndirects, also when empty (each ~14 us of GPU after its barrier on an RTX 5070 Ti, #2404). -fn slabs_before(measured: bool, whole: bool, most: u32, last: u32) -> Option { - measured.then_some(if whole { last } else { most }) +/// The slabs of an earlier ExecuteIndirect of the program for `indirect_rounds`: None (the most +/// rounds) until one was read back and its whole form is built, as slabs past the rounds are +/// lost until then (one program's first ExecuteIndirects had a slab, a later one 22, #2404). Then +/// the last one's, as more run the whole form: every round costs its pieces' ExecuteIndirects, +/// also when empty (each ~14 us of GPU after its barrier on an RTX 5070 Ti, #2404). +fn slabs_before(measured: bool, whole: bool, last: u32) -> Option { + (measured && whole).then_some(last) } /// An ExecuteIndirect of split program `pso` whose command signature is one Dispatch of `stride` @@ -458,7 +456,7 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect(list: &ID3D12GraphicsComma None => { let s = pso::chain_command_signature(dev, &chain.builder.signature)?; chain.signature.get_or_init(|| s).clone() } }; let full = chain.whole.get().cloned().map(|p| pso::dispatch_command_signature(dev).map(|s| (p, s))).transpose()?; - let before = slabs_before(chain.measured.load(Ordering::Relaxed), full.is_some(), chain.slabs.load(Ordering::Relaxed), chain.last.load(Ordering::Relaxed)); + let before = slabs_before(chain.measured.load(Ordering::Relaxed), full.is_some(), chain.last.load(Ordering::Relaxed)); let rounds = indirect_rounds(seen, most, before, most_rounds()); let pieces = chain.tail.len() as u32 + 1; let buffer = pso::chain_commands_buffer(dev, rounds, pieces, commands).ok_or("no buffer for the commands of a chained ExecuteIndirect")?; @@ -560,14 +558,15 @@ mod tests { #[test] fn once_the_whole_form_is_built_the_last_execute_indirect_sizes_the_rounds() { use super::{indirect_rounds, slabs_before}; - assert_eq!(slabs_before(false, true, 17, 1), None); - // not built: the most slabs any had, so that none are lost - assert_eq!(slabs_before(true, false, 17, 1), Some(17)); - assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, slabs_before(true, false, 17, 1), 32), 22); + assert_eq!(slabs_before(false, true, 1), None); + // not built: the most rounds, also after one of a slab was read back (a later one can + // have 22, whose slabs past the rounds would be lost) + assert_eq!(slabs_before(true, false, 1), None); + assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, slabs_before(true, false, 1), 32), 32); // built: the last one's, an overflow runs the whole form - assert_eq!(slabs_before(true, true, 17, 1), Some(1)); - assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, slabs_before(true, true, 17, 1), 32), 2); - assert_eq!(indirect_rounds(&[[3, 1, 1]], 1, slabs_before(true, true, 17, 1), 32), 4); + assert_eq!(slabs_before(true, true, 1), Some(1)); + assert_eq!(indirect_rounds(&[[0, 0, 0]], 1, slabs_before(true, true, 1), 32), 2); + assert_eq!(indirect_rounds(&[[3, 1, 1]], 1, slabs_before(true, true, 1), 32), 4); } #[test] @@ -602,7 +601,7 @@ mod tests { let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0 }); let pso = first.as_raw() as usize; CHAINS.lock().unwrap().insert(pso, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, whole_code: Vec::new(), whole: OnceLock::new(), - build_whole: Mutex::new(()), waiting: Default::default(), signature: OnceLock::new(), slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() })); + build_whole: Mutex::new(()), waiting: Default::default(), signature: OnceLock::new(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() })); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); @@ -694,7 +693,7 @@ mod tests { let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); code[..16].copy_from_slice(&nonce.to_le_bytes()); let chain = Arc::new(Chain { builder, tail: Vec::new(), words: 4, whole_code: code, whole: OnceLock::new(), - build_whole: Mutex::new(()), waiting: Default::default(), signature: OnceLock::new(), slabs: Default::default(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); + build_whole: Mutex::new(()), waiting: Default::default(), signature: OnceLock::new(), last: Default::default(), measured: Default::default(), wanted: Default::default(), warned: Default::default() }); let held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false)).collect(); chain.want_whole(); let started = Instant::now(); From 2b32e81824e82d21d3754b14804a3a797e3b1905 Mon Sep 17 00:00:00 2001 From: b3IKK <278540256+b3IKK@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:16:18 +0000 Subject: [PATCH 15/15] D3D12.X: a freed allocator's recordings leave before its address is reused title_reset() free_aside()s a PC allocator under STATE, unlocks, and only then drops its RECORDINGS entries. A backing reused in that window could have its new recording swept away, or keep the old recording's readbacks/COM releases alive (#2404). The free backings' recordings are taken out while STATE is held and dropped after the unlock; a backing reused in between keeps the recordings made after its reuse. Patch from KDenKC's tested diff in #2404. Test: aside_sweep_keeps_recordings_made_after_backing_reuse fails on 5b9d4ff, passes here. --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 66 +++++++++++++++++-- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 10 ++- 2 files changed, 67 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index d08a3ca290..359dbe59a0 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -312,17 +312,22 @@ pub unsafe fn forget(alloc: usize) { /// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put /// aside with its recordings and another one took its place. pub unsafe fn title_reset(alloc: *mut c_void) -> Option { + title_reset_with(alloc, || {}) +} + +unsafe fn title_reset_with(alloc: *mut c_void, after_unlock: impl FnOnce()) -> Option { if !enabled() { return None; } let mut g = STATE.lock().unwrap(); let s = g.get_or_insert_with(State::default); let hr = title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)); - let free = free_aside(s); + // A backing can be reused as soon as STATE is unlocked. Detach its old recordings + // now so the sweep cannot remove recordings made by its next user. + let retired: Vec<_> = free_aside(s).filter_map(super::real::dispatch_chain::take_recordings).collect(); drop(g); - for b in free { - super::real::dispatch_chain::allocator_reset(b); - } + after_unlock(); + drop(retired); hr } @@ -331,8 +336,8 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { /// for takes one of them again, which may not come, so the scratch and commands that chained /// ExecuteIndirects kept with their recordings (`dispatch_chain::allocator_reset`) go now. Without /// this a title held 1,887 recordings under 48 allocators 110 s in, and memory grew until removal. -unsafe fn free_aside(s: &State) -> Vec { - s.aside.values().flatten().copied().filter(|b| s.backings.get(b).is_none_or(|x| x.free())).collect() +unsafe fn free_aside(s: &State) -> impl Iterator + '_ { + s.aside.values().flatten().copied().filter(move |b| s.backings.get(b).is_none_or(|x| x.free())) } /// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. @@ -396,6 +401,55 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu mod tests { use super::*; + #[test] + fn aside_sweep_keeps_recordings_made_after_backing_reuse() { + use super::super::real::dispatch_chain::{allocator_reset, holds_recordings_for_test as holds, note_recordings_for_test as note}; + + let ids = Box::new([0u8; 6]); + let title = ids.as_ptr() as usize; + let (current, spare, old_list, new_list, trigger) = (title + 1, title + 2, title + 3, title + 4, title + 5); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT.0; + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.cur.insert(title, current); + s.aside.insert(title, vec![spare]); + s.types.insert(title, ty); + move_list(s, old_list, current); + } + note(spare); + + // Pause the sweep after it unlocks and run reuse before it can finish retirement. + let hr = unsafe { title_reset_with(trigger as *mut c_void, || { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let reused = title_reset_in(s, title as *mut c_void, |raw| { + assert_eq!(raw as usize, spare); + allocator_reset(spare); // what native allocator Reset does after success + 0 + }); + assert_eq!(reused, Some(0)); + move_list(s, new_list, spare); + note(spare); + }) }; + let kept = holds(spare); + + forget_list(old_list); + forget_list(new_list); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.cur.remove(&title); + s.aside.remove(&title); + s.types.remove(&title); + s.backings.remove(¤t); + s.backings.remove(&spare); + } + allocator_reset(spare); + assert_eq!(hr, None); + assert!(kept, "the earlier sweep erased the reused backing's new recording"); + } + #[test] fn a_spare_whose_reset_fails_stays_available_for_retry() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index d37feb4003..87ee632d0c 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -222,7 +222,7 @@ impl Drop for Scratch { } } -struct Recording { +pub(in crate::hle::d3d12x) struct Recording { scratch: Arc, first: ID3D12PipelineState, chain: Arc, @@ -340,9 +340,13 @@ unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed: Some((s, false)) } +/// Take ownership without running recording readback or releasing COM objects under the lock. +pub(in crate::hle::d3d12x) fn take_recordings(allocator: usize) -> Option>> { + RECORDINGS.lock().unwrap().remove(&allocator) +} + pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) { - let recordings = RECORDINGS.lock().unwrap().remove(&allocator); - drop(recordings); + drop(take_recordings(allocator)); } #[cfg(test)]