diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8e..65ab22ece0 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; // `pso.rs` also contains cache storage and pipeline setup. Keep it out of the source hash so // those changes do not discard translations; bump this only when its container parsing, // translation options, profiles, or post-translation HLSL changes. -const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v2"; +const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v3"; const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/dxbc.rs", diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..bca748de70 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -259,6 +259,10 @@ fn translate_on_this_thread( [1, 1, 1] } }; + // Entry setup may contain real control flow (compute dispatch limits use a guarded + // prologue). The program must start after that prologue's join, not by appending another + // branch to the already-terminated physical entry block. + let prologue = lw.cur(); // the HLSL kernel loads and stores every register its emitted instructions name: all of // them in a program with branches, those up to the first s_endpgm in straight-line code let branchy = cfg.insts.iter().any(|d| crate::gpu::rdna2::branch_target(d).is_some()); @@ -325,12 +329,12 @@ fn translate_on_this_thread( if gs_only { // the GS alone: in the lower hardware wave only let gate = lw.block(Some(1)); - lw.edge(Block(0), gate); + lw.edge(prologue, gate); lw.s.m.set_block(gate); let up = lw.upper; lw.cond_br(up, exit, h0); } else { - lw.edge(Block(0), h0); + lw.edge(prologue, h0); } let switch = if two_phase { Some(lw.block(None)) } else { None }; // scalar loads the program repeats keep their first values (compute programs and kernels: @@ -440,7 +444,7 @@ fn translate_on_this_thread( } } lw.s.m.ret(); - lw.s.m.set_block(Block(0)); + lw.s.m.set_block(prologue); lw.s.m.br(h0); let hw = if split || !o.wave64 { 32 } else { 64 }; let limit = if compute && (!split || split_tid.is_some()) { dispatch_piece_limit() } else { 0 }; @@ -474,7 +478,7 @@ impl Lw { /// `entry`: the shader with its buffers, /// the SSA's entry block, the program's LDS and the split form's exchange storage and /// partner. The caller then sets up the lanes for its entry (`setup_lanes*`), lowers the - /// program's blocks, branches from `Block(0)` to the first of them and ends with + /// program's blocks, branches from the entry prologue's exit to the first of them and ends with /// [`Lw::finish`]. #1426's block walk (`translate_on_this_thread`) and the recompiler's /// per-lane lowering (`recomp::lower_dxil`) both build their `Lw` here. pub fn new(insts: &[Decoded], leaders: &BTreeSet, o: KernelOptions, entry: &Entry) -> Lw { @@ -644,6 +648,15 @@ impl Lw { } } +#[cfg(test)] +#[test] +fn compute_dispatch_limit_prologue_reaches_the_program_after_its_guard() { + let code = crate::gpu::rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap(); + let cs = CsInterface { threads: [64, 1, 1], ..Default::default() }; + let options = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + translate_compute(&code, options, &cs).expect("a guarded dispatch-limit prologue"); +} + #[cfg(test)] #[test] fn dispatch_chain_native_wave64_builds_whole() { @@ -741,7 +754,44 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) } let zero = lw.c(0); sgpr.insert(VAR_SCC, zero); + let io = lw.init.io.expect("the I/O buffer"); + let mut dispatch_limited = lw.s.m.i1c(false); + let mut limits = Vec::new(); + for (k, _) in cs.threads.iter().enumerate().filter(|(_, &threads)| threads > 1) { + let off = lw.c((crate::gpu::recomp::IO_THREAD_LIMIT[k] * 4) as u32); + let limit = lw.s.raw_load(io, off, 1)[0]; + let zero = lw.c(0); + let limited = lw.cmp(Pred::Ne, limit, zero); + dispatch_limited = lw.lor(dispatch_limited, limited); + limits.push((k, limit)); + } let (lo, hi) = entry_exec(lw, total, tid); + let (exec_lo, exec_hi) = (lw.tmp_var(), lw.tmp_var()); + lw.wr(exec_lo, lo); + lw.wr(exec_hi, hi); + let _ = lw.guarded(dispatch_limited, &mut |lw| { + let mut dispatch_live = lw.s.m.i1c(true); + for &(k, limit) in &limits { + let zero = lw.c(0); + let unlimited = lw.cmp(Pred::Eq, limit, zero); + let group = lw.s.group_id(k as u32); + let width = lw.c(cs.threads[k]); + let base = lw.mul(group, width); + let id = lw.add(base, gtid[k]); + let inside = lw.cmp(Pred::ULt, id, limit); + let axis_live = lw.lor(unlimited, inside); + dispatch_live = lw.land(dispatch_live, axis_live); + } + let (dispatch_lo, dispatch_hi) = lw.ballot(dispatch_live); + let old_lo = lw.rd(exec_lo); + let old_hi = lw.rd(exec_hi); + let lo = lw.and(old_lo, dispatch_lo); + let hi = lw.and(old_hi, dispatch_hi); + lw.wr(exec_lo, lo); + lw.wr(exec_hi, hi); + Ok(()) + }); + let (lo, hi) = (lw.rd(exec_lo), lw.rd(exec_hi)); sgpr.insert(126, lo); sgpr.insert(127, hi); let mut vgpr = HashMap::new(); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 31d70ab897..36f60988e5 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -100,7 +100,7 @@ impl Init { } let v = self.first(s, var); let cur = s.m.current_block(); - let before = s.m.set_insert_before_term(false); + let before = s.m.set_insert_before_term(true); s.m.set_block(self.entry); let i32 = s.m.i32(); let p = s.m.alloca(i32, 4); @@ -133,6 +133,7 @@ impl Init { } } let cur = s.m.current_block(); + let before = s.m.set_insert_before_term(true); s.m.set_block(self.entry); self.touched.insert(var); let io = self.io.expect("io"); @@ -146,10 +147,53 @@ impl Init { s.raw_load(io, off, 1)[0] }; s.m.set_block(cur); + s.m.set_insert_before_term(before); v } } +#[cfg(test)] +mod init_tests { + use super::{Init, VAR_BUDGET}; + use crate::gpu::dxil::{container::Stage, shader::Shader}; + use std::collections::{BTreeSet, HashMap}; + + fn after_terminated_entry() -> (Shader, Init) { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let io = s.raw_uav(0, 0); + let entry = s.m.current_block(); + let body = s.m.new_block(); + s.m.br(body); + s.m.set_block(body); + let init = Init { + io: Some(io), + compute: None, + vgpr_base: None, + entry, + touched: BTreeSet::new(), + slots: HashMap::new(), + mem: None, + }; + (s, init) + } + + #[test] + fn lazy_register_load_precedes_an_entry_terminator() { + let (mut s, mut init) = after_terminated_entry(); + let _ = init.first(&mut s, 4); + s.m.ret(); + s.try_finish([1, 1, 1], None).expect("lazy register load after an entry branch"); + } + + #[test] + fn compact_register_slot_precedes_an_entry_terminator() { + let (mut s, mut init) = after_terminated_entry(); + let _ = init.slot(&mut s, VAR_BUDGET); + s.m.ret(); + s.try_finish([1, 1, 1], None).expect("compact register slot after an entry branch"); + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Partner { Present, diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 7d259d55ac..a99bb5a715 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5082,7 +5082,23 @@ impl Em { // waves in the group: a last, partial wave counts (96 threads: 2 of 64) let _ = writeln!(h, " {} = {}u | ((gi / {lanes}u) << 6);", sname(next).unwrap(), (x * y * z).div_ceil(lanes)); } - let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); + h.push_str(" bool xcl_dispatch_limited = false;\n"); + for (k, c) in ["x", "y", "z"].iter().enumerate().filter(|(k, _)| cs.threads[*k] > 1) { + let slot = super::IO_THREAD_LIMIT[k] * 4; + let _ = writeln!(h, " uint xcl_limit_{c} = io.Load({slot}u);\n xcl_dispatch_limited = xcl_dispatch_limited || xcl_limit_{c} != 0u;"); + } + let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0;"); + let _ = writeln!(h, " if (xcl_dispatch_limited) {{\n bool xcl_dispatch_live = true;"); + for (k, c) in ["x", "y", "z"].iter().enumerate().filter(|(k, _)| cs.threads[*k] > 1) { + let group = match remap { + Some((ratio, dim, _)) if dim == k => format!("(gid.{c} / {ratio}u)"), + _ => format!("gid.{c}"), + }; + let threads = cs.threads[k]; + let _ = writeln!(h, " xcl_dispatch_live = xcl_dispatch_live && (xcl_limit_{c} == 0u || {group} * {threads}u + gtid.{c} < xcl_limit_{c});"); + } + let ballot = self.ballot_fn(); + let _ = writeln!(h, " e0 = {ballot}(xcl_dispatch_live);\n }} else {{\n e0 = {ballot}(true);\n }}\n exec_lo = e0.x; exec_hi = e0.y; }}"); for &v in &self.vgprs { let init = match v { 0 => "gtid.x", diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 3a7b0520fb..b888923bd0 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -209,6 +209,11 @@ 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 slots of a `DispatchX` with thread dimensions (flag 0x20): the thread count of each axis +/// when it is not a whole number of groups (0: the last group is whole), so the program can leave +/// the lanes past it out of EXEC. Written by D3D12.X and read by both compute backends. +/// (113 is left for the group-limit slot of #1428.) +pub const IO_THREAD_LIMIT: [usize; 3] = [114, 115, 116]; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index fa695d84a9..9321ea9c74 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1012,13 +1012,19 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { /// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in /// registers. None: not a console compute shader. pub fn compute_user_sgprs(blob: &[u8]) -> Option { + compute_interface(blob).map(|cs| cs.user_sgprs) +} + +/// The dispatch ABI of a console compute program: its user SGPRs and the console's group shape +/// (`numthreads`). None: not a console compute program. +pub fn compute_interface(blob: &[u8]) -> Option { if let Some(f) = fspx(blob) { - return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2).user_sgprs); + return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2)); } let sh = xbox::parse(blob)?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; match interface(blob, &sh, f)? { - Mode::Compute(cs) => Some(cs.user_sgprs), + Mode::Compute(cs) => Some(cs), _ => None, } } @@ -1048,6 +1054,9 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?; let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; + if direct_compute_needs_hlsl(&cs) { + return Err("multidimensional groups need the HLSL console-linear thread reorder".into()); + } let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::fssm_wave64(f, code); @@ -1071,6 +1080,19 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) } +fn direct_compute_needs_hlsl(cs: &super::CsInterface) -> bool { + cs.threads[1] > 1 || cs.threads[2] > 1 +} + +#[cfg(test)] +#[test] +fn direct_compute_routes_multidimensional_thread_groups_to_hlsl() { + let cs = |threads| super::CsInterface { threads, user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 3 }; + assert!(!direct_compute_needs_hlsl(&cs([64, 1, 1]))); + assert!(direct_compute_needs_hlsl(&cs([8, 8, 1]))); + assert!(direct_compute_needs_hlsl(&cs([4, 4, 4]))); +} + /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's /// DXIL to `%TEMP%\xcl-dxil-dump\.dxil` (with `XCL_TRANSLATED_CACHE=0`, so cached /// translations are redone). diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 37fd347cd4..8c264943f0 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5178,10 +5178,19 @@ fn gpu_compute_mode_dispatch_abi() { ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None), ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 9), ("DATA", 11), ("SADDR", 0x7D)], None), ]); - let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); + let opt = on_gpu(Options { mode: Mode::Compute(cs.clone()), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); + let hlsl_dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let split = opt.wave64 && (opt.split_wave64 || runner::split_wave64()); + let direct_dxil = crate::gpu::dxil::kernel::translate_compute( + &p, + crate::gpu::dxil::kernel::KernelOptions { wave64: opt.wave64, split, mem_windows: opt.mem_windows, sampler_base: opt.static_sampler_base }, + &cs, + ) + .unwrap_or_else(|e| panic!("direct DXIL: {e}")) + .dxil; + let dxil = if direct_enabled(&opt) { direct_dxil.clone() } else { hlsl_dxil.clone() }; let (w, h, base) = (32usize, 24usize, 0x100usize); let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -5196,6 +5205,24 @@ fn gpu_compute_mode_dispatch_abi() { assert_eq!(out[at + 1], (px | py << 16) as u32, "({x}, {y}): value of thread {} through LDS", 127 - i); } } + + // DispatchX thread limits seed EXEC in both backends. The hardware groups still contain + // 32x24 threads, but only the 20x17 console dispatch rectangle may reach memory. + for (backend, dxil) in [("HLSL", hlsl_dxil), ("direct DXIL", direct_dxil)] { + let mut limited_io = io.clone(); + limited_io[super::IO_THREAD_LIMIT[0]] = 20; + limited_io[super::IO_THREAD_LIMIT[1]] = 17; + let sentinel = 0xA5A5_5A5Au32; + let out = runner::dispatch(&dxil, [2, 3, 1], &limited_io, &vec![sentinel; (base + w * h * 8) / 4]).unwrap(); + for y in 0..h { + for x in 0..w { + let at = (base + (y * w + x) * 8) / 4; + let written = x < 20 && y < 17; + assert_eq!(out[at] != sentinel, written, "{backend} ({x}, {y}) own write"); + assert_eq!(out[at + 1] != sentinel, written, "{backend} ({x}, {y}) partner write"); + } + } + } } /// A wave32 program in a 64-lane hardware wave (what VS / PS may get from the driver): the @@ -7439,6 +7466,42 @@ fn wave_local_remap_decision_and_console_ids() { assert!(fallback.hlsl.contains("numthreads(128, 1, 1)") && fallback.hlsl.contains("#define XCL_X_SPIN 1")); } +#[test] +fn dispatch_thread_limits_seed_compute_exec_for_native_and_remapped_groups() { + use super::{CsInterface, Mode, Options}; + let p = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 0), ("SADDR", 0x7D)], None), + ]); + let translated = |threads, split_wave64| { + translate( + &p, + &Options { + mode: Mode::Compute(CsInterface { threads, user_sgprs: 2, tgid: [true; 3], tg_size: false, tid_components: 3 }), + wave64: true, + split_wave64, + ..Default::default() + }, + ) + .unwrap() + }; + + let native = translated([8, 8, 1], false); + assert!(native.hlsl.contains("uint xcl_limit_x = io.Load(456u);")); + assert!(native.hlsl.contains("gid.x * 8u + gtid.x < xcl_limit_x")); + assert!(native.hlsl.contains("uint xcl_limit_y = io.Load(460u);")); + assert!(native.hlsl.contains("gid.y * 8u + gtid.y < xcl_limit_y")); + assert!(!native.hlsl.contains("xcl_limit_z"), "a one-thread axis is always whole"); + assert!(native.hlsl.contains("if (xcl_dispatch_limited)")); + assert!(native.hlsl.contains("ballot(xcl_dispatch_live)")); + assert!(native.hlsl.contains("ballot(true)"), "ordinary Dispatch keeps the original entry ballot"); + + let remapped = translated([128, 1, 1], true); + assert_eq!(remapped.dispatch_remap, Some((2, 0))); + assert!(remapped.hlsl.contains("(gid.x / 2u) * 128u + gtid.x < xcl_limit_x")); + assert!(remapped.hlsl.contains("xcl_x_ballot(xcl_dispatch_live)")); +} + /// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64 /// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the /// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32 diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index cdd26ca9bf..02c43da04e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -34,6 +34,9 @@ struct State { uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + /// the next dispatch's thread limits (`IO_THREAD_LIMIT`; a `DispatchX` with thread + /// dimensions), taken by its `bind_abi` + limits: [u32; 3], } static STATES: Mutex>> = Mutex::new(None); @@ -82,6 +85,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.limits = [0; 3]; (old, std::mem::take(&mut s.uma)) }); console_list::hold_until_reset(old, blocks); @@ -906,8 +910,35 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { + dispatch_flags(this, x, y, z, 0); +} + +/// `DispatchX` flag: x, y, z are thread counts, not group counts; the console launches whole +/// groups and leaves the lanes past the count out of EXEC (0x8000, wave32, needs nothing here) +const DISPATCH_THREAD_DIMENSIONS: u32 = 0x20; +const MAX_DISPATCH_GROUPS: u32 = 65_535; + +fn valid_dispatch_grid(groups: [u32; 3]) -> bool { + groups.into_iter().all(|n| n <= MAX_DISPATCH_GROUPS) +} + +/// What a dispatch of `dims` with `flags` launches on pipeline `pso`: its groups and the thread +/// limits for `IO_THREAD_LIMIT` (0: that axis ends on a whole group). None: it cannot be run +/// as the console would (thread dimensions with a group shape not known). +fn dispatch_groups(pso: usize, dims: [u32; 3], flags: u32) -> Option<([u32; 3], [u32; 3])> { + if flags & DISPATCH_THREAD_DIMENSIONS == 0 { + return Some((dims, [0; 3])); + } + let threads = super::real::pso_threads(pso)?.map(|t| t.max(1)); + let groups = std::array::from_fn(|k| dims[k].div_ceil(threads[k])); + let limits = std::array::from_fn(|k| if dims[k] % threads[k] != 0 { dims[k] } else { 0 }); + Some((groups, limits)) +} + +/// `Dispatch` / `DispatchX(x, y, z, flags)`. +pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { let pso = with(this, |s| s.pso); - if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { + if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z, flags)) { return super::pso_async::need_by_submit(pso); } let pso = super::pso_async::resolve_wait(pso); @@ -922,7 +953,34 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, count(DISPATCHES_SKIPPED); return; } - match translated_dispatch(this, list, pso, x, y, z) { + let Some((groups, limits)) = dispatch_groups(pso, [x, y, z], flags) else { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: DispatchX of {x}x{y}x{z} threads (flags {flags:#x}) with a pipeline whose group shape is not known ({pso:#x}) skipped"); + } + count(DISPATCHES_SKIPPED); + return; + }; + if !valid_dispatch_grid(groups) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: Dispatch of {}x{}x{} groups exceeds the PC limit of {MAX_DISPATCH_GROUPS} on one axis and was skipped", groups[0], groups[1], groups[2]); + } + count(DISPATCHES_SKIPPED); + return; + } + if flags != 0 { + // each kind of flags once: what titles pass, and what it launches + static SEEN: Mutex> = Mutex::new(Vec::new()); + let first = { let mut g = SEEN.lock().unwrap(); !g.contains(&flags) && { g.push(flags); true } }; + if first { + crate::xlog_info!("D3D12.X: DispatchX with flags {flags:#x}: {x}x{y}x{z} launched as {}x{}x{} groups (thread limits {limits:?})", groups[0], groups[1], groups[2]); + } + } + with(this, |s| s.limits = limits); + let done = translated_dispatch(this, list, pso, groups[0], groups[1], groups[2]); + with(this, |s| s.limits = [0; 3]); + match done { Ok(()) => count(DISPATCHES), Err(e) => { count(DISPATCHES_SKIPPED); @@ -1075,6 +1133,11 @@ 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; + if !gfx { + for (k, l) in take_dispatch_limits(this).into_iter().enumerate() { + io[crate::gpu::recomp::IO_THREAD_LIMIT[k]] = l; + } + } 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); @@ -1099,6 +1162,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi Ok(()) } +fn take_dispatch_limits(list: *mut c_void) -> [u32; 3] { + with(list, |s| std::mem::take(&mut s.limits)) +} + #[cfg(test)] pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { DRAW_ARGS.with(|d| d.get()) @@ -1476,6 +1543,60 @@ void main(uint t : SV_GroupIndex) { (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); } + /// `DispatchX` with thread dimensions (flag 0x20, as the BVH builder's rehydration passes + /// use it): the console launches whole groups of the pipeline's `numthreads` and leaves + /// the lanes past the count out; without the flag the counts are groups. With the flag + /// and a group shape not known, nothing is launched (the counts as groups was the bug). + #[test] + fn dispatch_x_with_thread_dimensions_launches_whole_groups() { + let pso = 0x7300_0001usize; + real::register_threads_for_test(pso, [64, 1, 1]); + // 640 threads in groups of 64: 10 groups, the last one whole + assert_eq!(dispatch_groups(pso, [640, 1, 1], 0x20), Some(([10, 1, 1], [0, 0, 0]))); + // 100 threads: 2 groups, and the lanes past 100 to leave out + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x20), Some(([2, 1, 1], [100, 0, 0]))); + // the wave32 bit (0x8000) changes nothing here + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x8020), Some(([2, 1, 1], [100, 0, 0]))); + // a 2-D group shape + let pso2 = 0x7300_0002usize; + real::register_threads_for_test(pso2, [8, 8, 1]); + assert_eq!(dispatch_groups(pso2, [20, 16, 3], 0x20), Some(([3, 2, 3], [20, 0, 0]))); + // group counts (Dispatch, DispatchX without the flag) are launched as they are + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0), Some(([7, 2, 1], [0, 0, 0]))); + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0x8000), Some(([7, 2, 1], [0, 0, 0]))); + // no threads: no groups + assert_eq!(dispatch_groups(pso, [0, 1, 1], 0x20), Some(([0, 1, 1], [0, 0, 0]))); + // thread dimensions on a pipeline whose group shape is not known: not launched + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0x20), None); + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0), Some(([100, 1, 1], [0, 0, 0]))); + + let last = MAX_DISPATCH_GROUPS * 64; + let at_limit = dispatch_groups(pso, [last, 1, 1], 0x20).unwrap().0; + let past_limit = dispatch_groups(pso, [last + 1, 1, 1], 0x20).unwrap().0; + assert!(valid_dispatch_grid(at_limit)); + assert!(!valid_dispatch_grid(past_limit)); + for k in 0..3 { + let mut grid = [1; 3]; + grid[k] = MAX_DISPATCH_GROUPS; + assert!(valid_dispatch_grid(grid), "axis {k} at the D3D12 limit"); + grid[k] += 1; + assert!(!valid_dispatch_grid(grid), "axis {k} past the D3D12 limit"); + } + } + + #[test] + fn deferred_dispatch_limits_are_consumed_once_and_reset_with_the_list() { + let list = 0x7301_0001usize as *mut c_void; + with(list, |s| s.limits = [100, 17, 0]); + assert_eq!(take_dispatch_limits(list), [100, 17, 0]); + assert_eq!(take_dispatch_limits(list), [0; 3], "a later ordinary dispatch must not inherit deferred limits"); + + with(list, |s| s.limits = [9, 8, 7]); + reset(list, 0x7301_1000, 0); + assert_eq!(take_dispatch_limits(list), [0; 3], "Reset drops an unconsumed deferred dispatch state"); + forget(list); + } + #[test] fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() { let mut orig_vt = [0usize; 64]; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index fe7a296f52..a67c9b4d56 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -774,7 +774,8 @@ struct ListState { /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. pub(super) enum Deferred { - Dispatch(u32, u32, u32), + /// x, y, z and `DispatchX`'s flags (0 for `Dispatch`) + Dispatch(u32, u32, u32, u32), Indirect(usize, u32, usize, u64, usize, u64), } @@ -3240,7 +3241,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { real::dispatch_chain::list_follows(last as usize, seg as usize); } match what { - Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), + Deferred::Dispatch(x, y, z, flags) => super::bind::dispatch_flags(seg, x, y, z, flags), Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), } let ext = *(seg as *const usize); @@ -3666,8 +3667,8 @@ pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: } /// command list #78 DispatchX(x, y, z, flags) -pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) { - super::bind::dispatch(this, x, y, z); +pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + super::bind::dispatch_flags(this, x, y, z, flags); } /// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH @@ -5982,7 +5983,10 @@ mod tests { fn segment_reasons_keep_the_existing_segment_costs() { assert_eq!(SegmentReason::WaitAfterWrite64.extra_segments(), 1); assert_eq!(SegmentReason::WaitAfterCpuWrite.extra_segments(), 1); - assert_eq!(SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3)).extra_segments(), 2); + let deferred = SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3, 0x8020)); + let SegmentReason::DeferredDispatch(Deferred::Dispatch(x, y, z, flags)) = &deferred else { unreachable!() }; + assert_eq!((*x, *y, *z, *flags), (1, 2, 3, 0x8020), "deferred replay retains DispatchX flags"); + assert_eq!(deferred.extra_segments(), 2); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index dbc016e4b4..a953cc8e72 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3951,15 +3951,27 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { } } -/// user SGPRs of the console CS of a translated compute pipeline -static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); +/// user SGPRs and the console's `numthreads` of the console CS of a translated compute pipeline +static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); static PSO_DISPATCH_REMAP: Mutex>> = Mutex::new(None); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). pub fn pso_user_sgprs(pso: usize) -> Option { let pso = super::pso_async::resolve(pso); - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.0) +} + +/// The console's group shape (`numthreads`) of a translated compute pipeline (None: not known). +pub fn pso_threads(pso: usize) -> Option<[u32; 3]> { + let pso = super::pso_async::resolve(pso); + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.1) +} + +/// (tests) A translated compute pipeline with this console group shape. +#[cfg(test)] +pub(crate) fn register_threads_for_test(pso: usize, threads: [u32; 3]) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, (0, threads)); } pub fn pso_dispatch_remap(pso: usize) -> Option<(u32, u32)> { @@ -4447,8 +4459,8 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const LAST_COMPUTE_RS.with(|c| c.set(rs)); note_pso_rs(*ppv, rs as *mut c_void); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_translated_compute(0, ppv); TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); @@ -4484,8 +4496,8 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_pso_dispatch_remap(*ppv, compiled.dispatch_remap); remap_fallback::note(*ppv as usize, this, f, rs as usize, d.Flags, d.NodeMask, record, cs, diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 8b84548a04..a7fba17f21 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -235,6 +235,9 @@ unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option) -> Option<[u32; 3]> { + if grid.into_iter().any(|n| n > 65_535) { + return None; + } if let Some((ratio, dim)) = remap { let count = grid.get_mut(dim as usize)?; let scaled = count.checked_mul(ratio)?; @@ -251,6 +254,9 @@ fn remapped_grid(mut grid: [u32; 3], remap: Option<(u32, u32)>) -> Option<[u32; /// common to every piece and the whole fallback. Choose before recording any /// part of the dispatch, including when scratch allocation fails. pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, grid: [u32; 3]) -> Result<(), String> { + if grid.into_iter().any(|n| n > 65_535) { + return Err("dispatch group count exceeds 65535 on one axis".into()); + } let [x, y, z] = grid; let chain = CHAINS.lock().unwrap().get(&pso).cloned(); let Some(chain) = chain else { @@ -300,6 +306,10 @@ mod tests { fn remapped_grid_scales_only_its_dimension_and_refuses_overflow() { assert_eq!(remapped_grid([3, 5, 7], Some((4, 1))), Some([3, 20, 7])); assert_eq!(remapped_grid([3, 5, 7], None), Some([3, 5, 7])); + assert_eq!(remapped_grid([65_535, 1, 1], None), Some([65_535, 1, 1])); + assert_eq!(remapped_grid([65_536, 1, 1], None), None); + assert_eq!(remapped_grid([1, 65_536, 1], None), None); + assert_eq!(remapped_grid([1, 1, 65_536], None), None); assert_eq!(remapped_grid([32_768, 1, 1], Some((2, 0))), None); assert_eq!(remapped_grid([u32::MAX, 1, 1], Some((2, 0))), None); assert_eq!(remapped_grid([1, 1, 1], Some((2, 3))), None);