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/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/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]); diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..d08a3ca290 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; @@ -227,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). @@ -267,7 +317,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. @@ -370,6 +435,205 @@ 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); + } + + /// 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 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] + 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/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..814f1692fe 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, + 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 +/// `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/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..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 { @@ -3167,6 +3169,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) { @@ -4594,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] @@ -5795,6 +5818,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 +5891,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/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 6fa76b4cbf..5c5cb19c08 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -13,12 +13,32 @@ 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); +/// recordings made (`RECORDINGS`) +static RECORDED: 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)); + // 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 @@ -55,19 +75,99 @@ 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 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 + wanted: std::sync::atomic::AtomicBool, + warned: std::sync::atomic::AtomicBool, } 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")?; 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 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}"); } + }); + } + } +} + +/// 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()) +} + +/// 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, @@ -91,7 +191,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(()), waiting: Default::default(), signature: OnceLock::new(), + 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(); @@ -106,6 +207,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,16 +226,67 @@ 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 and the title's predication was not set (it may skip the slicer, whose words are + /// then no count) + 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())) }; + self.chain.last.store(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; + } + 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); +/// Recordings of dispatches on a list with no title allocator (a bundle, or a list whose +/// allocator XCL cannot see): their scratch lives until the title resets that list, which D3D12 +/// only allows after the GPU has finished the commands recorded in it. +static LIST_RECORDINGS: LazyLock>>>> = LazyLock::new(Default::default); /// list → the allocator it records on and the scratch its chains share: they are dispatched one /// after another, with a barrier between them (the recordings keep it alive) static SHARED: LazyLock)>>> = LazyLock::new(Default::default); -/// `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); + LIST_RECORDINGS.lock().unwrap().remove(&list); } /// `to` records right after `from` on the same allocator: its chains go on in `from`'s scratch. @@ -144,6 +297,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. @@ -187,6 +350,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, @@ -215,8 +388,12 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, let group = u64::from(chain.words) * 4; let needed = grid.into_iter().fold(group, |s, n| s.saturating_mul(n as u64)); WANTED.fetch_max(needed, Ordering::Relaxed); - let scratch = (allocator != 0 && list.GetType() != D3D12_COMMAND_LIST_TYPE_BUNDLE) - .then(|| scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, needed, group)).flatten(); + let list_key = list.as_raw() as usize; + // No title allocator (a bundle, or a list whose allocator XCL cannot see): XCL owns the + // scratch and keeps it until the title resets the list (D3D12 allows a reset only after the + // GPU has finished the commands recorded in it), so the pieces run instead of the whole form. + let owned = allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE; + let scratch = scratch_for(&chain.builder.device, list_key, if owned { 0 } else { allocator }, needed, group); let most = scratch.as_ref().map_or(1, |(s, _)| (s.bytes / group).max(1)); let slabs = pso::dispatch_slabs(grid, most); let Some((scratch, used)) = scratch else { @@ -225,14 +402,171 @@ 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 }); - RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); + let held = Arc::new(Recording { scratch, first, chain, indirect: None }); + RECORDED.fetch_add(1, Ordering::Relaxed); + if owned { + LIST_RECORDINGS.lock().unwrap().entry(list_key).or_default().push(held.clone()); + } else { + 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); pso::record_dispatch_chain(list, grid, most, &held.scratch.buffer, used, std::iter::once(&held.first).chain(&held.chain.tail)); Ok(()) } +/// 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(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`. 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 +} + +/// 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` +/// 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 (`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]], predicated: bool, bind: impl FnOnce() -> Result<(), String>) -> Result { + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + let Some(chain) = chain else { 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) }; + 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 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.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")?; + // 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 + // 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() && !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); + Ok(true) +} + +#[cfg(test)] +mod scratch_tests { + use super::*; + use std::sync::atomic::{AtomicBool, AtomicU32}; + + unsafe extern "system" fn no_create(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { + E_INVALIDARG + } + + /// A bundle (or a list with no title allocator) runs the already-compiled pieces with an + /// XCL-owned scratch, not the whole form; the scratch is released when the bundle is reset. + #[test] + fn a_bundle_dispatch_runs_the_pieces_with_an_xcl_scratch_not_the_whole_form() { + unsafe { + if crate::gpu::recomp::dxc::location().is_err() { + return crate::gpu::recomp::runner::skip_test("no DXC"); + } + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); + if let Ok(warp) = warp { + let _ = D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev); + } + } + let Some(dev) = dev else { return crate::gpu::recomp::runner::skip_test("no D3D12 device") }; + let dxil = crate::gpu::recomp::dxc::compile( + "RWByteAddressBuffer mem : register(u2); [numthreads(1,1,1)] void main() { mem.Store(0, 1); }", + "main", "cs_6_6", &[], + ).expect("DXC compile"); + let rs = pso::dispatch_chain_root_signature(&dev, &[]).expect("dispatch chain RS"); + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).expect("CreateComputePipelineState"); + std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: no_create, signature: rs.clone(), flags: Default::default(), node: 0, record: 0 }); + let chain = Arc::new(Chain { + builder, tail: Vec::new(), words: 4, whole_code: Vec::new(), whole: OnceLock::new(), build_whole: Mutex::new(()), + signature: OnceLock::new(), waiting: std::sync::atomic::AtomicUsize::new(0), last: AtomicU32::new(0), measured: AtomicBool::new(false), + wanted: AtomicBool::new(false), warned: AtomicBool::new(false), + }); + let pso = first.clone().into_raw() as usize; + CHAINS.lock().unwrap().insert(pso, chain.clone()); + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE).expect("bundle allocator"); + let bundle: ID3D12GraphicsCommandList = dev.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_BUNDLE, + &alloc, + Option::<&ID3D12PipelineState>::None, + ).expect("bundle"); + bundle.SetComputeRootSignature(&rs); + assert!(dispatch(&bundle, pso, 0, [1, 1, 1]).is_ok(), "the bundle records the pieces"); + assert!(LIST_RECORDINGS.lock().unwrap().get(&(bundle.as_raw() as usize)).is_some_and(|v| !v.is_empty()), "the scratch is kept with the bundle"); + list_reset(bundle.as_raw() as usize); + assert!(!LIST_RECORDINGS.lock().unwrap().contains_key(&(bundle.as_raw() as usize)), "resetting the bundle releases its scratch"); + drop(bundle); + drop(alloc); + forget(pso); + } + } +} + #[cfg(test)] mod tests { use super::{scratch_bytes, LEAST}; @@ -284,4 +618,176 @@ 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_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 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, 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, 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] + 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::*; + 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.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(), 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(); + 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]], 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 + // (`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(()) + }; + 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])); + list.Close().unwrap(); + allocator_reset(allocator); + list_reset(raw_list); + forget(pso); + 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 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::*; + 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(), 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"); + } + } }