diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 8687e4807a..6bf5716672 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -197,6 +197,8 @@ fn translate_on_this_thread( let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); + // a compute program: whether this group runs (`compute_init`: not past a folded dispatch's count) + let mut group_runs = None; let numthreads = match &entry { Entry::Kernel => { lw.setup_lanes(); @@ -209,7 +211,7 @@ fn translate_on_this_thread( } Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); - compute_init(&mut lw, cs, tid, gtid); + group_runs = Some(compute_init(&mut lw, cs, tid, gtid)); cs.threads } Entry::Mesh(ms) => { @@ -301,6 +303,8 @@ fn translate_on_this_thread( } let h0 = if plan.is_some() { lw.block(None) } else { head(&mut lw, entry) }; let exit = lw.block(None); + // where `Block(0)` goes + let mut first = h0; if gs_only { // the GS alone: in the lower hardware wave only let gate = lw.block(Some(1)); @@ -308,6 +312,14 @@ fn translate_on_this_thread( lw.s.m.set_block(gate); let up = lw.upper; lw.cond_br(up, exit, h0); + } else if let Some(runs) = group_runs { + // a folded dispatch's groups past the console's count leave at once (the whole group: + // no barrier waits on them) + let gate = lw.block(Some(1)); + lw.edge(Block(0), gate); + lw.s.m.set_block(gate); + lw.cond_br(runs, h0, exit); + first = gate; } else { lw.edge(Block(0), h0); } @@ -420,7 +432,7 @@ fn translate_on_this_thread( } lw.s.m.ret(); lw.s.m.set_block(Block(0)); - lw.s.m.br(h0); + lw.s.m.br(first); let hw = if split || !o.wave64 { 32 } else { 64 }; lw.finish(numthreads, hw) } @@ -641,12 +653,28 @@ fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { /// The compute entry's fixed registers (the HLSL compute mode's prologue): group ids /// after the user SGPRs, TG_SIZE, SCC = 0, EXEC = the wave's threads, v0..v2 = thread id. -pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { +/// Returns whether this group runs: a dispatch folded into Y (`recomp::IO_GROUP_LIMIT` in `io` +/// not 0, the console's group count in X) takes its group in X from both ids, and the groups +/// past that count do not run. +pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) -> Value { + let io = lw.init.io.expect("the I/O buffer"); + let o = lw.c((crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32); + let limit = lw.s.raw_load(io, o, 1)[0]; + let (gx, gy) = (lw.s.group_id(0), lw.s.group_id(1)); + let k = lw.c(crate::gpu::recomp::FOLD_X); + let rows = lw.mul(gy, k); + let flat = lw.add(gx, rows); + let folded = lw.cmpc(Pred::Ne, limit, 0); + let zero = lw.c(0); + let ids = [lw.sel(folded, flat, gx), lw.sel(folded, zero, gy)]; + let inside = lw.cmp(Pred::ULt, flat, limit); + let t = lw.b(true); + let runs = lw.sel(folded, inside, t); let mut sgpr = HashMap::new(); let mut next = cs.user_sgprs; for k in 0..3 { if cs.tgid[k] { - let g = lw.s.group_id(k as u32); + let g = if k < 2 { ids[k] } else { lw.s.group_id(2) }; sgpr.insert(next, g); next += 1; } @@ -674,6 +702,7 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) } } lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); + runs } /// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 069c8b3f6f..ea347d9371 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4919,12 +4919,20 @@ impl Em { h.push_str(" lane_id = WaveGetLaneIndex();\n"); } load_sgprs(&mut h); + // a folded dispatch (`IO_GROUP_LIMIT`): the console's group in X, the groups + // past its count left out (the whole group returns) + let _ = writeln!( + h, + " uint3 xcl_gid = gid;\n {{\n uint xcl_gl = io.Load({}u);\n if (xcl_gl != 0u) {{\n uint xcl_f = gid.x + gid.y * {}u;\n if (xcl_f >= xcl_gl) return;\n xcl_gid = uint3(xcl_f, 0u, gid.z);\n }}\n }}", + super::IO_GROUP_LIMIT * 4, + super::FOLD_X + ); // system SGPRs after the user data: enabled group ids, then TG_SIZE let mut next = cs.user_sgprs as u64; for (k, c) in ["x", "y", "z"].iter().enumerate() { if cs.tgid[k] { if sg.contains(&next) { - let _ = writeln!(h, " {} = gid.{c};", sname(next).unwrap()); + let _ = writeln!(h, " {} = xcl_gid.{c};", sname(next).unwrap()); } next += 1; } diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index a62b1c9810..20eda3e90b 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1294,12 +1294,15 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s prev = c; } } - // compute: every lane that runs is in EXEC, and nothing is stored at the end – the skip and - // store blocks are left unreachable (a bare `ret`) + // compute: every lane that runs is in EXEC, and nothing is stored at the end – the store + // blocks are left unreachable, and the skip block (a bare `ret`) takes the groups past a + // folded dispatch's count if kernel { preds[skip] = vec![0]; preds[sstore] = vec![exit]; preds[vstore] = vec![exit, sstore]; + } else if matches!(stage, Stage::Compute(_)) { + preds[skip] = vec![0]; } preds[exit] = kernel.then_some(skip).into_iter().chain(ends.iter().map(|&b| tail[b])).collect(); for i in 0..count { @@ -1392,11 +1395,25 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s } Stage::Compute(cs) => { let (flat, tid) = l.ir.compute_ids(cs.threads); + // a dispatch folded into Y (`IO_GROUP_LIMIT` not 0: the console's group count in X): + // the group in X from both ids, the groups past the count leave at once + let a = l.ir.int(super::IO_GROUP_LIMIT as u32); + let limit = l.ir.io_load(a); + let (gx, gy) = (l.ir.group_id(0), l.ir.group_id(1)); + let k = l.ir.int(super::FOLD_X); + let rows = l.ir.bin(Bin::Mul, gy, k); + let group = l.ir.bin(Bin::Add, gx, rows); + let z = l.ir.int(0); + let folded = l.ir.icmp(Cmp::Ne, limit, z); + let ids = [l.ir.select(folded, group, gx), l.ir.select(folded, z, gy)]; + let inside = l.ir.icmp(Cmp::Ult, group, limit); + let t = l.ir.boolean(true); + let runs = l.ir.select(folded, inside, t); // system SGPRs after the user data: the enabled group ids, then TG_SIZE let mut next = cs.user_sgprs as u8; for k in 0..3 { if cs.tgid[k as usize] { - let g = l.ir.group_id(k); + let g = if k < 2 { ids[k as usize] } else { l.ir.group_id(k) }; l.write_num(0, next, g); next += 1; } @@ -1426,7 +1443,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s // every lane that runs is in EXEC let t = l.ir.boolean(true); l.write_bit(0, EXEC, t); - l.ir.br(blk(0)); + l.ir.br_if(runs, blk(0), skip); l.ir.at(skip); l.ssa.seal(&mut l.ir, skip); l.ir.ret(); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index d1e7d8bc4e..38bb58a68f 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -202,6 +202,14 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21; pub const IO_GS_PRIMS: usize = 110; pub const IO_GS_VERTICES: usize = 111; pub const IO_UMA_BASE_HI: usize = 112; +/// io slot (trap-temp range) of a compute dispatch whose groups were folded: the console's group +/// count in X, 0 when not folded. The console takes up to 2^32 − 1 groups a dimension, D3D12 +/// 65 535 – a dispatch of more in X (and 1 in Y) runs as 65 535 × ⌈n / 65 535⌉ groups, and +/// the translated program takes `gid.x + gid.y · 65 535` as its group in X, leaving out the +/// groups at or past `n` (a retail game's 72 512 × 1 × 1 hung the GPU). +pub const IO_GROUP_LIMIT: usize = 113; +/// Groups a folded dispatch has in X. +pub const FOLD_X: u32 = 65_535; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 4cd1663d56..f602b6ecf7 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -533,6 +533,14 @@ fn transition(r: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RE } /// Name of the GPU the kernels run on (None: no usable GPU). +/// The tests' device (with the Agility SDK when there is one): a test that makes its own device +/// first leaves the SDK unappliable for the process (0x887E0003), and the GPU tests after it skip. +pub fn device() -> Result { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init); + gpu.as_ref().map(|x| x.dev.clone()).map_err(|x| x.clone()) +} + pub fn adapter() -> Result { let mut g = GPU.lock().unwrap(); let gpu = g.get_or_insert_with(init); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 8aa9aa1c01..44c51809c9 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7366,6 +7366,62 @@ fn gpu_compute_tg_size_counts_a_partial_last_wave() { } } +/// A dispatch of more groups in X than D3D12 takes, folded into Y (`IO_GROUP_LIMIT`): each of +/// the console's groups runs once with its own id in X, none past its count; with no count in io +/// the groups are the dispatch's own (a retail game's 72 512 × 1 × 1 hung the GPU unfolded). +/// The HLSL path, then the direct translator (`gpu::dxil`, wave32 / wave64 / split wave64) and +/// its per-lane form (`lower_dxil`): `bind` and `clamp` fold for every translated pipeline. +#[test] +fn gpu_compute_folded_dispatch_runs_each_console_group_once() { + if !gpu_ready() { + return; + } + // global_store_dword [s2 * 4], s2 (s2: the group id in X after user SGPRs s0, s1) + let p = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 2)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 4)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 0x7D)], None), + ]); + let fold = super::FOLD_X; + // each console group once, none past the count; unfolded, the dispatch's own groups + let check = |dxil: &[u8], what: &str| { + for n in [72_512u32, fold + 1] { + let rows = n.div_ceil(fold); + let mut io = vec![0u32; 128]; + io[super::IO_GROUP_LIMIT] = n; + let mem = runner::dispatch(dxil, [fold, rows, 1], &io, &vec![0xFFFF_FFFFu32; (fold * rows) as usize]).unwrap_or_else(|e| panic!("{what}: {e}")); + for (k, &got) in mem.iter().enumerate() { + let want = if (k as u32) < n { k as u32 } else { 0xFFFF_FFFF }; + assert_eq!(got, want, "{what}: {n} groups folded into {fold} x {rows}, group {k}"); + } + } + let mem = runner::dispatch(dxil, [100, 1, 1], &[0u32; 128], &vec![0xFFFF_FFFFu32; 128]).unwrap(); + for (k, &got) in mem.iter().enumerate() { + assert_eq!(got, if k < 100 { k as u32 } else { 0xFFFF_FFFF }, "{what}: unfolded group {k}"); + } + }; + let cs = super::CsInterface { threads: [1, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + // the native wave64 forms need a GPU that runs wave64 (the split form runs anywhere) + let wave64_ok = runner::wave64_supported() == Ok(true); + for wave64 in [false, true] { + let t = translate(&p, &on_gpu(Options { mode: Mode::Compute(cs.clone()), wave64, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e} +{}", t.hlsl)); + check(&dxil, &format!("HLSL, wave64 {wave64}")); + if !wave64 || wave64_ok { + let dxil = super::lower_dxil::compute_code(&p, &cs, wave64).unwrap(); + check(&dxil, &format!("per-lane, wave64 {wave64}")); + } + } + for (wave64, split) in [(false, false), (true, false), (true, true)].into_iter().filter(|&(w, s)| !w || s || wave64_ok) { + let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let k = crate::gpu::dxil::kernel::translate_compute(&p, o, &cs).unwrap(); + check(&k.dxil, &format!("direct, wave64 {wave64}, split {split}")); + } +} + /// v_fract_f32 at the edges, as RDNA computes it (x - floor(x) kept below 1.0): ±inf gives /// NaN and a NaN stays NaN – a `min()` clamp returned 0.99999994 there on NVIDIA (HLSL min /// returns its non-NaN operand); a tiny negative value rounds to the largest float below 1. diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index c888e6325d..7b44931daa 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -312,10 +312,24 @@ 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 }; - match bind_abi(this, list, pso, gfx) { - Ok(()) => { + match bind_abi(this, list, pso, gfx, 0) { + Ok(b) => { + // one dispatch: its group counts folded or clamped on the GPU first (`clamp`, which + // writes a folded count into this dispatch's io), then the binding set again + let (mut args, mut args_off) = (args, args_off); + let mut clamped = None; + if !gfx && max == 1 { + clamped = super::clamp::before(list, args, args_off, b.io + 4 * crate::gpu::recomp::IO_GROUP_LIMIT as u64); + if let Some((a, o)) = clamped { + (args, args_off) = (a, o); + rebind(list, &b, false); + } + } count(if gfx { DRAWS } else { DISPATCHES }); - fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) + fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); + if clamped.is_some() { + super::clamp::done(list); + } } Err(e) => { count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); @@ -559,8 +573,8 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option if super::present::trace_frame() { trace_ui_draw(this, pso); } - match bind_abi(this, &list, pso, true) { - Ok(()) => { + match bind_abi(this, &list, pso, true, 0) { + Ok(_) => { count(DRAWS); Some(list) } @@ -969,15 +983,61 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis if super::present::trace_frame() { trace_fullscreen(this, pso, [x, y, z]); } - bind_abi(this, list, pso, false)?; + // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`) + let (limit, [x, y, z]) = fold(x, y, z); + bind_abi(this, list, pso, false, limit)?; list.Dispatch(x, y, z); Ok(()) } +/// A dispatch of `x` × `y` × `z` groups as D3D12 takes it: (the count for +/// `recomp::IO_GROUP_LIMIT` – 0: not folded –, the groups to dispatch). More than 65 535 in X +/// with 1 in Y is folded into Y; any other count past 65 535 is clamped (logged once). +pub(super) fn fold(x: u32, y: u32, z: u32) -> (u32, [u32; 3]) { + use crate::gpu::recomp::FOLD_X; + if x <= FOLD_X && y <= 65_535 && z <= 65_535 { + return (0, [x, y, z]); + } + if y == 1 && z <= 65_535 && x.div_ceil(FOLD_X) <= 65_535 { + return (x, [FOLD_X, x.div_ceil(FOLD_X), z]); + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: a dispatch of {x}x{y}x{z} groups cannot be folded – clamped to 65535 a dimension"); + } + (0, [x.min(65_535), y.min(65_535), z.min(65_535)]) +} + +/// What `bind_abi` set on a list, for setting it again after other work in between (`rebind`) +/// and the GPU address of its `io`. +pub(super) struct Bound { + rs: ID3D12RootSignature, + views: [u64; 6], + pso: ID3D12PipelineState, + pub io: u64, +} + +/// The binding `bind_abi` made, set on `list` again. +pub(super) unsafe fn rebind(list: &ID3D12GraphicsCommandList, b: &Bound, gfx: bool) { + if gfx { + list.SetGraphicsRootSignature(&b.rs); + for (k, v) in b.views.iter().enumerate() { + list.SetGraphicsRootUnorderedAccessView(k as u32, *v); + } + } else { + list.SetComputeRootSignature(&b.rs); + for (k, v) in b.views.iter().enumerate() { + list.SetComputeRootUnorderedAccessView(k as u32, *v); + } + } + list.SetPipelineState(&b.pso); +} + /// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept /// arguments the console's way – compute or graphics) and the argument table in unified -/// memory, u1 res, u2… the memory windows; then the pipeline. -unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { +/// memory, u1 res, u2… the memory windows; then the pipeline. `group_limit`: a folded +/// dispatch's group count in X (`recomp::IO_GROUP_LIMIT`), 0 for any other. +unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, group_limit: u32) -> Result { super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); @@ -1002,28 +1062,24 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + io[crate::gpu::recomp::IO_GROUP_LIMIT] = group_limit; let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; let rs = rs as *mut c_void; - let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; - let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); - if gfx { - list.SetGraphicsRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetGraphicsRootUnorderedAccessView(k as u32, v); - } - } else { - list.SetComputeRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetComputeRootUnorderedAccessView(k as u32, v); - } + let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?.clone(); + let mut views = [first; 6]; + views[0] = va(io_at); + views[1] = va(res_at); + for k in 0..4 { + views[2 + k] = windows.get(k).copied().unwrap_or(first); } let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; - list.SetPipelineState(pc); - Ok(()) + let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?.clone(); + let b = Bound { rs, views, pso: pc, io: views[0] }; + rebind(list, &b, gfx); + Ok(b) } #[cfg(test)] @@ -1052,6 +1108,24 @@ mod tests { use super::*; use std::sync::atomic::AtomicUsize; + /// Counts D3D12 takes are dispatched as they are; more than 65 535 in X with 1 in Y are + /// folded into Y with the console's count kept (a retail game's 72 512 × 1 × 1); others past + /// the limit are clamped. + #[test] + fn dispatches_past_the_d3d12_limit_are_folded_or_clamped() { + assert_eq!(fold(64, 2, 1), (0, [64, 2, 1])); + assert_eq!(fold(65_535, 1, 1), (0, [65_535, 1, 1])); + assert_eq!(fold(72_512, 1, 1), (72_512, [65_535, 2, 1])); + assert_eq!(fold(131_071, 1, 3), (131_071, [65_535, 3, 3])); + assert_eq!(fold(70_000, 2, 1), (0, [65_535, 2, 1]), "two dimensions in use: clamped"); + // every console group is in the folded grid exactly once, and no more than 65 535 more + for n in [65_536u32, 72_512, 75_072, 200_000] { + let (limit, [x, y, _]) = fold(n, 1, 1); + assert_eq!(limit, n); + assert!(x * y >= n && x * y - n < x, "{n}: {x}x{y}"); + } + } + /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. #[test] fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { diff --git a/crates/xcl/src/hle/d3d12x/clamp.rs b/crates/xcl/src/hle/d3d12x/clamp.rs new file mode 100644 index 0000000000..b57f88a09e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/clamp.rs @@ -0,0 +1,304 @@ +//! Indirect compute dispatches with group counts D3D12 takes (`XCL_CLAMP_INDIRECT=0`: off). +//! +//! The console runs up to 2^32 − 1 groups a dimension; D3D12 takes 65 535, and past that the +//! dispatch is undefined – on an NVIDIA GPU it ran on until the driver reset the device +//! (0x887A0006). A retail game's world loading dispatches a compute program indirectly with +//! 72 512 × 1 × 1 and 75 072 × 1 × 1 groups, counts another dispatch wrote, so the CPU never sees +//! them. +//! +//! Before such a dispatch a one-thread pass reads its three counts and writes the ones to +//! dispatch into a slot of XCL's own buffer: more than 65 535 in X with 1 in Y folded into Y, +//! with the console's count written into the dispatch's io (`recomp::IO_GROUP_LIMIT`: the +//! program takes its group in X from both and leaves out the groups past the count), any other +//! count past 65 535 clamped. The dispatch then reads the slot. How many were folded and clamped, +//! and the latest counts, are kept in the buffer's first 32 bytes and logged now and then (the +//! buffer is CPU-visible memory, a custom heap). + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +/// Slots of 16 bytes after the header; reused in turn (a slot is read by the dispatch recorded +/// right after it is written, long before 65 536 more indirect dispatches come). +const SLOTS: u64 = 1 << 16; +/// Counts clamped (count, the last x, y, z) and folded (count, the last x) – 32 bytes. +const HEADER: u64 = 32; + +const HLSL: &str = r#" +#define RS "RootConstants(num32BitConstants=1, b0), UAV(u0), UAV(u1), UAV(u2)" +cbuffer C : register(b0) { uint slot; }; +RWByteAddressBuffer src : register(u0); +RWByteAddressBuffer dst : register(u1); +RWByteAddressBuffer io : register(u2); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint3 g = src.Load3(0); + uint3 c; + uint folded = 0u; + // rows of 65 535 groups (a ceiling without an addition that could wrap near 2^32) + uint rows = g.x / 65535u + (g.x % 65535u != 0u ? 1u : 0u); + if (g.x > 65535u && g.y == 1u && g.z <= 65535u && rows <= 65535u) { + // more groups in X than D3D12 takes: folded into Y, the program told the count + // (as `bind::fold` does on the CPU) + folded = g.x; + c = uint3(65535u, rows, g.z); + } else { + c = min(g, 65535u); + } + io.Store(0, folded); + if (folded != 0u) { + uint n; + dst.InterlockedAdd(16, 1, n); + dst.Store(20, g.x); + } else if (any(c != g)) { + uint n; + dst.InterlockedAdd(0, 1, n); + dst.Store3(4, g); + } + dst.Store3(32 + slot * 16, c); +} +"#; + +struct Clamp { + rs: ID3D12RootSignature, + pso: ID3D12PipelineState, + buf: ID3D12Resource, + gpu: u64, + cpu: *const u32, +} +// SAFETY: D3D12 objects are free-threaded; `cpu` is the persistent map of `buf`, only read +unsafe impl Send for Clamp {} +unsafe impl Sync for Clamp {} + +pub fn enabled() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("XCL_CLAMP_INDIRECT").map_or(true, |v| v.trim() != "0")) +} + +fn get(list: &ID3D12GraphicsCommandList) -> Option<&'static Clamp> { + static C: OnceLock> = OnceLock::new(); + C.get_or_init(|| match unsafe { make(list) } { + Ok(c) => { + crate::xlog_info!("D3D12.X: indirect dispatches past 65535 groups a dimension are folded or clamped on the GPU"); + Some(c) + } + Err(e) => { + crate::xlog_warn!("D3D12.X: indirect dispatches are not clamped: {e}"); + None + } + }) + .as_ref() +} + +unsafe fn make(list: &ID3D12GraphicsCommandList) -> Result { + let mut dev: Option = None; + list.GetDevice(&mut dev).map_err(|e| e.to_string())?; + let dev = dev.ok_or("no device")?; + let dxil = crate::gpu::recomp::dxc::compile(HLSL, "main", "cs_6_0", &[])?; + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("root signature: {e}"))?; + let 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 pso: Result = dev.CreateComputePipelineState(&desc); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + let pso = pso.map_err(|e| format!("pipeline: {e}"))?; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let bdesc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: HEADER + SLOTS * 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &bdesc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("buffer: {e}"))?; + let buf = buf.ok_or("buffer")?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).map_err(|e| format!("map: {e}"))?; + std::ptr::write_bytes(p as *mut u8, 0, HEADER as usize); + Ok(Clamp { rs, pso, gpu: buf.GetGPUVirtualAddress(), buf, cpu: p as *const u32 }) +} + +fn transition(res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + 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: unsafe { std::mem::transmute_copy(res) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// Before one indirect dispatch whose counts are at `args` + `off` (a buffer that takes UAV +/// access): the counts as D3D12 takes them – more than 65 535 in X (1 in Y) folded into Y with +/// the console's count written to `io_limit` (the dispatch's `recomp::IO_GROUP_LIMIT` word, 0 +/// otherwise), any other count past 65 535 clamped – in a slot of XCL's buffer, which is +/// returned with the slot's offset, in INDIRECT_ARGUMENT state; `done` returns it to UAV after +/// the dispatch. None: left as it was (the caller dispatches from `args`). The list's compute +/// root signature, root arguments and pipeline are changed: the caller sets its own again. +pub unsafe fn before(list: &ID3D12GraphicsCommandList, args: usize, off: u64, io_limit: u64) -> Option<(usize, u64)> { + if !enabled() { + return None; + } + let raw = args as *mut c_void; + let res = ID3D12Resource::from_raw_borrowed(&raw)?; + let d = res.GetDesc(); + if d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 || off % 4 != 0 || off + 12 > d.Width { + static N: AtomicU32 = AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: an indirect dispatch's arguments ({:?}, flags {:#x}, offset {off:#x}) cannot be clamped", d.Dimension, d.Flags.0); + } + return None; + } + let c = get(list)?; + static NEXT: AtomicU64 = AtomicU64::new(0); + let slot = NEXT.fetch_add(1, Ordering::Relaxed) % SLOTS; + // COMMON at the list's start: promoted to UAV by its first use + list.SetComputeRootSignature(&c.rs); + list.SetPipelineState(&c.pso); + list.SetComputeRoot32BitConstant(0, slot as u32, 0); + list.SetComputeRootUnorderedAccessView(1, res.GetGPUVirtualAddress() + off); + list.SetComputeRootUnorderedAccessView(2, c.gpu); + list.SetComputeRootUnorderedAccessView(3, io_limit); + list.Dispatch(1, 1, 1); + // the slot for the dispatch's arguments; the io word for its program (a UAV barrier on all) + let uav = 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.ResourceBarrier(&[transition(&c.buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), uav]); + report(c); + Some((c.buf.as_raw() as usize, HEADER + slot * 16)) +} + +/// After the dispatch `before` clamped: XCL's buffer back in UAV state. +pub unsafe fn done(list: &ID3D12GraphicsCommandList) { + if let Some(c) = get(list) { + list.ResourceBarrier(&[transition(&c.buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + } +} + +/// The counts the GPU had to change so far: logged when more were changed (at most every 2 s). +fn report(c: &Clamp) { + static SEEN: AtomicU32 = AtomicU32::new(0); + static LAST: Mutex> = Mutex::new(None); + let mut l = LAST.lock().unwrap(); + if l.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(2)) { + return; + } + *l = Some(std::time::Instant::now()); + // SAFETY: the mapped header of `buf` (16 bytes) + let w = |k: usize| unsafe { std::ptr::read_volatile(c.cpu.add(k)) }; + let n = w(0); + if n != SEEN.swap(n, Ordering::Relaxed) { + crate::xlog_warn!("D3D12.X: {n} indirect dispatches had group counts clamped so far (the latest asked for {}x{}x{})", w(1), w(2), w(3)); + } + static FOLDED: AtomicU32 = AtomicU32::new(0); + let f = w(4); + if f != FOLDED.swap(f, Ordering::Relaxed) { + crate::xlog_info!("D3D12.X: {f} indirect dispatches folded so far (the latest of {} groups in X)", w(5)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A CPU-visible buffer that takes UAV access (a custom heap), mapped. + unsafe fn visible(dev: &ID3D12Device, bytes: u64) -> (ID3D12Resource, *mut u32) { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf).unwrap(); + let buf = buf.unwrap(); + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).unwrap(); + (buf, p as *mut u32) + } + + /// The pass writes the counts D3D12 takes into its slot: 72 512 × 1 × 1 folded into + /// 65 535 × 2 × 1 with 72 512 in io; 70 000 × 2 × 1 clamped with 0 in io; 300 × 4 × 2 as + /// it was. + #[test] + fn indirect_group_counts_are_folded_or_clamped_on_the_gpu() { + use crate::gpu::recomp::runner; + unsafe { + let dev = match (runner::device(), crate::gpu::recomp::dxc::location()) { + (Ok(d), Ok(_)) => d, + _ => { + runner::skip_test("no GPU or DXC"); + return; + } + }; + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + // (the last three at the top of the range: 65 535² folds into exactly 65 535 rows, + // one more or u32::MAX would need 65 536 rows – clamped, as `bind::fold` does) + for (k, (args, want, io_want)) in [ + ([72_512u32, 1, 1], [65_535u32, 2, 1], 72_512u32), + ([70_000, 2, 1], [65_535, 2, 1], 0), + ([300, 4, 2], [300, 4, 2], 0), + ([65_535 * 65_535, 1, 1], [65_535, 65_535, 1], 65_535 * 65_535), + ([65_535 * 65_535 + 1, 1, 1], [65_535, 1, 1], 0), + ([u32::MAX, 1, 1], [65_535, 1, 1], 0), + ] + .into_iter() + .enumerate() + { + let (limit, groups) = super::super::bind::fold(args[0], args[1], args[2]); + assert_eq!((groups, limit), (want, io_want), "{args:?}: the CPU's fold, which the GPU's must match"); + let (a, ap) = visible(&dev, 256); + let (io, iop) = visible(&dev, 256); + std::ptr::copy_nonoverlapping(args.as_ptr(), ap.add(16), 3); + *iop = 0xDEAD; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let (buf, off) = before(&list, a.as_raw() as usize, 64, io.GetGPUVirtualAddress()).expect("clamped"); + done(&list); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, k as u64 + 1).unwrap(); + let t = std::time::Instant::now(); + while fence.GetCompletedValue() < k as u64 + 1 { + assert!(t.elapsed().as_secs() < 10, "the pass did not finish"); + std::thread::yield_now(); + } + let c = get(&list).unwrap(); + assert_eq!(buf, c.buf.as_raw() as usize); + let slot = c.cpu.add(off as usize / 4); + let got = [*slot, *slot.add(1), *slot.add(2)]; + assert_eq!(got, want, "{args:?}"); + assert_eq!(*iop, io_want, "{args:?}: io"); + } + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 3a3480f18b..22503fa1c7 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -832,6 +832,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`) + let (limit, [x, y, z]) = super::bind::fold(x, y, z); + io[crate::gpu::recomp::IO_GROUP_LIMIT] = limit; let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?; let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?; // the pipeline's own root signature when it has static samplers diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f0357981..63d88ced13 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -13,6 +13,7 @@ mod alloc_pool; pub mod bind; pub mod console_heap; pub mod console_list; +pub mod clamp; pub mod device_x; pub mod dxgi_device; mod cpu_writes;