From 1dc3cf5e170ae48532ac0614188e1817c0291464 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:34:29 +0100 Subject: [PATCH 001/175] Recompiler: prefer live lanes in Direct DXIL PS v_readfirstlane and wave64 masks Bring Direct DXIL pixel shaders and wave64 HLSL pixel shaders in line with 6ec402b1 (first_lane_live) and 8fcc1113 (mask_live): - Direct DXIL v_readfirstlane_b32 now calls Lw::first_lane_live, intersecting EXEC with ballot(true) in pixel shaders when any live lane is active so helper-lane zeroing inside loops on AMD drivers cannot spin to LOOP_BUDGET. - Wave64 HLSL pixel shader s_and_b64 / s_andn2_b64 with EXEC or VCC now tests live lanes only via mask_live64, matching mask_live for wave32 pixel loops. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/lanes.rs | 38 +++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_valu.rs | 2 +- crates/xcl/src/gpu/recomp/emit.rs | 18 ++++++++++++- 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index ad59e7e4b5..a327862b97 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -696,6 +696,44 @@ impl Lw { let lnz = self.nz(lo); self.sel(lnz, fl, hv) } + + /// Hardware live-lane ballot (excludes pixel-shader helper lanes, unlike [`Lw::ballot`]). + fn ballot_live(&mut self, cond: Value) -> (Value, Value) { + let w = self.s.wave_ballot(cond); + if !self.wave64 { + let z = self.c(0); + if let Some(h) = self.gfx_half { + return (self.sel(h, w[1], w[0]), z); + } + return (w[0], z); + } + if !self.split { + return (w[0], w[1]); + } + let m = w[0]; + let o = self.exchange(m); + let u = self.upper; + let lo = self.sel(u, o, m); + let hi = self.sel(u, m, o); + (lo, hi) + } + + /// First live lane of (lo, hi) in a pixel shader when EXEC has one, else first set lane + /// (the recompiler's `first_lane_live`: avoids reading helper-lane registers inside PS loops). + pub fn first_lane_live(&mut self, lo: Value, hi: Value) -> Value { + if self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) { + let t = self.s.m.i1c(true); + let (lv_lo, lv_hi) = self.ballot_live(t); + let ml = self.and(lo, lv_lo); + let mh = self.and(hi, lv_hi); + let any = self.or(ml, mh); + let has_live = self.nz(any); + let lo = self.sel(has_live, ml, lo); + let hi = self.sel(has_live, mh, hi); + return self.first_lane(lo, hi); + } + self.first_lane(lo, hi) + } } #[cfg(test)] diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 08e15a5580..a952b8567c 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -991,7 +991,7 @@ impl Lw { } "v_readfirstlane_b32" => { let (el, eh) = self.exec_mask(); - let l = self.first_lane(el, eh); + let l = self.first_lane_live(el, eh); let t = self.read_lane_uniform(a, l); self.write32(&dst, t); return Ok(()); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 91723ebdd2..a75e420228 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1896,7 +1896,15 @@ impl Em { } }; self.line(&format!("uint {t0} = {lo}; uint {t1} = {hi};")); - if let Some(c) = scc { + // "is a lane left" of a 64-bit lane mask (an AND with EXEC or VCC) in a wave64 pixel + // shader: over the live lanes (`mask_live64`), matching `mask_live` for wave32. + let lanes_left = matches!(name, "s_and_b64" | "s_andn2_b64") + && matches!(self.opt.mode, Mode::Pixel(_)) + && d.enc.name == "ENC_SOP2" + && ["SSRC0", "SSRC1", "SDST"].iter().any(|f| matches!(Self::field(d, f), 106 | 126)); + if lanes_left { + self.line(&format!("scc = (uint)(mask_live64({t0}, {t1}) != 0u);")); + } else if let Some(c) = scc { self.line(&format!("scc = (uint)({c});")); } if matches!(name, "s_bcnt0_i32_b64" | "s_bcnt1_i32_b64" | "s_ff0_i32_b64" | "s_ff1_i32_b64" | "s_flbit_i32_b64" | "s_flbit_i32_i64") { @@ -6622,6 +6630,14 @@ uint mask_live(uint m) { #endif return m; } +uint mask_live64(uint lo, uint hi) { +#ifdef XCL_PIXEL + uint2 lv = ballot(true); + lo &= lv.x; + hi &= lv.y; +#endif + return lo | hi; +} uint first_lane_live(uint lo, uint hi) { #ifdef XCL_PIXEL uint2 lv = ballot(true); From e5aa419b31e2a13fd1929a9dd88129ae520a0260 Mon Sep 17 00:00:00 2001 From: Diskuss Date: Wed, 25 Nov 2026 11:18:33 +0100 Subject: [PATCH 002/175] Direct DXIL: fold Countbits of constants (AMD folds Bfrev(Countbits(K)) wrong) amdxc64 on RDNA4 folds Bfrev(Countbits(K)) for a constant K to Bfrev(n) | n (0x80000001 for K = 2). Fold Countbits of constants in bit_count so the driver never sees that pattern. Fixes fuzz seed 1599 on the RX 9070 XT (#2115). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module.rs | 10 ++++++++++ crates/xcl/src/gpu/dxil/ops.rs | 12 +++++++++--- crates/xcl/src/gpu/dxil/ops_tests.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..a7f0128da4 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -417,6 +417,16 @@ impl Module { let sext = if w >= 64 { v as i64 } else { ((v << (64 - w)) as i64) >> (64 - w) }; self.constant(ConstDef::Int(ty, sext)) } + /// The value of an integer constant (sign-extended to 64 bits), if `v` is one. + pub fn int_const(&self, v: Value) -> Option { + match v { + Value::Const(c) => match self.consts[c as usize] { + ConstDef::Int(_, x) => Some(x), + _ => None, + }, + _ => None, + } + } pub fn i32c(&mut self, v: u32) -> Value { let t = self.i32(); self.const_int(t, v as u64) diff --git a/crates/xcl/src/gpu/dxil/ops.rs b/crates/xcl/src/gpu/dxil/ops.rs index cf7d47b145..8c1272bd14 100644 --- a/crates/xcl/src/gpu/dxil/ops.rs +++ b/crates/xcl/src/gpu/dxil/ops.rs @@ -358,12 +358,18 @@ impl Shader { pub fn bit_count(&mut self, op: BitCount, v: Value) -> Value { let t = self.m.type_of(v); let i32 = self.m.i32(); + if let (BitCount::Countbits, Some(x), Some(w)) = (op, self.m.int_const(v), self.m.int_width(t)) { + // Fold `Countbits` of a constant here: AMD's driver (amdxc64, + // RDNA4) folds `Bfrev(Countbits(K))` to `Bfrev(n) | n` (n = + // countbits(K)), e.g. 0x80000001 for K = 2 (fuzz seed 1599, #2115). + let mask = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 }; + return self.m.i32c(((x as u64) & mask).count_ones()); + } if self.is_i64(v) { self.require(Feature::Int64Ops); if matches!(op, BitCount::Countbits) { - // Count each 32-bit half: AMD's driver (amdxc64, RDNA4) gets - // i64 bit ops wrong (see `bfrev`); fuzz seed 1599 reads a wrong - // value downstream of `Countbits.i64(i64 2)` there only. + // Count each 32-bit half: AMD's driver (amdxc64) gets i64 bit + // ops wrong (see `bfrev`). let lo = self.m.cast(CastOp::Trunc, v, i32); let c32 = self.m.const_int(t, 32); let hi = self.m.bin(BinOp::LShr, v, c32); diff --git a/crates/xcl/src/gpu/dxil/ops_tests.rs b/crates/xcl/src/gpu/dxil/ops_tests.rs index 71989884db..f38723bf86 100644 --- a/crates/xcl/src/gpu/dxil/ops_tests.rs +++ b/crates/xcl/src/gpu/dxil/ops_tests.rs @@ -1053,6 +1053,32 @@ fn i1_to_i64_sign_extension_and_shift_match_cpu() { } } +/// `Bfrev(Countbits(K))` with a constant `K`: AMD's driver (amdxc64, RDNA4) +/// folds it to `Bfrev(n) | n` (0x80000001 for K = 2), so `bit_count` folds +/// `Countbits` of constants itself (#2115, fuzz seed 1599). +#[test] +fn bfrev_of_countbits_of_a_constant_matches_cpu() { + let ks: [u64; 6] = [0, 2, 3, 0xF0, 0xFFFF_FFFF, 0x8000_0000_0000_0003]; + let mut k = kernel(); + let (i32, i64) = (k.s.m.i32(), k.s.m.i64()); + let mut outs = vec![]; + for (i, &c) in ks.iter().enumerate() { + let v = if i == ks.len() - 1 { k.s.m.const_int(i64, c) } else { k.s.m.const_int(i32, c) }; + let n = k.s.bit_count(BitCount::Countbits, v); + outs.push(k.s.bfrev(n)); + } + for (i, &o) in outs.iter().enumerate() { + k.out(i as u32, o); + } + let c = k.finish([32, 1, 1]); + let dis = validate::disassemble(&c).unwrap_or_else(|d| d); + assert!(!dis.contains("Countbits(value)"), "Countbits of a constant is folded:\n{dis}"); + let Some(r) = gpu(&c, &mem_of(&[vec![0; 32]]), &[], &[]) else { return }; + for (i, &v) in ks.iter().enumerate() { + assert_eq!(outv(&r, i)[0], v.count_ones().reverse_bits(), "Bfrev(Countbits({v:#x}))"); + } +} + #[test] fn uav_array_3d_stores_loads_and_texture_atomics_run() { // u: heap 3 = RWTexture2DArray 4×4×2, heap 5 = RWTexture3D 4×4×2. From 43d83cf07bdd05f3af5a4ac29abffe9ebc29af41 Mon Sep 17 00:00:00 2001 From: itsSio <31954644+itsSio@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:00:09 +0100 Subject: [PATCH 003/175] Recompiler: Wave32 pixel mask writes kill one SGPR, not a pair In a Wave32 pixel shader a VALU mask write (a carry or compare SDST) and a scalar SAVEEXEC / WREXEC write one dword: write_mask calls write32 when the program is not wave64. The liveness that decides whether a mask needs the helper lanes' quad reads (x64_masks) took its kill sets from the ISA tables, which describe the wave64 pair. So `v_add_co_u32 v3, s20, ...` was taken to overwrite s21 as well; an earlier carry into s21 that `v_bcnt_u32_b32 v4, s21, 0` reads later was taken for a lane-local mask and built with ballot_px_local, and with WQM on its helper lanes' bits were missing at triangle edges (#2584). For Wave32 pixel shaders those writes now kill one dword, and a mask write takes the full ballot when either this liveness or the existing pair rule says its destination can be read whole, so no mask that took the full ballot before loses it. Split wave64 and wave64 pixel shaders keep the pair rule; the direct DXIL path (by_pc) is unchanged. Tests: x64_masks::tests::wave32_carry_into_s20_preserves_a_whole_read_of_s21 and gpu_wave32_pixel_carry_preserves_adjacent_mask_at_triangle_edges, which draws the issue's program on two triangles. Fix and tests by akimfomin (akimfomin/xcl@d3e7725), carried onto main without its README line. Refs xcl-dev/xcl#2584 Co-authored-by: akimfomin Assisted-by: Google Antigravity CLI (Claude Opus 5.5 (High)) --- crates/xcl/src/gpu/recomp/emit.rs | 11 ++-- crates/xcl/src/gpu/recomp/mod.rs | 4 +- crates/xcl/src/gpu/recomp/tests.rs | 39 ++++++++++++++ crates/xcl/src/gpu/recomp/x64_masks.rs | 73 ++++++++++++++++++++++++-- 4 files changed, 115 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index a75e420228..7f08cda47e 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -46,10 +46,9 @@ pub(super) struct Em { /// split wave64 (`x64`): words one exchange carries (1: masks and lane reads, up to 16: /// coherent scalar loads, 32: `ds_bpermute`) x64_words: usize, - /// split wave64 and pixel shaders: pc → SGPRs whose whole value may be read after that - /// instruction (`x64_masks`); a mask written to none of them is only read lane by lane - /// (split: stays in its half, no exchange; pixel: no quad reads for the helper lanes) - pub mask_whole_live: BTreeMap, + /// Mask-producing instruction PC and starting SGPR destinations that require + /// full reconstruction (split-wave exchange or pixel helper quad reads). + pub full_mask_destinations: BTreeMap, /// wave64 VS / PS on a GPU with 32-lane waves only: what the console's lanes 32..63 hold /// where the program reads them (`upper_lanes`), used when the wave has 32 lanes pub upper: Option, @@ -618,7 +617,7 @@ impl Em { uses_lds: false, uses_scratch: false, x64_words: 1, - mask_whole_live: BTreeMap::new(), + full_mask_destinations: BTreeMap::new(), upper: None, cur_pc: 0, static_ss: BTreeMap::new(), @@ -978,7 +977,7 @@ impl Em { // lane (the half's own word, the lane's own bit are enough), that goes nowhere, or that // is 0 in every lane anyway let local = match *dst { - Dst::S(n) => n < 126 && self.mask_whole_live.get(&self.cur_pc).is_some_and(|live| live & (3u128 << n) == 0), + Dst::S(n) => n < 126 && self.full_mask_destinations.get(&self.cur_pc).is_some_and(|live| live & (1u128 << n) == 0), Dst::Null => true, Dst::V(_) => false, }; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index e63624adec..7f876ee9ca 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1689,9 +1689,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // continues from the ES into the GS through s_setpc: left as it is); pixel shaders: they // skip the quad reads that give the helper lanes' bits if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_)) && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { - em.mask_whole_live = x64_masks::by_pc(&insts, matches!(opt.mode, Mode::Kernel)); + em.full_mask_destinations = x64_masks::full_mask_destinations(&insts, matches!(opt.mode, Mode::Kernel), true); } else if matches!(opt.mode, Mode::Pixel(_)) { - em.mask_whole_live = x64_masks::by_pc(&insts, false); + em.full_mask_destinations = x64_masks::full_mask_destinations(&insts, false, opt.wave64); } // a wave64 VS / PS on a GPU that can run 32-lane waves: what lanes 32..63 hold where the // program reads them (the driver may still pick 64 lanes: decided at run time); only a diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index c1d00bf2ae..5573d7ea39 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1823,6 +1823,45 @@ fn el(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gp crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } } +#[test] +fn gpu_wave32_pixel_carry_preserves_adjacent_mask_at_triangle_edges() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + // GFX1030 wave32. Expected green counts the odd lanes of WQM EXEC. Red + // counts the same lanes through s21, after writing the neighboring s20. + let words: &[u32] = &[ + 0xbefe097e, // s_wqm_b32 exec_lo, exec_lo + 0x8706ff7e, 0xaaaaaaaa, // s_and_b32 s6, exec_lo, 0xaaaaaaaa + 0xbe870f06, // s_bcnt1_i32_b32 s7, s6 + 0xd7650002, 0x020100c1, // v_mbcnt_lo_u32_b32 v2, -1, 0 + 0x36040481, // v_and_b32 v2, 1, v2 + 0xd70f1503, 0x020204c1, // v_add_co_u32 v3, s21, -1, v2 + 0xd70f1403, 0x02020480, // v_add_co_u32 v3, s20, 0, v2 + 0xd7640004, 0x02010015, // v_bcnt_u32_b32 v4, s21, 0 + 0x7e080d04, 0x7e0a0c07, 0x7e0c02f2, // convert v4 and s7 to float, set v6 to 1.0 + 0xf800180f, 0x06060504, 0xbf810000, // exp mrt0 v4, v5, v6, v6 done vm; end + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let ps = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 15)], + outputs: vec![el("SV_Target", 0, 64, 3, 0, 15)], input_ena: 0x300, attrs: None }; + let t = translate(&code, &Options { wave64: false, mode: Mode::Pixel(ps), ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let ps = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap(); + let vs = super::dxc::compile("float4 main(float2 p:POSITION):SV_Position { return float4(p,0.5,1); }", + "main", "vs_6_6", &[]).unwrap(); + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let triangles = [-1.,-1., 1.,-1., -1.,1., 1.,-1., 1.,1., -1.,1.]; + let pixels = runner::draw(&vs, &ps, &layout, &triangles, 8, &[], &[], 32, [-99.; 4]).unwrap(); + assert_eq!(pixels.len(), 1024); + for (i, c) in pixels.iter().enumerate() { + assert_eq!((c[2], c[3]), (1., 1.), "raster coverage at {i}"); + assert!((1.0..=16.0).contains(&c[1]), "odd active lanes at {i}: {c:?}"); + assert_eq!(c[0], c[1], "mask popcount at {i}"); + } +} + /// VS + PS pair recompiled to graphics stages and drawn on the GPU: VS inputs from the /// fetch-shader VGPRs, exp pos0/param0, PS interpolation through v_interp, discard via v_cmpx. #[test] diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index cc8b830edd..132625dc20 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -398,7 +398,20 @@ struct Block { has_exit: bool, } -fn whole_live_out_unsorted(insts: &[Decoded], end_reads_all: bool, table: &UsePlanTable) -> Vec { +/// Pixel VALU mask writes and scalar saveexec/wrexec write one dword in +/// XCL's wave32 lowering. The instruction tables describe their wave64 pairs. +/// Dropping a neighboring kill is conservative if two destinations touch. +fn liveness_uses(d: &Decoded, table: &UsePlanTable, wave64: bool) -> (Regs, Regs) { + let (whole, written) = uses_with_table(d, table); + let name = d.inst.name; + if !wave64 && (name.starts_with("V_") || name.contains("SAVEEXEC") || name.contains("WREXEC")) { + (whole, written & !(written << 1)) + } else { + (whole, written) + } +} + +fn whole_live_out_unsorted(insts: &[Decoded], end_reads_all: bool, table: &UsePlanTable, wave64: bool) -> Vec { let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); let at_end = if end_reads_all { ALL } else { EXEC }; let succ: Vec>> = insts @@ -429,7 +442,7 @@ fn whole_live_out_unsorted(insts: &[Decoded], end_reads_all: bool, table: &UsePl .iter() .map(|d| loops.iter().filter(|&&(a, b)| a <= d.pc && d.pc < b).map(|&(_, b)| pcs.range(b..).next().map(|(_, &j)| j)).collect()) .collect(); - let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(|d| uses_with_table(d, table)).collect(); + let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(|d| liveness_uses(d, table, wave64)).collect(); let mut live_in = vec![0 as Regs; insts.len()]; let mut live_out = vec![0 as Regs; insts.len()]; loop { @@ -515,13 +528,17 @@ fn nested_loop_ranges(mut raw: Vec<(u64, u64)>) -> Vec<(u64, u64)> { /// For each instruction (index in `insts`): the SGPRs whose whole value may be read after it. /// `end_reads_all`: the program's end reads every SGPR (kernel mode). pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { + whole_live_out_for_width(insts, end_reads_all, true) +} + +fn whole_live_out_for_width(insts: &[Decoded], end_reads_all: bool, wave64: bool) -> Vec { let n = insts.len(); if n == 0 { return Vec::new(); } let table = use_plans(); if !insts.windows(2).all(|w| w[0].pc < w[1].pc) { - return whole_live_out_unsorted(insts, end_reads_all, table); + return whole_live_out_unsorted(insts, end_reads_all, table, wave64); } let at_end = if end_reads_all { ALL } else { EXEC }; @@ -589,7 +606,7 @@ pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { } let num_blocks = block_starts.len(); - let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(|d| uses_with_table(d, table)).collect(); + let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(|d| liveness_uses(d, table, wave64)).collect(); // Summarize each basic block: because `(X & !k) | X == X` for bitmasks, the constant // per-block `left | EXEC` term collapses out of the intra-block composition into: @@ -743,6 +760,22 @@ pub fn by_pc(insts: &[Decoded], end_reads_all: bool) -> BTreeMap { insts.iter().map(|d| d.pc).zip(whole_live_out(insts, end_reads_all)).collect() } +/// Bit n blocks a local ballot for a mask written at SGPR n. Keep the original +/// pair-wide admission rule. A Wave32 pixel mask also needs the full ballot +/// when its actual single output word can still be observed as a whole. +pub fn full_mask_destinations(insts: &[Decoded], end_reads_all: bool, wave64: bool) -> BTreeMap { + let mut blocked = whole_live_out(insts, end_reads_all); + for bits in &mut blocked { + *bits |= *bits >> 1; + } + if !wave64 { + for (veto, actual) in blocked.iter_mut().zip(whole_live_out_for_width(insts, end_reads_all, false)) { + *veto |= actual; + } + } + insts.iter().map(|d| d.pc).zip(blocked).collect() +} + #[cfg(test)] mod tests { use super::*; @@ -845,6 +878,38 @@ mod tests { const BCNT_S20: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 20)]); const BCNT_VCC: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]); + #[test] + fn wave32_carry_into_s20_preserves_a_whole_read_of_s21() { + let carry = |dst| rdna2::encode("V_ADD_CO_U32", "VOP3_SDST_ENC", + &[("VDST", 3), ("SDST", dst), ("SRC0", 193), ("SRC1", V + 2)], None).unwrap(); + let mut code = carry(21); + code.extend(carry(20)); + code.extend(rdna2::encode("V_BCNT_U32_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 21), ("SRC1", 128)], None).unwrap()); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let p = program(&code); + assert_ne!(full_mask_destinations(&p, false, false)[&p[0].pc] & (1 << 21), 0); + assert_eq!(liveness_uses(&p[1], use_plans(), true).1, 3 << 20); + assert_eq!(liveness_uses(&p[1], use_plans(), false).1, 1 << 20); + + // A neighbor live across a second write to s20 did not observe s20. + // An unconditional branch makes the read a distinct successor block. + let mut other = carry(20); + other.extend(carry(20)); + other.extend(rdna2::encode("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap()); + other.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + other.extend(rdna2::encode("V_BCNT_U32_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 21), ("SRC1", 128)], None).unwrap()); + other.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let q = program(&other); + assert_ne!(whole_live_out_for_width(&q, false, false)[0] & (1 << 21), 0); + let blocked = full_mask_destinations(&q, false, false); + assert_eq!(blocked[&q[0].pc] & (1 << 20), 0); + assert_ne!(blocked[&q[1].pc] & (1 << 20), 0, "retain the original conservative refusal"); + + // An actual scalar pair write still kills both words at either width. + let scalar = asm(&[("S_MOV_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 128)])]); + assert_eq!(liveness_uses(&scalar[0], use_plans(), false).1, 3 << 20); + } + // review findings: writes that are not full overwrites, reads the operand tables miss #[test] From b958a344c983ffcc3ef52707626c021e3d2e29bb Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:12:46 -0700 Subject: [PATCH 004/175] Recompiler: the compact form's larger tables on every GPU again This takes out e964ad2, which kept the table limit of 8,192 words on a GPU with 64-lane waves. It was added after a run on an RX 9070 XT at cbc296a, where neither form of the program it let in built within 24 GB and the compact form reached that sooner. Since #2174 the compact form nests its dispatch by default, and on the same card model with 64 GB that program's nested compact form built in 159 to 203 s at about 34 GB with heap memory windows, where its plain form, which the guard kept, passed 48 GB (komglebissarov on #2088, 1 run per form). With the default switch windows both forms passed 48 GB, so that path does not change. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit b6df9a7f0557b9b289ba41e505f1ff53f4e998a4) Port onto nvidia-dev: the table limit lives in automatic_plan (this branch's form of `wanted`, which also takes split-wave atomic programs), so its `tables` argument goes and it checks MAX_TABLE_WORDS; the `wave32_only` argument of translate_compute_rodata goes the same way. --- crates/xcl/src/gpu/dxil/compact.rs | 8 ++--- crates/xcl/src/gpu/dxil/compact_tests.rs | 44 +++++++---------------- crates/xcl/src/gpu/dxil/kernel.rs | 46 ++++++++++-------------- crates/xcl/src/gpu/recomp/pso.rs | 2 +- 4 files changed, 35 insertions(+), 65 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index b84298be5e..c8bfab774b 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -22,9 +22,7 @@ pub struct Plan { } /// Most 32-bit words of tables a program may need to take the form by itself. -pub const TABLE_WORDS: usize = 8192; -/// `TABLE_WORDS` on a GPU that runs only 32-lane waves. -pub const TABLE_WORDS_WAVE32: usize = 12288; +const MAX_TABLE_WORDS: usize = 12288; impl Plan { /// Bits of a table entry: the class, and the taken successor or the index of the pair of offsets. @@ -48,11 +46,11 @@ pub(super) fn atomic_candidate(cfg: &Cfg) -> bool { }) } -pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool, tables: usize) -> Option { +pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { let large = large(cfg); if !large && !(split_compute && atomic_candidate(cfg)) { return None; } let p = plan(cfg, lw)?; - if p.words() > tables { return None; } + if p.words() > MAX_TABLE_WORDS { return None; } let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); let all: usize = (0..p.order.len()).map(insts).sum(); let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index e0bb2e8935..86d41bfd68 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -181,7 +181,16 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() { assert_ne!(p.class[0], p.class[2]); } -fn two_segments(copies: usize) -> Vec { +#[test] +fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { + if compact_mode().is_some() { + return; + } + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + const COPIES: usize = 8192; let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let mut code = Vec::new(); code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 2)])); @@ -189,48 +198,21 @@ fn two_segments(copies: usize) -> Vec { code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", r), ("SRC0", 256 + r)])); } for marker in [3, 4] { - for k in 0..copies { + for k in 0..COPIES { code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)])); code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 256), ("VSRC1", 1)])); - let offset = (copies - 1 - k) * 3 + 1; + let offset = (COPIES - 1 - k) * 3 + 1; assert!(offset <= i16::MAX as usize); code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", offset as u64)])); } code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", marker), ("SSRC0", 129)])); } code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); - code -} - -#[test] -fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() { - if compact_mode().is_some() { - return; - } - let code = two_segments(8192); - let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; - let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; - let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len(); - let (compact, plain) = (size(true), size(false)); - assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves"); -} - -#[test] -fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { - if compact_mode().is_some() { - return; - } - match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { - (Ok(_), Ok(true), Ok(_)) => {} - (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), - } - const COPIES: usize = 8192; - let code = two_segments(COPIES); let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; let cfg = super::cfg::Cfg::build(&code).unwrap(); let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); - let p = super::compact::automatic_plan(&cfg, &lw, false, super::compact::TABLE_WORDS_WAVE32).unwrap(); + let p = super::compact::automatic_plan(&cfg, &lw, false).unwrap(); assert!(p.inline && p.words() > 8192 && p.words() <= 12288); let k = translate_full(&code, o).unwrap(); for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] { diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 1a638d59f6..a6e9b9322b 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -91,33 +91,33 @@ pub fn compact_nest_tag() -> Option { /// `translate_full` in the compact form (`compact = true`) or the plain one. #[cfg(test)] pub fn translate_full_as(code: &[u8], o: KernelOptions, compact: bool) -> Result { - translate_entry(code, o, Entry::Kernel, Some(compact), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(compact), None) } /// `translate_full` in the compact form with an explicit dispatch nesting policy. #[cfg(test)] pub fn translate_full_nested(code: &[u8], o: KernelOptions, nest: super::compact::Nest) -> Result { - translate_entry(code, o, Entry::Kernel, Some(true), Some(nest), super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(true), Some(nest)) } pub fn translate_full(code: &[u8], o: KernelOptions) -> Result { - translate_entry(code, o, Entry::Kernel, compact_mode(), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, compact_mode(), None) } /// A mesh-mode (NGG) program: the first pass that writes one record per group into /// `res` (the recompiler's `Mode::Mesh`; the pass-through mesh shader draws them). pub fn translate_mesh(code: &[u8], o: KernelOptions, ms: &MsInterface) -> Result { - translate_entry(code, o, Entry::Mesh(ms.clone()), None, None, 0) + translate_entry(code, o, Entry::Mesh(ms.clone()), None, None) } /// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent). pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result { - translate_entry(code, o, Entry::Vertex(vs.clone()), None, None, 0) + translate_entry(code, o, Entry::Vertex(vs.clone()), None, None) } /// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent). pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result { - translate_entry(code, o, Entry::Pixel(ps.clone()), None, None, 0) + translate_entry(code, o, Entry::Pixel(ps.clone()), None, None) } /// A geometry-mode (ES+GS) program: the compute pass that writes one mesh record per @@ -136,7 +136,7 @@ pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Res /// `translate_geometry` without the refusal of the split form's ES phase: the translation /// `XCL_SAFE_BARRIER=0` takes (and what tests of that form check whatever the environment). pub(crate) fn translate_geometry_unrefused(code: &[u8], o: KernelOptions, g: &GsInterface) -> Result { - translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0) + translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None) } /// The entry ABI. @@ -152,18 +152,12 @@ pub enum Entry { /// A compute-mode program (the CS ABI of `cs`). pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result { - translate_compute_on(code, o, cs, true) + translate_compute_rodata(code, o, cs, &[]) } -/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables. -pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool) -> Result { - translate_compute_rodata(code, o, cs, wave32_only, &[]) -} - -/// `translate_compute_on` with the constant data after the program (`translate_entry_rodata`). -pub fn translate_compute_rodata(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool, rodata: &[(u32, Vec)]) -> Result { - let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS }; - translate_entry_with(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables, rodata.to_vec()) +/// `translate_compute` with the constant data after the program (`translate_entry_rodata`). +pub fn translate_compute_rodata(code: &[u8], o: KernelOptions, cs: &CsInterface, rodata: &[(u32, Vec)]) -> Result { + translate_entry_with(code, o, Entry::Compute(cs.clone()), compact_mode(), None, rodata.to_vec()) } fn translate_entry( @@ -172,20 +166,18 @@ fn translate_entry( entry: Entry, compact: Option, nest: Option, - tables: usize, ) -> Result { - translate_entry_with(code, o, entry, compact, nest, tables, Vec::new()) + translate_entry_with(code, o, entry, compact, nest, Vec::new()) } /// A program at `entry` with the constant data the console compiler put after it in the code /// region (`xbox::Fssm::rodata`, the recompiler's `Options::rodata`): `s_getpc_b64` plus the /// compiler's offset is its address, and dword loads at such an address read the table the -/// module carries (`Lw::rodata_loads`). The compact tables as `translate_full` / -/// `translate_compute` take them (a compute program for a GPU with 64-lane waves: -/// `translate_compute_rodata`). +/// module carries (`Lw::rodata_loads`). The compact form as `translate_full` / +/// `translate_compute` take it. pub fn translate_entry_rodata(code: &[u8], o: KernelOptions, entry: Entry, rodata: &[(u32, Vec)]) -> Result { - let (compact, tables) = if matches!(entry, Entry::Kernel | Entry::Compute(_)) { (compact_mode(), super::compact::TABLE_WORDS_WAVE32) } else { (None, 0) }; - translate_entry_with(code, o, entry, compact, None, tables, rodata.to_vec()) + let compact = if matches!(entry, Entry::Kernel | Entry::Compute(_)) { compact_mode() } else { None }; + translate_entry_with(code, o, entry, compact, None, rodata.to_vec()) } fn translate_entry_with( @@ -194,7 +186,6 @@ fn translate_entry_with( entry: Entry, compact: Option, nest: Option, - tables: usize, rodata: Vec<(u32, Vec)>, ) -> Result { // SSA construction recurses along the CFG (one level per guarded memory access between @@ -203,7 +194,7 @@ fn translate_entry_with( std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables, rodata)) + .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, rodata)) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -233,7 +224,6 @@ fn translate_on_this_thread( entry: Entry, compact: Option, nest: Option, - tables: usize, rodata: Vec<(u32, Vec)>, ) -> Result { let geo = match &entry { @@ -327,7 +317,7 @@ fn translate_on_this_thread( _ if !compute && !kernel => None, Some(false) => None, Some(true) => super::compact::plan(&cfg, &lw), - None => super::compact::automatic_plan(&cfg, &lw, compute && split, tables), + None => super::compact::automatic_plan(&cfg, &lw, compute && split), }; if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 1c7c6decd6..70e0bcc5ee 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1092,7 +1092,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, split_wave64, &rodata)?; + let k = crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata)?; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) } From fcbd0d144b8e895770175f664cfa86f55688035e Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:40:56 +0100 Subject: [PATCH 005/175] Recompiler: guard 32-bit raw-buffer OOB wraparound in Direct DXIL In Direct DXIL mubuf and buffer_atomic (stride == 0), off = voff + OFFSET and e = off + bytes were compared against d2 without checking for 32-bit unsigned wraparound (#1893). A large voff near 2^32 wrapped below d2 and passed the OOB guard while 64-bit buffer_window() carried into the adjacent 4 GiB UMA window. Check unsigned carry in pure 32-bit arithmetic (off >= voff when OFFSET != 0, and e >= off) before comparing e <= d2, avoiding i64 promotion while closing the wraparound bypass. Assisted-by: Antigravity (Gemini 4 Neon High) (cherry picked from commit 70e600d5c6a8484ded6174d70cacff2abbedc286) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 17 +++++++++++++++ crates/xcl/src/gpu/dxil/lower_mem.rs | 31 +++++++++++++++++++++------ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 4f0f700ffa..59508c6650 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -1131,6 +1131,23 @@ fn gpu_direct_loads_read_the_constant_data_after_the_program() { } } +#[test] +fn raw_buffer_oob_check_guards_32bit_wraparound() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 2, sampler_base: 0 }; + // Non-zero OFFSET + OFFEN on a raw buffer load/atomic must emit unsigned wraparound checks + // (`icmp uge`) for both `voff + OFFSET` and `off + bytes` (#1893). + let code = prog(&[ + ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 3), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 16)], None), + ("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 16)], None), + ]); + let dxil = translate(&code, ko).expect("mubuf + atomic translates"); + super::validate::validate(&dxil).expect("validates"); + if let Ok(dis) = super::validate::disassemble(&dxil) { + let uge = dis.matches("icmp uge i32").count(); + assert!(uge >= 4, "expected wraparound icmp uge checks for load and atomic (got {uge}):\n{dis}"); + } +} + #[test] fn dot8_u32_u4_unclamped_lowers_to_dot4_add_u8_packed() { use crate::gpu::recomp::{dxc, runner}; diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index b5eafeb578..cb09a73e89 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -1256,18 +1256,29 @@ impl Lw { let voff = if offen { self.vreg(vaddr + idxen as u64) } else { self.c(0) }; let stride = self.lshrc(d1, 16); let stride = self.andc(stride, 0x3FFF); - let off = self.addc(voff, f("OFFSET") as u32); + let imm_off = f("OFFSET") as u32; + let off = self.addc(voff, imm_off); + // 32-bit unsigned add `voff + imm_off` wraps iff `off < voff`; catch wraparound so a + // huge `voff` cannot wrap below `d2` while 64-bit `buffer_window()` carries into the next + // 4 GiB UMA window (#1893). + let off_no_wrap = if imm_off != 0 { Some(self.cmp(Pred::UGe, off, voff)) } else { None }; let a = self.add(d0, soff); let a = self.add(a, off); let si = self.mul(stride, index); let a = self.add(a, si); - self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(f("OFFSET") as u32), Ea::Mul(stride, index)], name.contains("store")); + self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(imm_off), Ea::Mul(stride, index)], name.contains("store")); let act = self.act(); let szero = self.cmpc(Pred::Eq, stride, 0); let idx_ok = self.cmp(Pred::ULt, index, d2); let in_range = |lw: &mut Lw, bytes: Value| -> Value { let e = lw.add(off, bytes); - let ok = lw.cmp(Pred::ULe, e, d2); + let e_no_wrap = lw.cmp(Pred::UGe, e, off); + let in_bounds = lw.cmp(Pred::ULe, e, d2); + let ok = lw.land(e_no_wrap, in_bounds); + let ok = match off_no_wrap { + Some(nw) => lw.land(nw, ok), + None => ok, + }; lw.sel(szero, ok, idx_ok) }; if let Some((n, signed, store, half)) = d16s { @@ -1906,16 +1917,24 @@ impl Lw { let bytes = if x2 { 8 } else { 4 }; let stride = self.lshrc(d1, 16); let stride = self.andc(stride, 0x3FFF); - let off = self.addc(voff, f("OFFSET") as u32); + let imm_off = f("OFFSET") as u32; + let off = self.addc(voff, imm_off); + let off_no_wrap = if imm_off != 0 { Some(self.cmp(Pred::UGe, off, voff)) } else { None }; let a = self.add(d0, soff); let a = self.add(a, off); let si = self.mul(stride, index); let a = self.add(a, si); - self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(f("OFFSET") as u32), Ea::Mul(stride, index)], true); + self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(imm_off), Ea::Mul(stride, index)], true); let a = self.andc(a, !(bytes - 1)); let szero = self.cmpc(Pred::Eq, stride, 0); let e = self.addc(off, bytes); - let r1 = self.cmp(Pred::ULe, e, d2); + let e_no_wrap = self.cmp(Pred::UGe, e, off); + let in_bounds = self.cmp(Pred::ULe, e, d2); + let r1 = self.land(e_no_wrap, in_bounds); + let r1 = match off_no_wrap { + Some(nw) => self.land(nw, r1), + None => r1, + }; let r2 = self.cmp(Pred::ULt, index, d2); let ok = self.sel(szero, r1, r2); let act = self.act(); From aac4343843d99af416fa1a60d6f9b794477c8126 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:41:14 +0100 Subject: [PATCH 006/175] Recompiler: fix Direct DXIL live double-ext scan and movrel VGPR range Fixes two Direct DXIL correctness bugs (#1894, #1890): - Module::uses_double_extensions now iterates live instructions in self.blocks (matching insts_use_type) instead of all self.insts, preventing DCE-removed f64 ops from spuriously setting DoubleExtensions shader flags. - Lw::top_vgpr now incorporates Lw::max_vgpr precomputed across all decoded instructions (init.touched is empty outside Entry::Kernel), and v_movrels / v_movreld / v_movrelsd mask M0 to M0[7:0] (& 0xFF) per RDNA2 ISA. Assisted-by: Antigravity (Gemini 4 Neon High) (cherry picked from commit 2c33f9f2a60dcf3825d04e80e0ed8c9c6632b77f) Port onto nvidia-dev: only `max_vgpr` is added to Lw; the `barrier_uav_fence` field next to it upstream belongs to 85a9480d, which this branch does not have. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 20 ++++++++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 9 +++++++++ crates/xcl/src/gpu/dxil/lower.rs | 2 ++ crates/xcl/src/gpu/dxil/lower_wide.rs | 12 ++++++++---- crates/xcl/src/gpu/dxil/module.rs | 13 ++++++++----- 5 files changed, 47 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 59508c6650..07b49755e2 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -1148,6 +1148,26 @@ fn raw_buffer_oob_check_guards_32bit_wraparound() { } } +#[test] +fn compute_movrel_uses_program_max_vgpr_and_masks_m0() { + use crate::gpu::recomp::CsInterface; + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + // Compute mode (not Entry::Kernel): v_movrels_b32 reading v[1 + (m0 & 0xFF)] when v5 is + // written later in the shader must still include k=4 (v5) in the switch and mask m0 & 0xFF. + let code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 129)], None), + ("V_MOVRELS_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", 256 + 1)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 130)], None), + ]); + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let k = super::kernel::translate_compute(&code, ko, &cs).expect("compute movrel translates"); + super::validate::validate(&k.dxil).expect("validates"); + if let Ok(dis) = super::validate::disassemble(&k.dxil) { + assert!(dis.contains("and i32") && dis.contains(", 255"), "expected m0 & 0xFF mask:\n{dis}"); + assert!(dis.contains("icmp eq i32") && dis.contains(", 4"), "expected k=4 (v5) branch from max_vgpr:\n{dis}"); + } +} + #[test] fn dot8_u32_u4_unclamped_lowers_to_dot4_add_u8_packed() { use crate::gpu::recomp::{dxc, runner}; diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index a6e9b9322b..e9e256ec08 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -605,6 +605,15 @@ impl Lw { track_frexp_denorm: crate::gpu::recomp::emit::tracks_frexp_f32_denorm(insts), has_f64_round_op: false, img_writes: crate::gpu::recomp::emit::image_write_srsrcs(insts), + max_vgpr: insts + .iter() + .flat_map(|d| { + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + r.into_iter().chain(w) + }) + .filter(|&v| v < 256) + .max() + .unwrap_or(0), exec_cache: HashMap::new(), xs: None, xw: None, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 50c94be287..fb18411e1e 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -233,6 +233,8 @@ pub struct Lw { pub has_f64_round_op: bool, /// the T# SGPRs of the program's image stores and atomics (`recomp::emit::image_write_srsrcs`) pub img_writes: Vec, + /// highest VGPR index referenced by the program (for `v_movrel*` outside `Entry::Kernel`) + pub max_vgpr: u64, /// static samplers bound so far: (S#, comparison, handle) at `s, space1` pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>, pub sampler_base: u32, diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index 91f90ffddc..b52981140d 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -280,7 +280,8 @@ impl Lw { /// The highest VGPR the program names (relative moves index up to it). fn top_vgpr(&self) -> u64 { - self.init.touched.iter().filter(|&&v| (VAR_VGPR..VAR_VGPR + 256).contains(&v)).map(|&v| (v - VAR_VGPR) as u64).max().unwrap_or(0) + let touched = self.init.touched.iter().filter(|&&v| (VAR_VGPR..VAR_VGPR + 256).contains(&v)).map(|&v| (v - VAR_VGPR) as u64).max().unwrap_or(0); + touched.max(self.max_vgpr) } pub fn movrel(&mut self, d: &Decoded, name: &str) -> LResult<()> { @@ -292,9 +293,12 @@ impl Lw { let m0 = self.sreg(124); let top = self.top_vgpr().max(vdst).max(src_code.saturating_sub(256)); let (rd_idx, wr_idx) = match name { - "v_movrels_b32" => (Some(m0), None), - "v_movreld_b32" => (None, Some(m0)), - "v_movrelsd_b32" => (Some(m0), Some(m0)), + "v_movrels_b32" => (Some(self.andc(m0, 0xFF)), None), + "v_movreld_b32" => (None, Some(self.andc(m0, 0xFF))), + "v_movrelsd_b32" => { + let m = self.andc(m0, 0xFF); + (Some(m), Some(m)) + } "v_movrelsd_2_b32" => { let r = self.andc(m0, 0x3FF); let w = self.lshrc(m0, 16); diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index a7f0128da4..6b00340eba 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -1426,11 +1426,14 @@ impl Module { /// integers (DXC's shader-flag rules; `Fma` is flagged by its helper). pub fn uses_double_extensions(&self) -> bool { let Some(f64) = self.type_ids.get(&TypeDef::Double).copied() else { return false }; - self.insts.iter().any(|d| match &d.op { - Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, - Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, - Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, - _ => false, + self.blocks.iter().flatten().any(|&i| { + let d = &self.insts[i as usize]; + match &d.op { + Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, + Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, + Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, + _ => false, + } }) } pub fn insts_use_type(&self, t: Ty) -> bool { From 3c54e55893e4090c200b29c5db4707e1b45baeb3 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:04:51 +0100 Subject: [PATCH 007/175] Recompiler: fold constant CFG terminators and recompute live DXIL flags Port #1818's constant-CFG terminator and path-fact folding onto Direct DXIL and fix the stale shader-flag validation gap that blocked it: 1. Resolve CSE and trivial-PHI replacements before CFG folding, propagate dominating branch/switch path facts (bounded to 16 RPO passes so large shaders stay linear), fold constant CondBr/Switch terminators, drop newly unreachable blocks and obsolete PHI edges (preserving loop backedges), and rerun trivial-PHI simplification (opt-out via XCL_DXIL_NO_OPT=cfg). 2. Reconcile Int64Ops, Doubles, DoubleExtensions (including f64 FMA), ResourceHeapIndexing, SamplerHeapIndexing, AtomicInt64*, and TypedUavLoadAdditionalFormats in Shader::infer_type_features() against surviving reachable instructions after optimize(), preventing stale shader flags when dead branches are pruned. Adds unit tests covering constant branches/switches, dominated branch facts, reconvergence, loop PHI backedges, and pruned i64/heap shader flags. Assisted-by: Antigravity (Gemini 4 Neon High) (cherry picked from commit f4b07062383d7a5bfface34fb07ba14c4d6b469d) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module.rs | 39 +++ crates/xcl/src/gpu/dxil/module/opt.rs | 418 +++++++++++++++++++++----- crates/xcl/src/gpu/dxil/shader.rs | 41 ++- 3 files changed, 422 insertions(+), 76 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 6b00340eba..60f4341917 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -1465,6 +1465,45 @@ impl Module { fields.first().and_then(|&p0| self.const_u64(p0)).is_some_and(|w| w & 0x2000 != 0) }) } + /// Scan surviving instructions in reachable blocks for call/atomic features that must stay in + /// sync with DXIL shader flags after optimization/DCE: `(double_fma, res_heap, smp_heap, + /// i64_atomic_gs, i64_atomic_res, uav_tex_load)`. + pub fn live_feature_scan(&self, i64: Option) -> (bool, bool, bool, bool, bool, bool) { + let mut has_double_fma = false; + let mut has_res_heap = false; + let mut has_smp_heap = false; + let mut has_i64_atomic_gs = false; + let mut has_i64_atomic_res = false; + let mut has_uav_tex_load = false; + for &i in self.blocks.iter().flatten() { + let d = &self.insts[i as usize]; + match &d.op { + Op::Call(f, args) => { + let name = self.funcs[*f as usize].name.as_str(); + if name == "dx.op.createHandleFromHeap" && args.len() >= 3 { + if self.const_u64(args[2]) == Some(0) { + has_res_heap = true; + } else { + has_smp_heap = true; + } + } else if name == "dx.op.tertiary.f64" && args.first().and_then(|&a| self.const_u64(a)) == Some(47) { + has_double_fma = true; + } else if matches!(name, "dx.op.atomicBinOp.i64" | "dx.op.atomicCompareExchange.i64") { + has_i64_atomic_res = true; + } else if name.starts_with("dx.op.textureLoad") + && args.get(2).is_some_and(|&mip| matches!(mip, Value::Const(c) if matches!(self.consts[c as usize], ConstDef::Undef(_)))) + { + has_uav_tex_load = true; + } + } + Op::AtomicRmw(..) | Op::CmpXchg(..) if i64 == Some(d.ty) => { + has_i64_atomic_gs = true; + } + _ => {} + } + } + (has_double_fma, has_res_heap, has_smp_heap, has_i64_atomic_gs, has_i64_atomic_res, has_uav_tex_load) + } /// The integer value of a constant (zero-extended from its width). pub fn const_u64(&self, v: Value) -> Option { match v { diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 230a59f9f9..ef37369b34 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -424,14 +424,114 @@ impl Module { idom } + /// Replace phis whose incoming values are only themselves and one other value. Repeat + /// because resolving one phi may make another trivial, including across loop backedges. + fn simplify_phis(&self, order: &[u32], repl: &mut [Option]) { + loop { + let mut changed = false; + for &b in order { + for &i in &self.blocks[b as usize] { + let i = i as usize; + if repl[i].is_some() { + continue; + } + let Op::Phi(inc) = &self.insts[i].op else { break }; + let me = Value::Inst(i as u32); + let mut same: Option = None; + let mut trivial = true; + for &(v, _) in inc { + let v = resolve(repl, v); + if v == me || Some(v) == same { + continue; + } + if same.is_some() { + trivial = false; + break; + } + same = Some(v); + } + if let (true, Some(v)) = (trivial, same) { + repl[i] = Some(v); + changed = true; + } + } + } + if !changed { + break; + } + } + } + + /// Constants established by the control-flow edge that reaches each block. Facts are + /// intersected at joins, so a value is kept only when every incoming edge proves the same + /// value. Bounded to 16 RPO passes so giant shaders stay strictly linear. + fn branch_facts(&self, order: &[u32]) -> Vec> { + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in order { + for s in self.successors(b as usize) { + if !preds[s.0 as usize].contains(&(b as usize)) { + preds[s.0 as usize].push(b as usize); + } + } + } + let mut facts: Vec> = vec![HashMap::new(); self.blocks.len()]; + let max_iters = order.len().min(16); + for _ in 0..=max_iters { + let mut changed = false; + for &b in order.iter().skip(1) { + let b = b as usize; + let mut incoming: Option> = None; + for &p in &preds[b] { + let mut edge = facts[p].clone(); + if let Some(&term) = self.blocks[p].last() { + match &self.insts[term as usize].op { + Op::CondBr(v, t, f) if t != f => { + if t.0 as usize == b { + edge.insert(*v, 1); + } else if f.0 as usize == b { + edge.insert(*v, 0); + } + } + Op::Switch(v, default, cases) if default.0 as usize != b => { + let matching: Vec = cases.iter().filter(|(_, t)| t.0 as usize == b).map(|(c, _)| *c).collect(); + if let [case] = matching.as_slice() { + if let Some(value) = self.const_u64(*case) { + edge.insert(*v, value); + } + } + } + _ => {} + } + } + incoming = Some(match incoming { + None => edge, + Some(mut common) => { + common.retain(|v, value| edge.get(v) == Some(value)); + common + } + }); + } + let next = incoming.unwrap_or_default(); + if facts[b] != next { + facts[b] = next; + changed = true; + } + } + if !changed { + return facts; + } + } + vec![HashMap::new(); self.blocks.len()] + } + /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,cse,cfg,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); - let order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let mut order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); // malformed IR (a use before its definition or of a void result) is left for the // writer to report, not cleaned away if !self.uses_well_formed(&order) { @@ -459,38 +559,8 @@ impl Module { let mut repl: Vec> = vec![None; self.insts.len()]; // trivial phis (all incoming values the phi itself or one value), to a fixed point - while !skip("phi") { - let mut changed = false; - for &b in &order { - for &i in &self.blocks[b as usize] { - let i = i as usize; - if repl[i].is_some() { - continue; - } - let Op::Phi(inc) = &self.insts[i].op else { break }; - let me = Value::Inst(i as u32); - let mut same: Option = None; - let mut trivial = true; - for &(v, _) in inc { - let v = resolve(&mut repl, v); - if v == me || Some(v) == same { - continue; - } - if same.is_some() { - trivial = false; - break; - } - same = Some(v); - } - if let (true, Some(v)) = (trivial, same) { - repl[i] = Some(v); - changed = true; - } - } - } - if !changed { - break; - } + if !skip("phi") { + self.simplify_phis(&order, &mut repl); } // CSE along the dominator tree (preorder walk with a scoped table) @@ -563,47 +633,77 @@ impl Module { } // second trivial-phi fixed point if CSE/simplification collapsed incoming values if cse_replaced && !skip("phi") { - loop { - let mut changed = false; - for &b in &order { - for &i in &self.blocks[b as usize] { - let i = i as usize; - if repl[i].is_some() { - continue; - } - let Op::Phi(inc) = &self.insts[i].op else { break }; - let me = Value::Inst(i as u32); - let mut same: Option = None; - let mut trivial = true; - for &(v, _) in inc { - let v = resolve(&mut repl, v); - if v == me || Some(v) == same { - continue; - } - if same.is_some() { - trivial = false; - break; - } - same = Some(v); - } - if let (true, Some(v)) = (trivial, same) { - repl[i] = Some(v); - changed = true; - } - } - } - if !changed { - break; - } - } + self.simplify_phis(&order, &mut repl); } - // phis may name values defined later (back edges): resolve once more + // phis may name values defined later (back edges): resolve before CFG folding so + // terminators see constants exposed by both CSE and the second trivial-phi pass. for &b in &order { for k in 0..self.blocks[b as usize].len() { let i = self.blocks[b as usize][k] as usize; self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); } } + // CSE, trivial-phi folding, or dominating branches can prove a terminator constant. Fold + // it before DCE, then rebuild reachability and predecessor edges so unreachable blocks and + // obsolete PHI edges are pruned cleanly while preserving loop backedges. + let mut cfg_folded = false; + if !skip("cfg") { + let facts = self.branch_facts(&order); + for &b in &order { + let Some(&i) = self.blocks[b as usize].last() else { continue }; + let replacement = match self.insts[i as usize].op.clone() { + Op::CondBr(c, t, f) => match self.const_u64(c).or_else(|| facts[b as usize].get(&c).copied()) { + Some(0) => Some(Op::Br(f)), + Some(1) => Some(Op::Br(t)), + _ => None, + }, + Op::Switch(v, default, cases) => self.const_u64(v).or_else(|| facts[b as usize].get(&v).copied()).map(|needle| { + let target = cases.iter().find_map(|(case, target)| (self.const_u64(*case) == Some(needle)).then_some(*target)).unwrap_or(default); + Op::Br(target) + }), + _ => None, + }; + if let Some(op) = replacement { + self.insts[i as usize].op = op; + cfg_folded = true; + } + } + } + if cfg_folded { + order = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let mut reach = vec![false; self.blocks.len()]; + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in &order { + reach[b as usize] = true; + for succ in self.successors(b as usize) { + if let Some(p) = preds.get_mut(succ.0 as usize) { + if !p.contains(&b) { + p.push(b); + } + } + } + } + for (b, r) in reach.iter().enumerate() { + if !r { + self.blocks[b].clear(); + } + } + for &b in &order { + for &i in &self.blocks[b as usize] { + let Op::Phi(inc) = &mut self.insts[i as usize].op else { break }; + inc.retain(|p| preds[b as usize].contains(&p.1 .0)); + } + } + if !skip("phi") { + self.simplify_phis(&order, &mut repl); + for &b in &order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); + } + } + } + } // dead instructions: live = side effects, terminators and their operands, transitively let (i64t, f64t) = self.existing_i64_f64(); @@ -1401,4 +1501,186 @@ mod tests { let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); assert!(m.uses_well_formed(&order)); } + + #[test] + fn constant_conditional_removes_edge_and_trivial_phi() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let join = m.new_block(); + let i32 = m.i32(); + let slot = m.alloca(i32, 4); + let one = m.i32c(1); + let cond = m.cmp(Pred::Eq, one, one); + m.cond_br(cond, yes, no); + m.set_block(yes); + let live = m.i32c(7); + m.br(join); + m.set_block(no); + let dead = m.i32c(9); + m.br(join); + m.set_block(join); + let phi = m.phi(i32); + m.add_incoming(phi, live, yes); + m.add_incoming(phi, dead, no); + m.store(slot, phi, 4); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.iter().all(|&b| !m.blocks[b].iter().any(|&i| matches!(m.insts[i as usize].op, Op::CondBr(..))))); + assert!(m.blocks[no.0 as usize].is_empty()); + assert!(!m.blocks[join.0 as usize].iter().any(|&i| matches!(m.insts[i as usize].op, Op::Phi(_)))); + } + + #[test] + fn constant_switch_keeps_only_the_selected_predecessor() { + let mut m = Module::new(); + let default = m.new_block(); + let selected = m.new_block(); + let join = m.new_block(); + let one = m.i32c(1); + let two = m.i32c(2); + let selector = m.bin(BinOp::Add, one, one); + m.switch(selector, default, &[(two, selected)]); + m.set_block(default); + m.br(join); + m.set_block(selected); + m.br(join); + m.set_block(join); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.iter().all(|&b| !m.blocks[b].iter().any(|&i| matches!(m.insts[i as usize].op, Op::Switch(..))))); + assert!(m.blocks[default.0 as usize].is_empty()); + } + + #[test] + fn branch_condition_folds_a_dominated_branch() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let proven = m.new_block(); + let impossible = m.new_block(); + let i1 = m.i1(); + let condition = m.alloca(i1, 1); + let condition = m.load(condition, 1); + m.cond_br(condition, yes, no); + m.set_block(yes); + m.cond_br(condition, proven, impossible); + m.set_block(no); + m.ret(); + m.set_block(proven); + m.ret(); + m.set_block(impossible); + m.ret(); + + m.optimize(); + + assert!(m.blocks[impossible.0 as usize].is_empty()); + assert!(m.blocks[yes.0 as usize] + .iter() + .all(|&i| !matches!(m.insts[i as usize].op, Op::CondBr(..)))); + } + + #[test] + fn branch_condition_is_dropped_when_paths_reconverge() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let join = m.new_block(); + let a = m.new_block(); + let b = m.new_block(); + let i1 = m.i1(); + let condition = m.alloca(i1, 1); + let condition = m.load(condition, 1); + m.cond_br(condition, yes, no); + m.set_block(yes); + m.br(join); + m.set_block(no); + m.br(join); + m.set_block(join); + m.cond_br(condition, a, b); + m.set_block(a); + m.ret(); + m.set_block(b); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.contains(&(a.0 as usize))); + assert!(reachable.contains(&(b.0 as usize))); + assert!(reachable.iter().any(|&block| m.blocks[block] + .iter() + .any(|&i| matches!(m.insts[i as usize].op, Op::CondBr(..))))); + } + + #[test] + fn edge_trim_keeps_a_loop_phi_backedge() { + let mut m = Module::new(); + let entry = m.entry_block(); + let dead = m.new_block(); + let lp = m.new_block(); + let exit = m.new_block(); + let i32 = m.i32(); + let i1 = m.i1(); + let result = m.alloca(i32, 4); + let loop_cond = m.alloca(i1, 1); + let zero = m.i32c(0); + let one = m.i32c(1); + let always = m.cmp(Pred::Eq, one, one); + m.cond_br(always, lp, dead); + m.set_block(dead); + let discarded = m.i32c(99); + m.br(lp); + m.set_block(lp); + let phi = m.phi(i32); + m.add_incoming(phi, zero, entry); + m.add_incoming(phi, discarded, dead); + let next = m.bin(BinOp::Add, phi, one); + m.add_incoming(phi, next, lp); + let again = m.load(loop_cond, 1); + m.cond_br(again, lp, exit); + m.set_block(exit); + m.store(result, phi, 4); + m.ret(); + + m.optimize(); + + assert!(m.blocks[dead.0 as usize].is_empty()); + let incoming = m.phi_incoming(phi); + assert_eq!(incoming.len(), 2); + assert!(incoming.iter().any(|p| p.1 == entry)); + assert!(incoming.iter().any(|p| p.1 == lp)); + } + + #[test] + fn dead_branch_i64_and_heap_handle_do_not_leave_stale_shader_flags() { + use crate::gpu::dxil::container::Stage; + use crate::gpu::dxil::shader::{Feature, Shader}; + let mut s = Shader::new(Stage::Compute, (6, 6)); + let live = s.m.new_block(); + let dead = s.m.new_block(); + let one = s.m.i32c(1); + let cond = s.m.cmp(Pred::Eq, one, one); + s.m.cond_br(cond, live, dead); + s.m.set_block(dead); + let i64 = s.m.i64(); + let z64 = s.m.cast(CastOp::ZExt, one, i64); + let _ = s.m.bin(BinOp::Add, z64, z64); + s.require(Feature::Int64Ops); + let _ = s.handle_from_heap(one, false, false); + s.m.ret(); + s.m.set_block(live); + s.m.ret(); + + s.m.optimize(); + s.infer_type_features(); + assert!(!s.features.contains(&Feature::Int64Ops), "pruned i64 branch must clear Int64Ops"); + assert!(!s.features.contains(&Feature::ResourceHeapIndexing), "pruned heap handle must clear ResourceHeapIndexing"); + } } diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index a0a970925d..266972f30e 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -497,21 +497,46 @@ impl Shader { (Some(node), [cbv, smp, srv, uav].concat()) } - /// Requires the features implied by instruction types alone (`Int64Ops` - /// for any i64, `Doubles` for any double, `DoubleExtensions` for double - /// division and int ↔ double conversions), which the validator derives - /// from the code and demands in the flags even when the IR was built - /// with [`Module`] methods directly rather than the [`Shader`] helpers. + /// Reconciles shader feature flags against the surviving reachable instructions after + /// `optimize()`: adds features implied by instruction types (`Int64Ops`, `Doubles`, + /// `DoubleExtensions`, `Rovs`) and clears flags whose instructions were dead-code-eliminated + /// or folded away in unreachable CFG arms ("Flags must match usage"). pub(super) fn infer_type_features(&mut self) { let (i64, f64) = self.m.existing_i64_f64(); - if i64.is_some_and(|t| self.m.insts_use_type(t)) { + let has_i64 = i64.is_some_and(|t| self.m.insts_use_type(t)); + let has_f64 = f64.is_some_and(|t| self.m.insts_use_type(t)); + if has_i64 { self.require(Feature::Int64Ops); + } else { + self.features.remove(&Feature::Int64Ops); } - if f64.is_some_and(|t| self.m.insts_use_type(t)) { + if has_f64 { self.require(Feature::Doubles); + } else { + self.features.remove(&Feature::Doubles); } - if self.m.uses_double_extensions() { + + let (has_double_fma, has_res_heap, has_smp_heap, has_i64_atomic_gs, has_i64_atomic_res, has_uav_tex_load) = self.m.live_feature_scan(i64); + if has_f64 && (self.m.uses_double_extensions() || has_double_fma) { self.require(Feature::DoubleExtensions); + } else { + self.features.remove(&Feature::DoubleExtensions); + } + if !has_res_heap { + self.features.remove(&Feature::ResourceHeapIndexing); + } + if !has_smp_heap { + self.features.remove(&Feature::SamplerHeapIndexing); + } + if !has_i64_atomic_gs { + self.features.remove(&Feature::AtomicInt64GroupShared); + } + if !has_i64_atomic_res { + self.features.remove(&Feature::AtomicInt64Typed); + self.features.remove(&Feature::AtomicInt64Heap); + } + if !has_uav_tex_load { + self.features.remove(&Feature::TypedUavLoadAdditionalFormats); } if self.bindings.iter().any(|b| b.rov) || self.m.has_rov_handle() { self.require(Feature::Rovs); From f089a9df4d7b3018f1a33578abc5c2ef820038a8 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:35:27 +0100 Subject: [PATCH 008/175] DXIL: shrink emitted shaders 4.5x-5.4x via abbrevs, compact micro-blocks, and IR opts Large console compute shaders previously exceeded 1 MB of DXIL bitcode (>136k instructions, 15k interned table constants, 84 switches) and stalled or OOM-spiked amdxc64 during pipeline creation on AMD RDNA4. - Bitcode encoding (bitstream.rs, module.rs, bitreader_tests.rs): emit LLVM DEFINE_ABBREV records for hot instruction/constant opcodes, emit compact lookup tables via CST_CODE_DATA (ConstDef::DataI32), and prune dead constants in write_bitcode (~6.88 -> 4.31 B/inst). - Compact form (compact.rs, lower.rs, kernel.rs): isolate repeated heavy memory ops (ENC_MUBUF/MTBUF/SMEM/MIMG/FLAT) into standalone micro-blocks, run backward SGPR+SCC liveness to strip dead far-jump veneers and dead SCC/SGPR slot stores, strip pure no-ops and bypass empty non-header jump blocks while preserving fallthroughs, add TargetPool successor encoding, and support single-literal / S_GETPC_B64 parameterization on large shaders. - IR optimization (opt.rs, lanes.rs, prelude.rs, lower_valu.rs, pso.rs): multi-iteration fixed-point optimize() with intra-block scalar alloca store->load forwarding + DSE, entry hoisting of repeated ReadNone system intrinsics (keeping createHandleFromHeap unshared and annotateHandle / getDimensions block-local for AMD RDNA4 amdxc64 stability), dominator branch-fact propagation, adjacent redundant barrier elimination, chained select collapse, constant EXEC lanebit folding, single-instruction f32 IEEE-754 fcmp predicates, XCL_RDNA_FLOAT native op::FRC + mul/fma_legacy constant fast-paths, and XCL_HEAP_WINDOWS default ON. Verified: 201/201 gpu::dxil + gpu_bvh unit/validator/GPU tests pass with 0 dxcompiler 1.8.2502.11 errors; 95cc13288a27a96e shrinks from 1,238 KB (1,036.8 KB w/ heap windows) -> 230.8 KB (236,320 B DXBC, 37.6s amdxc64 compile) and 958400d2caf07244 -> 139.4 KB (142,740 B DXBC, 9.86s compile). Assisted-by: Antigravity (Gemini 4 Neon High) (cherry picked from commit 46aecbf702b1747e1c8e0990a890c1a88fce2989) Port onto nvidia-dev: - XCL_HEAP_WINDOWS stays opt-in (`=1`), as on this branch: the default flip is not part of the size work, and two NVIDIA setups failed with heap windows on. - compact.rs: this branch's automatic_plan (which also takes split-wave atomic programs) counts the micro-blocks the same way `wanted` does upstream, against the new MAX_TABLE_WORDS. - lanes.rs keeps the launch-EXEC shortcut (`live_exec`) before the new constant-mask folds; lower.rs keeps the code region's high word (`code_hi`, constant data after the program) for s_getpc_b64. - opt.rs keeps the test-only XCL_SAMPLE_PHI_CSE arm. - Left out: the test edits for 9c4a9217 (split.rs) and 324193c0 (heap_window_tests.rs), commits this branch does not have. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/bitreader_tests.rs | 75 +- crates/xcl/src/gpu/dxil/bitstream.rs | 141 ++- crates/xcl/src/gpu/dxil/compact.rs | 732 ++++++++++++++-- crates/xcl/src/gpu/dxil/compact_tests.rs | 2 +- crates/xcl/src/gpu/dxil/core_tests.rs | 3 +- crates/xcl/src/gpu/dxil/kernel.rs | 2 + crates/xcl/src/gpu/dxil/lanes.rs | 21 + crates/xcl/src/gpu/dxil/lower.rs | 28 +- crates/xcl/src/gpu/dxil/lower_valu.rs | 25 +- crates/xcl/src/gpu/dxil/module.rs | 250 +++++- crates/xcl/src/gpu/dxil/module/opt.rs | 961 ++++++++++++++++----- crates/xcl/src/gpu/dxil/prelude.rs | 32 + 12 files changed, 1928 insertions(+), 344 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/bitreader_tests.rs b/crates/xcl/src/gpu/dxil/bitreader_tests.rs index b3a7b3dd41..3393060ba4 100644 --- a/crates/xcl/src/gpu/dxil/bitreader_tests.rs +++ b/crates/xcl/src/gpu/dxil/bitreader_tests.rs @@ -1,7 +1,7 @@ //! A test-only reader for the bitstream [`super::bitstream::BitWriter`] -//! produces (unabbreviated records only), used to check record layouts -//! that the validator and disassembler do not distinguish (e.g. atomic -//! ordering codes the LLVM reader maps leniently). +//! produces (both unabbreviated records and `DEFINE_ABBREV` abbreviated records), +//! used to check record layouts that the validator and disassembler do not +//! distinguish (e.g. atomic ordering codes the LLVM reader maps leniently). use super::module::{BinOp, Module, RmwOp}; @@ -12,6 +12,15 @@ pub(super) struct Block { pub blocks: Vec, } +#[derive(Clone, Debug)] +enum AbOp { + Literal(u64), + Fixed(u32), + Vbr(u32), + ArrayFixed(u32), + ArrayVbr(u32), +} + impl Block { /// Depth-first search for the first block with `id`. pub fn find(&self, id: u32) -> Option<&Block> { @@ -57,6 +66,7 @@ impl Reader<'_> { } fn block(&mut self, id: u32, width: u32, end_bit: Option) -> Block { let mut blk = Block { id, ..Default::default() }; + let mut abbrevs: Vec> = Vec::new(); loop { if end_bit.is_none() && self.pos + width as usize > self.b.len() * 8 { return blk; @@ -77,13 +87,70 @@ impl Reader<'_> { let end = self.pos + words * 32; blk.blocks.push(self.block(sub, w, Some(end))); } + 2 => { + let n = self.vbr(5); + let mut ops = Vec::new(); + let mut i = 0; + while i < n { + if self.fixed(1) == 1 { + ops.push(AbOp::Literal(self.vbr(8))); + i += 1; + } else { + match self.fixed(3) { + 1 => { + ops.push(AbOp::Fixed(self.vbr(5) as u32)); + i += 1; + } + 2 => { + ops.push(AbOp::Vbr(self.vbr(5) as u32)); + i += 1; + } + 3 => { + assert_eq!(self.fixed(1), 0, "array element must be encoded"); + match self.fixed(3) { + 1 => ops.push(AbOp::ArrayFixed(self.vbr(5) as u32)), + 2 => ops.push(AbOp::ArrayVbr(self.vbr(5) as u32)), + e => panic!("unsupported array elem encoding {e}"), + } + i += 2; + } + e => panic!("unsupported abbrev encoding {e}"), + } + } + } + abbrevs.push(ops); + } 3 => { let code = self.vbr(6) as u32; let n = self.vbr(6); let ops = (0..n).map(|_| self.vbr(6)).collect(); blk.records.push((code, ops)); } - a => panic!("unexpected abbreviation id {a}"), + a => { + let ab = abbrevs.get((a - 4) as usize).unwrap_or_else(|| panic!("unknown abbreviation id {a}")); + let mut vals = Vec::new(); + for op in ab { + match *op { + AbOp::Literal(v) => vals.push(v), + AbOp::Fixed(w) => vals.push(self.fixed(w)), + AbOp::Vbr(w) => vals.push(self.vbr(w)), + AbOp::ArrayFixed(w) => { + let len = self.vbr(6); + for _ in 0..len { + vals.push(self.fixed(w)); + } + } + AbOp::ArrayVbr(w) => { + let len = self.vbr(6); + for _ in 0..len { + vals.push(self.vbr(w)); + } + } + } + } + let code = vals[0] as u32; + blk.records.push((code, vals[1..].to_vec())); + } } } } diff --git a/crates/xcl/src/gpu/dxil/bitstream.rs b/crates/xcl/src/gpu/dxil/bitstream.rs index 70757093f1..6b23eedd51 100644 --- a/crates/xcl/src/gpu/dxil/bitstream.rs +++ b/crates/xcl/src/gpu/dxil/bitstream.rs @@ -1,21 +1,30 @@ //! LLVM bitstream writer: fixed and VBR fields, nested blocks with -//! back-patched lengths, and unabbreviated records. -//! -//! DXIL accepts the plain bitstream container without any abbreviations, -//! which keeps the writer small; size is not a concern for shader modules -//! (the driver re-encodes them anyway). +//! back-patched lengths, unabbreviated records, and LLVM `DEFINE_ABBREV` +//! abbreviations for compact DXIL encoding. /// Bit-level writer, little-endian within 32-bit words as LLVM defines. pub struct BitWriter { out: Vec, acc: u64, nbits: u32, - /// Open blocks: (byte offset of the length word, outer abbreviation width). - blocks: Vec<(usize, u32)>, + /// Open blocks: (byte offset of the length word, outer abbreviation width, next abbrev id). + blocks: Vec<(usize, u32, u32)>, width: u32, } -/// Abbreviation width used for every block we open (IDs 0..3 need 2 bits). +/// Abbreviation operand encoding for LLVM `DEFINE_ABBREV` records. +#[derive(Clone, Copy, Debug)] +pub enum AbbrevOp { + Literal(u64), + Fixed(u32), + Vbr(u32), + /// Trailing array of fixed-width operands (LLVM `Array` + `Fixed(w)` pair). + ArrayFixed(u32), + /// Trailing array of VBR-encoded operands (LLVM `Array` + `VBR(w)` pair). + ArrayVbr(u32), +} + +/// Abbreviation width used for every block opened via [`BitWriter::enter_block`] (IDs 0..7). pub const ABBREV_WIDTH: u32 = 3; impl Default for BitWriter { @@ -31,7 +40,7 @@ impl BitWriter { pub fn emit(&mut self, value: u64, width: u32) { debug_assert!(width <= 32); - debug_assert!(width == 64 || value >> width == 0, "value {value:#x} does not fit {width} bits"); + debug_assert!(width == 64 || width == 32 || value >> width == 0, "value {value:#x} does not fit {width} bits"); self.acc |= value << self.nbits; self.nbits += width; while self.nbits >= 8 { @@ -60,25 +69,114 @@ impl BitWriter { } pub fn enter_block(&mut self, id: u32) { + self.enter_block_with_width(id, ABBREV_WIDTH); + } + + pub fn enter_block_with_width(&mut self, id: u32, abbrev_width: u32) { self.emit(1, self.width); // ENTER_SUBBLOCK self.vbr(id as u64, 8); - self.vbr(ABBREV_WIDTH as u64, 4); + self.vbr(abbrev_width as u64, 4); self.align32(); let at = self.out.len(); self.out.extend_from_slice(&[0; 4]); - self.blocks.push((at, self.width)); - self.width = ABBREV_WIDTH; + self.blocks.push((at, self.width, 4)); + self.width = abbrev_width; } pub fn end_block(&mut self) { self.emit(0, self.width); // END_BLOCK self.align32(); - let (at, outer) = self.blocks.pop().expect("end_block without enter_block"); + let (at, outer, _) = self.blocks.pop().expect("end_block without enter_block"); let words = ((self.out.len() - at - 4) / 4) as u32; self.out[at..at + 4].copy_from_slice(&words.to_le_bytes()); self.width = outer; } + /// Define a block-local abbreviation (`DEFINE_ABBREV = 2`) and return its ID (`>= 4`). + pub fn define_abbrev(&mut self, ops: &[AbbrevOp]) -> u32 { + let id = { + let top = self.blocks.last_mut().expect("define_abbrev outside block"); + let id = top.2; + top.2 += 1; + id + }; + debug_assert!((id as u64) < (1u64 << self.width), "abbrev id {id} exceeds width {}", self.width); + let num_ops: u64 = ops.iter().map(|o| if matches!(o, AbbrevOp::ArrayFixed(_) | AbbrevOp::ArrayVbr(_)) { 2 } else { 1 }).sum(); + self.emit(2, self.width); // DEFINE_ABBREV + self.vbr(num_ops, 5); + for &op in ops { + match op { + AbbrevOp::Literal(v) => { + self.emit(1, 1); + self.vbr(v, 8); + } + AbbrevOp::Fixed(w) => { + self.emit(0, 1); + self.emit(1, 3); + self.vbr(w as u64, 5); + } + AbbrevOp::Vbr(w) => { + self.emit(0, 1); + self.emit(2, 3); + self.vbr(w as u64, 5); + } + AbbrevOp::ArrayFixed(w) => { + self.emit(0, 1); + self.emit(3, 3); // Array + self.emit(0, 1); + self.emit(1, 3); // Fixed element + self.vbr(w as u64, 5); + } + AbbrevOp::ArrayVbr(w) => { + self.emit(0, 1); + self.emit(3, 3); // Array + self.emit(0, 1); + self.emit(2, 3); // VBR element + self.vbr(w as u64, 5); + } + } + } + id + } + + /// Emit an abbreviated record defined by [`Self::define_abbrev`]. `values` supplies only the + /// non-literal operands in order; if `ops` ends with `ArrayFixed`/`ArrayVbr`, remaining items + /// in `values` form the array payload. + pub fn emit_abbrev(&mut self, id: u32, ops: &[AbbrevOp], values: &[u64]) { + self.emit(id as u64, self.width); + let mut idx = 0usize; + for &op in ops { + match op { + AbbrevOp::Literal(_) => {} + AbbrevOp::Fixed(w) => { + self.emit(values[idx], w); + idx += 1; + } + AbbrevOp::Vbr(w) => { + self.vbr(values[idx], w); + idx += 1; + } + AbbrevOp::ArrayFixed(w) => { + let rest = &values[idx..]; + self.vbr(rest.len() as u64, 6); + for &v in rest { + self.emit(v, w); + } + idx = values.len(); + } + AbbrevOp::ArrayVbr(w) => { + let rest = &values[idx..]; + self.vbr(rest.len() as u64, 6); + for &v in rest { + self.vbr(v, w); + } + idx = values.len(); + } + } + } + debug_assert_eq!(idx, values.len()); + } + /// An unabbreviated record. pub fn record(&mut self, code: u32, ops: &[u64]) { self.emit(3, self.width); // UNABBREV_RECORD @@ -152,4 +250,21 @@ mod tests { assert_eq!(signed(-3), 7); assert_eq!(signed(i64::MIN), 1); } + + #[test] + fn define_abbrev_round_trips_fixed_vbr_and_arrays() { + const AB: &[AbbrevOp] = &[AbbrevOp::Literal(22), AbbrevOp::ArrayFixed(32)]; + let mut w = BitWriter::new(); + for b in [b'B', b'C', 0xC0, 0xDE] { + w.emit(b as u64, 8); + } + w.enter_block_with_width(11, 3); + let id = w.define_abbrev(AB); + assert_eq!(id, 4); + w.emit_abbrev(id, AB, &[0x1234_5678, 0xDEAD_BEEF]); + w.end_block(); + let bc = w.finish(); + assert_eq!(&bc[..4], b"BC\xC0\xDE"); + assert_eq!(bc.len() % 4, 0); + } } diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index c8bfab774b..02ebe198a7 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -1,14 +1,192 @@ //! The compact form: each distinct block of a program lowered once, in a loop over a table. use super::cfg::{Cfg, Term}; -use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET}; +use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET, VAR_SCC}; use super::lower_mem::VAR_TMP; use super::module::{Block, Pred, Value}; use std::collections::{BTreeSet, HashMap}; +const ALL_SGPRS_MASK: u128 = (1u128 << 106) - 1; +const SCC_LIVE_BIT: u128 = 1u128 << VAR_SCC; + +fn is_pure_nop(name: &str) -> bool { + matches!( + name, + "S_NOP" + | "V_NOP" + | "S_WAITCNT" + | "S_WAITCNT_VSCNT" + | "S_WAITCNT_VMCNT" + | "S_WAITCNT_LGKMCNT" + | "S_WAITCNT_EXPCNT" + | "S_WAITCNT_DEPCTR" + | "S_INST_PREFETCH" + | "S_CLAUSE" + ) +} + +/// Conservative `(use_mask, def_mask)` over `s0..s105` (bits `0..106`) and `SCC` (bit `VAR_SCC`). +/// Any register not provably unconditionally overwritten is omitted from `def_mask`; any unknown +/// or indexed SGPR read sets all bits in `use_mask`. +fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded) -> (u128, u128) { + use crate::gpu::rdna2::{field_value, register_scale, Variant}; + if d.inst.name.starts_with("S_MOVREL") { + return (ALL_SGPRS_MASK, 0); + } + let cond_write = d.inst.name == "S_CMOVK_I32"; + let (mut u, mut def) = (0u128, 0u128); + for o in d.ienc.operands { + if o.ty == "OPR_SSRC_SPECIAL_SCC" { + if o.input { + u |= SCC_LIVE_BIT; + } + if o.output { + def |= SCC_LIVE_BIT; + } + continue; + } + let Some(f) = o.field else { continue }; + if f == "LITERAL" || o.implicit { + continue; + } + if !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"].iter().any(|k| o.ty.contains(k)) { + continue; + } + if f == "SRC0" && d.variant != Variant::Plain { + if d.variant == Variant::Sdwa { + let ext = d.words.get(1).copied().unwrap_or(0); + if (ext >> 23) & 1 == 1 { + let code = ext & 0xFF; + if code < 106 { + u |= 1u128 << code; + } else if code == 253 { + u |= SCC_LIVE_BIT; + } + } + } + continue; + } + let Some(raw) = field_value(d.enc, &d.words, f) else { continue }; + let v = raw * register_scale(f); + if v == 253 && o.input { + u |= SCC_LIVE_BIT; + continue; + } + if v >= 106 { + continue; + } + let n = (o.size as u64).div_ceil(32).max(1); + for r in v..(v + n).min(106) { + if o.input || cond_write { + u |= 1u128 << r; + } + if o.output && !cond_write { + def |= 1u128 << r; + } + } + } + (u, def) +} + +fn compute_live_out(cfg: &Cfg, mblocks: &[MicroBlock], end_live: u128) -> Vec { + let n = mblocks.len(); + let mut b_use = vec![0u128; n]; + let mut b_def = vec![0u128; n]; + for (idx, blk) in mblocks.iter().enumerate() { + let (mut u, mut d) = (0u128, 0u128); + for &i in &blk.insts { + let (iu, id) = inst_sreg_scc_use_def(&cfg.insts[i]); + u |= iu & !d; + d |= id; + } + if let Term::Cond(ci, ..) = blk.term { + let (iu, _) = inst_sreg_scc_use_def(&cfg.insts[ci]); + u |= iu & !d; + } + b_use[idx] = u; + b_def[idx] = d; + } + let mut live_in = vec![0u128; n]; + let mut live_out = vec![0u128; n]; + loop { + let mut changed = false; + for idx in (0..n).rev() { + let out = match mblocks[idx].term { + Term::End => end_live, + Term::Jump(t) => if t < n { live_in[t] } else { end_live }, + Term::Cond(_, t, f) => { + let lt = if t < n { live_in[t] } else { end_live }; + let lf = if f < n { live_in[f] } else { end_live }; + lt | lf + } + }; + let inp = b_use[idx] | (out & !b_def[idx]); + if out != live_out[idx] || inp != live_in[idx] { + live_out[idx] = out; + live_in[idx] = inp; + changed = true; + } + } + if !changed { + break; + } + } + live_out +} + +/// If `blk` ends with a 3-instruction far-jump address computation (`s_getpc_b64 s[r:r+1]`, +/// `s_{add,sub}_u32 s[r]`, `s_{addc,subb}_u32 s[r+1]`) feeding a resolved `s_setpc_b64`, +/// return the destination SGPR base `r` (`< 105`) so dead far-jump veneers can be stripped. +fn resolved_far_jump_reg(cfg: &Cfg, blk: &MicroBlock) -> Option { + if !matches!(blk.term, Term::Jump(_)) || blk.insts.len() < 3 { + return None; + } + let len = blk.insts.len(); + let (i0, i1, i2) = (blk.insts[len - 3], blk.insts[len - 2], blk.insts[len - 1]); + if i1 != i0 + 1 || i2 != i1 + 1 { + return None; + } + let set = cfg.insts.get(i2 + 1)?; + if set.inst.name != "S_SETPC_B64" || set.far_target.is_none() { + return None; + } + let (get, lo, hi) = (&cfg.insts[i0], &cfg.insts[i1], &cfg.insts[i2]); + if get.inst.name != "S_GETPC_B64" { + return None; + } + if !matches!((lo.inst.name, hi.inst.name), ("S_ADD_U32", "S_ADDC_U32") | ("S_SUB_U32", "S_SUBB_U32")) { + return None; + } + let r = crate::gpu::rdna2::field_value(get.enc, &get.words, "SDST")?; + (r < 105).then_some(r) +} + +/// One virtual basic block in a compact plan (either a whole guest block or a split micro-block +/// isolating a repeated heavy memory instruction so its lowering is emitted once instead of once +/// per surrounding ALU context). +pub struct MicroBlock { + pub pc: u64, + pub insts: Vec, + pub term: Term, + pub is_header: bool, +} + +/// How the compact table encodes each micro-block's successor target(s). +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum NextEnc { + /// Pair of relative `(taken_off, not_taken_off)` indexed in `xcl_steps`. + Steps, + /// `not_taken = b + 1`; `field` holds the absolute `taken` block number directly. + Inline, + /// `not_taken = b + 1`; `field == 0` means `taken = b + 1`, else `xcl_targets[field - 1]`. + TargetPool, +} + pub struct Plan { - /// the reachable blocks in address order: the loop's block numbers + /// the reachable blocks in address order (same length as `mblocks`) pub order: Vec, + /// virtual blocks executed by the compact loop (targets in `term` are indices into `mblocks`) + pub mblocks: Vec, /// the class of each pub class: Vec, /// a block of each class (a block number) @@ -17,23 +195,45 @@ pub struct Plan { pub next: Vec<(u32, u32)>, /// the distinct pairs of offsets from a block to its two successors, sorted pub steps: Vec<(u32, u32)>, - /// an entry holds the block's taken successor itself; the other one is the next block + /// unique non-fallthrough taken targets for `NextEnc::TargetPool` + pub targets: Vec, + /// successor table encoding mode + pub next_enc: NextEnc, + /// an entry holds the block's taken successor itself (true for `Inline` and `TargetPool`) pub inline: bool, + /// per-block parameterized 32-bit literal when the block has exactly one parameterizable literal + pub blk_lit: Vec>, + /// whether `blk_lit` parameterization is enabled for this plan + pub use_lit: bool, + /// whether `S_GETPC_B64` block-PC parameterization is enabled for this plan + pub use_pc: bool, + /// union of live-out `(s0..s105 | SCC)` bitmasks across all micro-blocks in each class + pub class_live_out: Vec, } /// Most 32-bit words of tables a program may need to take the form by itself. -const MAX_TABLE_WORDS: usize = 12288; +const MAX_TABLE_WORDS: usize = 32768; impl Plan { /// Bits of a table entry: the class, and the taken successor or the index of the pair of offsets. fn widths(&self) -> (u32, u32) { - (bits(self.rep.len()), if self.inline { bits(self.order.len()) } else { bits(self.steps.len()) }) + let pb = match self.next_enc { + NextEnc::Steps => bits(self.steps.len()), + NextEnc::Inline => bits(self.mblocks.len()), + NextEnc::TargetPool => bits(self.targets.len() + 1), + }; + (bits(self.rep.len()), pb) } /// 32-bit words of the tables. pub fn words(&self) -> usize { let (cb, pb) = self.widths(); - (self.order.len() * (cb + pb) as usize).div_ceil(32) + 1 + if self.inline { 0 } else { self.steps.len() * 2 } + let extra = match self.next_enc { + NextEnc::Steps => self.steps.len() * 2, + NextEnc::Inline => 0, + NextEnc::TargetPool => self.targets.len(), + }; + (self.mblocks.len() * (cb + pb) as usize).div_ceil(32) + 1 + extra } } @@ -51,8 +251,8 @@ pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { if !large && !(split_compute && atomic_candidate(cfg)) { return None; } let p = plan(cfg, lw)?; if p.words() > MAX_TABLE_WORDS { return None; } - let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); - let all: usize = (0..p.order.len()).map(insts).sum(); + let insts = |n: usize| p.mblocks[n].insts.len(); + let all: usize = (0..p.mblocks.len()).map(insts).sum(); let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); let repeated = if large { once * 10 < all * 3 } else { p.rep.len() * 4 <= p.order.len() }; repeated.then_some(p) @@ -65,59 +265,374 @@ pub fn large(cfg: &Cfg) -> bool { pub const END: u32 = u32::MAX; +fn is_heavy_mem(d: &crate::gpu::rdna2::Decoded) -> bool { + matches!( + d.enc.name, + "ENC_MUBUF" | "ENC_MTBUF" | "ENC_SMEM" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" + ) && !matches!( + d.inst.name, + "S_DCACHE_INV" + | "S_DCACHE_WB" + | "S_DCACHE_DISCARD" + | "S_DCACHE_DISCARD_X2" + | "S_GL1_INV" + | "S_MEMTIME" + | "S_MEMREALTIME" + ) +} + +/// Whether a micro-block has exactly one parameterizable 32-bit literal instruction. +fn single_param_lit(cfg: &Cfg, blk: &MicroBlock) -> Option { + let mut found = None; + for &i in &blk.insts { + let d = &cfg.insts[i]; + if let Some(lit) = d.literal { + if d.inst.name == "S_SETREG_IMM32_B32" || d.enc.name == "ENC_MIMG" || found.is_some() { + return None; + } + found = Some(lit); + } + } + found +} + /// Sorts the reachable blocks into classes the lowering would emit the same for. +/// On large shaders, repeated heavy memory instructions (appearing `>= 4` times) are split +/// into standalone micro-blocks so each unique buffer/SMEM/image lowering is emitted once +/// instead of once per surrounding ALU context. pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { - let mut order = cfg.rpo.clone(); - order.sort_by_key(|&b| (cfg.blocks[b].pc, b)); - let mut number = vec![END; cfg.blocks.len()]; - for (n, &b) in order.iter().enumerate() { - number[b] = n as u32; + let mut orig_order = cfg.rpo.clone(); + orig_order.sort_by_key(|&b| (cfg.blocks[b].pc, b)); + + // Count exact heavy-memory instruction occurrences across reachable blocks. + let mut mem_counts: HashMap<(Vec, Option, Option<[u32; 4]>), usize> = HashMap::new(); + let allow_split = orig_order.len() >= 64; + if allow_split { + for &b in &orig_order { + for &i in &cfg.blocks[b].insts { + let d = &cfg.insts[i]; + if is_heavy_mem(d) { + let sampler = lw.static_samplers.get(&d.pc).copied(); + *mem_counts.entry((d.words.clone(), d.literal, sampler)).or_insert(0) += 1; + } + } + } } - let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); - let (mut class, mut rep, mut next) = (Vec::new(), Vec::new(), Vec::new()); - let mut falls = true; - for (n, &b) in order.iter().enumerate() { + + // Pass 1: split blocks around repeated heavy memory ops (`>= 4` occurrences). + let mut segs_per_orig: Vec<(usize, Vec>)> = Vec::with_capacity(orig_order.len()); + let mut orig_to_mb = vec![END; cfg.blocks.len()]; + let mut mb_cursor = 0u32; + for &b in &orig_order { let blk = &cfg.blocks[b]; - let mut key = vec![cfg.headers.contains(&b) as u64]; - for &i in &blk.insts { - let d = &cfg.insts[i]; - key.push(d.words.len() as u64); - key.extend(d.words.iter().map(|&w| w as u64)); - key.push(d.literal.map_or(u64::MAX, |l| l as u64)); - let sampler = lw.static_samplers.get(&d.pc); - key.push(sampler.is_some() as u64); - key.extend(sampler.into_iter().flatten().map(|&w| w as u64)); - // what `Lw::write_mask` asks of this address, for any register a mask can go to - if let Some(&l) = lw.whole_live.get(&d.pc) { - let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST")); - let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); - key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); + let mut segs: Vec> = Vec::new(); + if allow_split && blk.insts.len() > 1 { + let mut cur: Vec = Vec::new(); + for &i in &blk.insts { + let d = &cfg.insts[i]; + let isolate = is_heavy_mem(d) + && mem_counts + .get(&(d.words.clone(), d.literal, lw.static_samplers.get(&d.pc).copied())) + .copied() + .unwrap_or(0) + >= 2; + if isolate { + if !cur.is_empty() { + segs.push(std::mem::take(&mut cur)); + } + segs.push(vec![i]); + } else { + cur.push(i); + } } - if d.inst.name == "S_GETPC_B64" { - key.push(d.pc); + if !cur.is_empty() { + segs.push(cur); } } - let (end, to) = match blk.term { - Term::End => ("end", (END, END)), - Term::Jump(t) => ("jump", (number[t], number[t])), - Term::Cond(i, t, f) => { - falls &= number[f] == n as u32 + 1; - (cfg.insts[i].inst.name, (number[t], number[f])) + if segs.is_empty() { + segs.push(blk.insts.clone()); + } + orig_to_mb[b] = mb_cursor; + mb_cursor += segs.len() as u32; + segs_per_orig.push((b, segs)); + } + + // Pass 2: materialize micro-blocks with remapped successor targets (stripping pure no-ops). + let mut order: Vec = Vec::with_capacity(mb_cursor as usize); + let mut mblocks: Vec = Vec::with_capacity(mb_cursor as usize); + for (orig_b, segs) in segs_per_orig { + let blk = &cfg.blocks[orig_b]; + let is_hdr = cfg.headers.contains(&orig_b); + let n_segs = segs.len(); + for (s, raw_insts) in segs.into_iter().enumerate() { + let my_id = mblocks.len(); + let pc = raw_insts.first().map_or(blk.pc, |&i| cfg.insts[i].pc); + let insts = if allow_split { + raw_insts.into_iter().filter(|&i| !is_pure_nop(cfg.insts[i].inst.name)).collect() + } else { + raw_insts + }; + let term = if s + 1 < n_segs { + Term::Jump(my_id + 1) + } else { + match blk.term { + Term::End => Term::End, + Term::Jump(t) => Term::Jump(orig_to_mb[t] as usize), + Term::Cond(ci, t, f) => Term::Cond(ci, orig_to_mb[t] as usize, orig_to_mb[f] as usize), + } + }; + order.push(orig_b); + mblocks.push(MicroBlock { pc, insts, term, is_header: s == 0 && is_hdr }); + } + } + + // Pass 3 (large shaders): strip dead far-jump veneers (`s_getpc_b64 + s_add_u32 + s_addc_u32` + // feeding a resolved `s_setpc_b64` when `s[r:r+1]` and `SCC` are dead at the jump target) and + // bypass empty non-header jump blocks so neither `xcl_blocks` nor `FUNCTION` pays for them. + let end_live = if lw.res.is_some() { ALL_SGPRS_MASK | SCC_LIVE_BIT } else { 0 }; + if allow_split { + let live_out = compute_live_out(cfg, &mblocks, end_live); + for (idx, blk) in mblocks.iter_mut().enumerate() { + if let Some(r) = resolved_far_jump_reg(cfg, blk) { + let clobber = (1u128 << r) | (1u128 << (r + 1)) | SCC_LIVE_BIT; + if (live_out[idx] & clobber) == 0 { + let new_len = blk.insts.len() - 3; + blk.insts.truncate(new_len); + } } - }; - let fresh = ids.len() as u32; - let c = *ids.entry((key, end)).or_insert(fresh); - if c == fresh { - rep.push(n); } - class.push(c); - next.push(to); + // Bypass empty non-header jump micro-blocks (entry 0 stays pinned at 0). + // Preserve `falls` (`Term::Cond` fallthrough `f == idx + 1`) by not bypassing a + // fallthrough block whose jump goes anywhere other than `cur + 1`. + let n_mb = mblocks.len(); + let mut is_fallthrough = vec![false; n_mb]; + for (idx, blk) in mblocks.iter().enumerate() { + if let Term::Cond(_, _, f) = blk.term { + if f == idx + 1 && f < n_mb { + is_fallthrough[f] = true; + } + } + } + let mut redir: Vec = (0..n_mb).collect(); + for start in 1..n_mb { + let mut cur = start; + let mut ft = is_fallthrough[start]; + for _ in 0..64 { + if cur == 0 || mblocks[cur].is_header || !mblocks[cur].insts.is_empty() { + break; + } + match mblocks[cur].term { + Term::Jump(t) if t < n_mb && t != cur => { + if ft && t != cur + 1 { + break; + } + cur = t; + ft |= is_fallthrough[cur]; + } + _ => break, + } + } + redir[start] = cur; + } + for blk in &mut mblocks { + match &mut blk.term { + Term::Jump(t) if *t < n_mb => *t = redir[*t], + Term::Cond(_, t, f) => { + if *t < n_mb { + *t = redir[*t]; + } + if *f < n_mb { + *f = redir[*f]; + } + } + _ => {} + } + if let Term::Cond(_, t, f) = blk.term { + if t == f { + blk.term = Term::Jump(t); + } + } + } + // Compact out bypassed/unreachable micro-blocks. + let mut reach = vec![false; n_mb]; + let mut stack = vec![0usize]; + reach[0] = true; + while let Some(u) = stack.pop() { + match mblocks[u].term { + Term::Jump(t) if t < n_mb && !reach[t] => { + reach[t] = true; + stack.push(t); + } + Term::Cond(_, t, f) => { + if t < n_mb && !reach[t] { + reach[t] = true; + stack.push(t); + } + if f < n_mb && !reach[f] { + reach[f] = true; + stack.push(f); + } + } + _ => {} + } + } + let mut remap = vec![END as usize; n_mb]; + let mut new_order = Vec::with_capacity(n_mb); + let mut new_mblocks = Vec::with_capacity(n_mb); + for (i, (orig_b, blk)) in order.into_iter().zip(mblocks.into_iter()).enumerate() { + if reach[i] { + remap[i] = new_mblocks.len(); + new_order.push(orig_b); + new_mblocks.push(blk); + } + } + for blk in &mut new_mblocks { + match &mut blk.term { + Term::Jump(t) if *t < n_mb => *t = remap[*t], + Term::Cond(_, t, f) => { + if *t < n_mb { + *t = remap[*t]; + } + if *f < n_mb { + *f = remap[*f]; + } + } + _ => {} + } + } + order = new_order; + mblocks = new_mblocks; + } + + let final_live_out = if allow_split { + compute_live_out(cfg, &mblocks, end_live) + } else { + vec![ALL_SGPRS_MASK | SCC_LIVE_BIT; mblocks.len()] + }; + + let build = |param_lit: bool, param_pc: bool| { + let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); + let (mut class, mut rep, mut next, mut blk_lit) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut falls = true; + for (n, blk) in mblocks.iter().enumerate() { + let p_lit = if param_lit { single_param_lit(cfg, blk) } else { None }; + blk_lit.push(p_lit); + let mut key = vec![blk.is_header as u64, p_lit.is_some() as u64]; + for &i in &blk.insts { + let d = &cfg.insts[i]; + let mask_lit = p_lit.is_some() && d.literal.is_some(); + let words = if mask_lit { &d.words[..d.words.len() - 1] } else { &d.words[..] }; + key.push(d.words.len() as u64); + key.extend(words.iter().map(|&w| w as u64)); + if mask_lit { + key.push(u64::MAX - 1); + } else { + key.push(d.literal.map_or(u64::MAX, |l| l as u64)); + } + let sampler = lw.static_samplers.get(&d.pc); + key.push(sampler.is_some() as u64); + key.extend(sampler.into_iter().flatten().map(|&w| w as u64)); + // what `Lw::write_mask` asks of this address, for any register a mask can go to + if let Some(&l) = lw.whole_live.get(&d.pc) { + let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST")); + let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); + key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); + } + if d.inst.name == "S_GETPC_B64" { + key.push(if param_pc { d.pc.wrapping_sub(blk.pc) } else { d.pc }); + } + } + let (end, to) = match blk.term { + Term::End => ("end", (END, END)), + Term::Jump(t) => ("jump", (t as u32, t as u32)), + Term::Cond(i, t, f) => { + falls &= f == n + 1; + (cfg.insts[i].inst.name, (t as u32, f as u32)) + } + }; + let fresh = ids.len() as u32; + let c = *ids.entry((key, end)).or_insert(fresh); + if c == fresh { + rep.push(n); + } + class.push(c); + next.push(to); + } + (class, rep, next, blk_lit, falls) + }; + let base = build(false, false); + let has_getpc = allow_split && mblocks.iter().any(|blk| blk.insts.iter().any(|&i| cfg.insts[i].inst.name == "S_GETPC_B64")); + // Parameterize single-literal blocks (and S_GETPC_B64 when present) on large shaders only + // when the collapsed switch arms outweigh the packed lookup tables (`~2 B/block` per table). + let (use_lit, use_pc, (class, rep, next, blk_lit, falls)) = if allow_split { + let cand = build(true, has_getpc); + let saved_both = base.1.len().saturating_sub(cand.1.len()); + let table_cost = mblocks.len() * if has_getpc { 4 } else { 2 }; + if saved_both >= 64 && saved_both * 60 > table_cost { + let only_lit = if has_getpc { build(true, false) } else { cand.clone() }; + let saved_pc = only_lit.1.len().saturating_sub(cand.1.len()); + if has_getpc && saved_pc >= 64 && saved_pc * 60 > mblocks.len() * 2 { + (true, true, cand) + } else if base.1.len().saturating_sub(only_lit.1.len()) >= 64 + && base.1.len().saturating_sub(only_lit.1.len()) * 60 > mblocks.len() * 2 + { + (true, false, only_lit) + } else { + (false, false, base) + } + } else { + (false, false, base) + } + } else { + (false, false, base) + }; + let mut class_live_out = vec![0u128; rep.len()]; + for (mb_idx, &c) in class.iter().enumerate() { + class_live_out[c as usize] |= final_live_out[mb_idx]; } let steps: BTreeSet<(u32, u32)> = next.iter().enumerate().map(|(b, &to)| offsets(b, to)).collect(); - let mut p = Plan { order, class, rep, next, steps: steps.into_iter().collect(), inline: false }; - let pairs = p.words(); - p.inline = falls; - p.inline = falls && p.words() < pairs; + let targets: Vec = if falls { + let set: BTreeSet = next + .iter() + .enumerate() + .filter_map(|(b, &(t, _))| (t != END && t != b as u32 + 1).then_some(t)) + .collect(); + set.into_iter().collect() + } else { + Vec::new() + }; + let mut p = Plan { + order, + mblocks, + class, + rep, + next, + steps: steps.into_iter().collect(), + targets, + next_enc: NextEnc::Steps, + inline: false, + blk_lit, + use_lit, + use_pc, + class_live_out, + }; + let mut best_enc = NextEnc::Steps; + let mut best_words = p.words(); + if falls { + for cand_enc in [NextEnc::Inline, NextEnc::TargetPool] { + if cand_enc == NextEnc::TargetPool && p.targets.is_empty() { + continue; + } + p.next_enc = cand_enc; + let (cb, pb) = p.widths(); + if cb + pb <= 32 && p.words() < best_words { + best_words = p.words(); + best_enc = cand_enc; + } + } + } + p.next_enc = best_enc; + p.inline = matches!(best_enc, NextEnc::Inline | NextEnc::TargetPool); let (cb, pb) = p.widths(); (cb + pb <= 32).then_some(p) } @@ -131,12 +646,12 @@ fn bits(n: usize) -> u32 { (usize::BITS - n.saturating_sub(1).leading_zeros()).max(1) } -/// A constant table of 32-bit words. +/// A constant table of 32-bit words (emitted via LLVM `CST_CODE_DATA` without interning +/// each element as an individual `CST_CODE_INTEGER` constant). fn table(lw: &mut Lw, name: &str, words: &[u32]) -> Value { - let vals: Vec = words.iter().map(|&w| lw.c(w)).collect(); let i32 = lw.s.m.i32(); let at = lw.s.m.array(words.len() as u64, i32); - let init = lw.s.m.aggregate(at, &vals); + let init = lw.s.m.const_data_i32(words); lw.s.m.global(name, at, 0, Some(init), true, 4) } @@ -220,10 +735,13 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let width = cb + pb; let mut packed = vec![0u32; (n * width as usize).div_ceil(32) + 1]; for (b, &to) in p.next.iter().enumerate() { - let field = match (p.inline, to.0) { - (true, END) => 0, - (true, t) => t, - _ => p.steps.binary_search(&offsets(b, to)).expect("a pair of the plan") as u32, + let field = match (p.next_enc, to.0) { + (NextEnc::Inline, END) => 0, + (NextEnc::Inline, t) => t, + (NextEnc::TargetPool, END) => 0, + (NextEnc::TargetPool, t) if t == b as u32 + 1 => 0, + (NextEnc::TargetPool, t) => p.targets.binary_search(&t).expect("target in pool") as u32 + 1, + (NextEnc::Steps, _) => p.steps.binary_search(&offsets(b, to)).expect("a pair of the plan") as u32, }; let e = (p.class[b] | field << cb) as u64; let at = b * width as usize; @@ -232,7 +750,44 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block } let blocks = table(lw, "xcl_blocks", &packed); let steps: Vec = p.steps.iter().flat_map(|&(t, f)| [t, f]).collect(); - let steps = (!p.inline).then(|| table(lw, "xcl_steps", &steps)); + let steps = (p.next_enc == NextEnc::Steps).then(|| table(lw, "xcl_steps", &steps)); + let target_pool = (p.next_enc == NextEnc::TargetPool).then(|| table(lw, "xcl_targets", &p.targets)); + let pc_table = p.use_pc.then(|| { + let max_pc_dw = p.mblocks.iter().map(|blk| (blk.pc >> 2) as usize).max().unwrap_or(0); + let pc_w = bits(max_pc_dw + 1).min(32); + let mut pc_packed = vec![0u32; (n * pc_w as usize).div_ceil(32) + 1]; + for (b, blk) in p.mblocks.iter().enumerate() { + let v = (blk.pc >> 2) as u64; + let at = b * pc_w as usize; + pc_packed[at / 32] |= (v << (at % 32)) as u32; + pc_packed[at / 32 + 1] |= (v << (at % 32) >> 32) as u32; + } + (table(lw, "xcl_pc", &pc_packed), pc_w) + }); + let lit_table = p.use_lit.then(|| { + // Deduplicate unique 32-bit literals into a pool and bit-pack pool indices per block. + let mut pool: Vec = vec![0]; + let mut idx_map: HashMap = HashMap::from([(0, 0)]); + let mut blk_idx: Vec = Vec::with_capacity(n); + for &opt in &p.blk_lit { + let val = opt.unwrap_or(0); + let idx = *idx_map.entry(val).or_insert_with(|| { + let id = pool.len() as u32; + pool.push(val); + id + }); + blk_idx.push(idx); + } + let lit_w = bits(pool.len()).min(32); + let mut idx_packed = vec![0u32; (n * lit_w as usize).div_ceil(32) + 1]; + for (b, &id) in blk_idx.iter().enumerate() { + let v = id as u64; + let at = b * lit_w as usize; + idx_packed[at / 32] |= (v << (at % 32)) as u32; + idx_packed[at / 32 + 1] |= (v << (at % 32) >> 32) as u32; + } + (table(lw, "xcl_lit_idx", &idx_packed), table(lw, "xcl_lit_pool", &pool), lit_w) + }); let (at, to) = (lw.tmp_var(), lw.tmp_var()); let (at, to, budget) = (slot(lw, at), slot(lw, to), slot(lw, VAR_BUDGET)); @@ -254,12 +809,61 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let class = lw.andc(e, (1u32 << cb) - 1); let field = lw.lshrc(e, cb); let field = lw.andc(field, (1u32 << pb) - 1); + let blk_pc = pc_table.map(|(pc_tbl, pc_w)| { + let pm = if pc_w == 32 { + word(lw, pc_tbl, b) + } else { + let pw = lw.c(pc_w); + let pbit = lw.mul(b, pw); + let pi = lw.lshrc(pbit, 5); + let psh = lw.andc(pbit, 31); + let plo = word(lw, pc_tbl, pi); + let pi1 = lw.addc(pi, 1); + let phi = word(lw, pc_tbl, pi1); + let plo = lw.lshr(plo, psh); + let phi = lw.shlc(phi, 1); + let pup = lw.sub(k31, psh); + let phi = lw.shl(phi, pup); + let pe = lw.or(plo, phi); + lw.andc(pe, (1u32 << pc_w) - 1) + }; + lw.shlc(pm, 2) + }); + let blk_lit_val = lit_table.map(|(idx_tbl, pool_tbl, lit_w)| { + let id = if lit_w == 32 { + word(lw, idx_tbl, b) + } else { + let lw_c = lw.c(lit_w); + let lbit = lw.mul(b, lw_c); + let li = lw.lshrc(lbit, 5); + let lsh = lw.andc(lbit, 31); + let llo = word(lw, idx_tbl, li); + let li1 = lw.addc(li, 1); + let lhi = word(lw, idx_tbl, li1); + let llo = lw.lshr(llo, lsh); + let lhi = lw.shlc(lhi, 1); + let lup = lw.sub(k31, lsh); + let lhi = lw.shl(lhi, lup); + let le = lw.or(llo, lhi); + lw.andc(le, (1u32 << lit_w) - 1) + }; + word(lw, pool_tbl, id) + }); let (taken, not_taken) = if let Some(steps) = steps { let pi = lw.shlc(field, 1); let step_t = word(lw, steps, pi); let pi1 = lw.addc(pi, 1); let step_f = word(lw, steps, pi1); (lw.add(b, step_t), lw.add(b, step_f)) + } else if let Some(target_tbl) = target_pool { + let next_b = lw.addc(b, 1); + let is_fall = lw.cmpc(Pred::Eq, field, 0); + let one = lw.c(1); + let tidx = lw.sub(field, one); + let z = lw.c(0); + let safe_tidx = lw.sel(is_fall, z, tidx); + let pooled = word(lw, target_tbl, safe_tidx); + (lw.sel(is_fall, next_b, pooled), next_b) } else { (field, lw.addc(b, 1)) }; @@ -296,8 +900,8 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.s.m.set_block(c); lw.init.mem = Some(c); lw.ssa.begin_log(); - let blk = &cfg.blocks[p.order[r]]; - if cfg.headers.contains(&p.order[r]) { + let blk = &p.mblocks[r]; + if blk.is_header { // a loop head spends the loop budget let left = lw.s.m.load(budget, 4); let none = lw.cmpc(Pred::Eq, left, 0); @@ -312,9 +916,13 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let l = lw.sub(left, one); lw.s.m.store(budget, l, 4); } + lw.compact_blk_pc = blk_pc.map(|v| (v, blk.pc)); + lw.compact_lit = if p.blk_lit[r].is_some() { blk_lit_val } else { None }; for &i in &blk.insts { lw.inst(&cfg.insts[i])?; } + lw.compact_blk_pc = None; + lw.compact_lit = None; let next = match blk.term { Term::End => lw.c(END), Term::Jump(_) => taken, @@ -323,7 +931,11 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.sel(c, taken, not_taken) } }; + let live_out = p.class_live_out[k]; for var in lw.ssa.end_log().into_iter().filter(|&v| v < VAR_TMP) { + if (var < 106 || var == VAR_SCC) && (live_out & (1u128 << var)) == 0 { + continue; + } let (v, p) = (lw.rd(var), slot(lw, var)); lw.s.m.store(p, v, 4); } diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 86d41bfd68..3cff9a054a 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -213,7 +213,7 @@ fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); let p = super::compact::automatic_plan(&cfg, &lw, false).unwrap(); - assert!(p.inline && p.words() > 8192 && p.words() <= 12288); + assert!(p.inline && p.order.len() > 16384 && p.words() <= 12288); let k = translate_full(&code, o).unwrap(); for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] { let mut st = KernelState::default(); diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 07b49755e2..b39ba4091a 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -1138,7 +1138,7 @@ fn raw_buffer_oob_check_guards_32bit_wraparound() { // (`icmp uge`) for both `voff + OFFSET` and `off + bytes` (#1893). let code = prog(&[ ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 3), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 16)], None), - ("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 16)], None), + ("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 20)], None), ]); let dxil = translate(&code, ko).expect("mubuf + atomic translates"); super::validate::validate(&dxil).expect("validates"); @@ -1158,6 +1158,7 @@ fn compute_movrel_uses_program_max_vgpr_and_masks_m0() { ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 129)], None), ("V_MOVRELS_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", 256 + 1)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 130)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), ]); let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; let k = super::kernel::translate_compute(&code, ko, &cs).expect("compute movrel translates"); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index e9e256ec08..e36381b547 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -615,6 +615,8 @@ impl Lw { .max() .unwrap_or(0), exec_cache: HashMap::new(), + compact_blk_pc: None, + compact_lit: None, xs: None, xw: None, xc: None, diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index a327862b97..dda789481b 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -187,6 +187,19 @@ impl Lw { if self.live_exec == Some((lo, hi)) { return self.b(true); } + if self.wave64 { + match (self.s.m.const_u64(lo), self.s.m.const_u64(hi)) { + (Some(0xFFFF_FFFF), Some(0xFFFF_FFFF)) => return self.b(true), + (Some(0), Some(0)) => return self.b(false), + _ => {} + } + } else { + match self.s.m.const_u64(lo) { + Some(0xFFFF_FFFF) => return self.b(true), + Some(0) => return self.b(false), + _ => {} + } + } let key = (self.cur(), lo, hi); if let Some(&v) = self.exec_cache.get(&key) { return v; @@ -197,6 +210,14 @@ impl Lw { } else { lo }; + if let Some(k) = self.s.m.const_u64(w) { + if k == 0xFFFF_FFFF { + return self.b(true); + } + if k == 0 { + return self.b(false); + } + } let l = self.lane31; let sh = self.bin(BinOp::LShr, w, l); let b = self.andc(sh, 1); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index fb18411e1e..4bab1223fe 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -239,6 +239,10 @@ pub struct Lw { pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>, pub sampler_base: u32, pub exec_cache: HashMap<(Block, Value, Value), Value>, + /// dynamic block-start PC `(blk_pc_val, rep_blk_pc)` when lowering compact `S_GETPC_B64` blocks + pub compact_blk_pc: Option<(Value, u64)>, + /// dynamic 32-bit literal value when lowering a single-literal parameterized compact block + pub compact_lit: Option, /// groupshared exchange words of the split form /// split form: the halves' exchange words (storage, first index) and the lane counter pub xs: Option<(super::ops::GroupShared, u32)>, @@ -713,6 +717,10 @@ impl Lw { } /// 32-bit value of a scalar source code (0..255) or VALU source (256+ = VGPR). + fn lit_c(&mut self, lit: u32) -> Value { + self.compact_lit.unwrap_or_else(|| self.c(lit)) + } + pub fn code32(&mut self, code: u64, lit: Option, f16: bool) -> Option { Some(match code { 0..=124 | 126 | 127 => self.sreg(code), @@ -736,7 +744,7 @@ impl Lw { self.u(z) } 253 => self.scc(), - 255 => self.c(lit?), + 255 => self.lit_c(lit?), 256..=511 => self.vreg(code - 256), 235..=238 => self.c(0), 239 => self.c(0x7FFF_FFFF), @@ -760,9 +768,9 @@ impl Lw { 251 | 252 | 253 => (self.code32(code, None, false)?, self.c(0)), 255 => { if f64 { - (self.c(0), self.c(lit?)) + (self.c(0), self.lit_c(lit?)) } else { - (self.c(lit?), self.c(0)) + (self.lit_c(lit?), self.c(0)) } } 256..=510 => (self.vreg(code - 256), self.vreg(code - 255)), @@ -779,7 +787,7 @@ impl Lw { pub fn read(&mut self, d: &Decoded, o: &Operand, f16: bool) -> Option { match o.field { - Some("LITERAL") => Some(self.c(d.literal?)), + Some("LITERAL") => Some(self.lit_c(d.literal?)), Some(f) => { let v = Self::field(d, f); let width = d.enc.field_width(f); @@ -788,7 +796,7 @@ impl Lw { } match o.ty { "OPR_SIMM16" => Some(self.c(v as u32)), - "OPR_SIMM32" => Some(self.c(d.literal?)), + "OPR_SIMM32" => Some(self.lit_c(d.literal?)), _ => self.code32(v, d.literal, f16), } } @@ -1349,9 +1357,15 @@ impl Lw { if name == "s_getpc_b64" { // the code region is addressed from 0 – with constant data after the program and // several memory windows, above them all (`rodata_loads`), as the HLSL kernel - let pc = d.pc + d.len as u64; + let lo = match self.compact_blk_pc { + Some((blk_pc, rep_blk_pc)) => { + let rel = (d.pc + d.len as u64).wrapping_sub(rep_blk_pc) as u32; + if rel == 0 { blk_pc } else { self.addc(blk_pc, rel) } + } + None => self.c((d.pc + d.len as u64) as u32), + }; let code_hi = if self.rodata.is_empty() || !self.windowed() { 0 } else { crate::gpu::recomp::CODE_ADDRESS_HI }; - let (lo, hi) = (self.c(pc as u32), self.c(code_hi)); + let hi = self.c(code_hi); self.write64(&dst, lo, hi); return Ok(()); } diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index a952b8567c..b2805c5f17 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -1324,8 +1324,31 @@ impl Lw { }) } - /// The recompiler's `float_compare`: NaN tested explicitly. + /// Float compare: single-instruction IEEE-754 ordered/unordered `fcmp` for `f32`, + /// explicit `isnan_d` for `f64`. pub fn float_compare(&mut self, opn: &str, a: Value, b: Value) -> Option { + let is_f32 = self.s.m.type_of(a) == self.s.m.f32(); + if is_f32 { + return Some(match opn { + "f" => self.b(false), + "t" | "tru" => self.b(true), + "lt" => self.fcmp(Pred::FOLt, a, b), + "eq" => self.fcmp(Pred::FOEq, a, b), + "le" => self.fcmp(Pred::FOLe, a, b), + "gt" => self.fcmp(Pred::FOGt, a, b), + "ge" => self.fcmp(Pred::FOGe, a, b), + "lg" => self.fcmp(Pred::FONe, a, b), + "o" => self.fcmp(Pred::FOrd, a, b), + "u" => self.fcmp(Pred::FUno, a, b), + "nlt" => self.fcmp(Pred::FUGe, a, b), + "neq" => self.fcmp(Pred::FUNe, a, b), + "nle" => self.fcmp(Pred::FUGt, a, b), + "ngt" => self.fcmp(Pred::FULe, a, b), + "nge" => self.fcmp(Pred::FULt, a, b), + "nlg" => self.fcmp(Pred::FUEq, a, b), + _ => return None, + }); + } let rel = |s: &mut Self, r: &str| -> Option { Some(match r { "lt" => s.fcmp(Pred::FOLt, a, b), diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 60f4341917..9145a21d7e 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; -use super::bitstream::{signed, BitWriter}; +use super::bitstream::{signed, AbbrevOp, BitWriter}; mod opt; pub(super) mod split; @@ -58,6 +58,9 @@ enum ConstDef { Undef(Ty), Null(Ty), Aggregate(Ty, Vec), + /// Packed `i32` constant array (`CST_CODE_DATA = 22`), avoiding per-element `CST_CODE_INTEGER` + /// interning for large lookup tables (e.g. `compact.rs`). + DataI32(Ty, Vec), } #[derive(Clone)] @@ -468,6 +471,16 @@ impl Module { self.constant(ConstDef::Aggregate(ty, elems.to_vec())) } + /// Packed `[N x i32]` constant data array (`CST_CODE_DATA`), avoiding interning each element. + pub fn const_data_i32(&mut self, words: &[u32]) -> Value { + let i32 = self.i32(); + let at = self.array(words.len() as u64, i32); + if words.is_empty() { + return self.null(at); + } + self.constant(ConstDef::DataI32(at, words.to_vec())) + } + // ---- functions and globals /// Declares (or finds) a function by name. @@ -517,7 +530,12 @@ impl Module { self.ptr(t, 0) } Value::Const(c) => match &self.consts[c as usize] { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }, Value::Inst(i) => self.insts[i as usize].ty, } @@ -837,34 +855,59 @@ impl Module { // are dropped. Value numbering follows that order. let (order, pos) = self.block_layout(); - // Global variables nothing references (e.g. an exchange array the code never - // needed) are left out: the validator rejects unused internal declarations. - // Likewise declarations of functions no longer called (after `optimize`). + // Global variables, functions, and constants nothing references (after `optimize`) + // are left out: the validator rejects unused internal globals, and pruning dead + // constants shrinks both `BLOCK_CONSTANTS` and every relative operand ID in `FUNCTION`. let mut gused = vec![false; self.globals.len()]; let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); + let mut cused = vec![false; self.consts.len()]; { - let mut mark = |v: Value| match v { - Value::Global(g) => gused[g as usize] = true, + let mut work_g: Vec = Vec::new(); + let mut work_c: Vec = Vec::new(); + let mark = |v: Value, gused: &mut [bool], fused: &mut [bool], cused: &mut [bool], work_g: &mut Vec, work_c: &mut Vec| match v { + Value::Global(g) => { + let g = g as usize; + if !gused[g] { + gused[g] = true; + work_g.push(g); + } + } Value::Func(f) => fused[f as usize] = true, - _ => {} + Value::Const(c) => { + let c = c as usize; + if !cused[c] { + cused[c] = true; + work_c.push(c); + } + } + Value::Inst(_) => {} }; for &b in &order { for &i in &self.blocks[b] { let op = &self.insts[i as usize].op; if let Op::Call(f, _) = op { - mark(Value::Func(*f)); + mark(Value::Func(*f), &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c); } - op.for_each_operand(&mut mark); - } - } - for c in &self.consts { - if let ConstDef::Aggregate(_, e) = c { - e.iter().copied().for_each(&mut mark); + op.for_each_operand(|v| mark(v, &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c)); } } for m in &self.md { if let MdDef::Val(_, v) = m { - mark(*v); + mark(*v, &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c); + } + } + while !work_g.is_empty() || !work_c.is_empty() { + while let Some(g) = work_g.pop() { + if let Some(init) = self.globals[g].init { + mark(init, &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c); + } + } + while let Some(c) = work_c.pop() { + if let ConstDef::Aggregate(_, e) = &self.consts[c] { + for &v in e { + mark(v, &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c); + } + } } } } @@ -886,7 +929,15 @@ impl Module { } } let fmap = &fmap; - let n_consts = self.consts.len() as u64; + let mut cmap: Vec> = vec![None; self.consts.len()]; + let mut n_consts = 0u64; + for (c, used) in cused.iter().enumerate() { + if *used { + cmap[c] = Some(n_consts); + n_consts += 1; + } + } + let cmap = &cmap; let const_base = n_globals + n_funcs; let inst_base = const_base + n_consts; @@ -907,7 +958,7 @@ impl Module { match v { Value::Global(g) => gmap[g as usize].expect("use of a dropped global"), Value::Func(f) => n_globals + fmap[f as usize].expect("use of a dropped function"), - Value::Const(c) => const_base + c as u64, + Value::Const(c) => const_base + cmap[c as usize].expect("use of a dropped constant"), Value::Inst(i) => inst_ids[i as usize].unwrap_or_else(|| { self.fail(format!("use of a void instruction %{i}")); 0 @@ -962,19 +1013,34 @@ impl Module { } // Module-level constants. - if !self.consts.is_empty() { + if n_consts > 0 { + const ABBREV_CST_INT: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_INTEGER as u64), AbbrevOp::Vbr(6)]; + const ABBREV_CST_F32: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_FLOAT as u64), AbbrevOp::Fixed(32)]; + const ABBREV_CST_DATA: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_DATA as u64), AbbrevOp::ArrayFixed(32)]; w.enter_block(BLOCK_CONSTANTS); + let ab_int = w.define_abbrev(ABBREV_CST_INT); + let ab_f32 = w.define_abbrev(ABBREV_CST_F32); + let ab_data = w.define_abbrev(ABBREV_CST_DATA); let mut cur_ty = None; - for c in &self.consts { + for (ci, c) in self.consts.iter().enumerate() { + if !cused[ci] { + continue; + } let t = match c { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }; if cur_ty != Some(t) { w.record(CST_CODE_SETTYPE, &[t.0 as u64]); cur_ty = Some(t); } match c { - ConstDef::Int(_, v) => w.record(CST_CODE_INTEGER, &[signed(*v)]), + ConstDef::Int(_, v) => w.emit_abbrev(ab_int, ABBREV_CST_INT, &[signed(*v)]), + ConstDef::Float(_, bits) if *bits <= u32::MAX as u64 => w.emit_abbrev(ab_f32, ABBREV_CST_F32, &[*bits]), ConstDef::Float(_, bits) => w.record(CST_CODE_FLOAT, &[*bits]), ConstDef::Undef(_) => w.record(CST_CODE_UNDEF, &[]), ConstDef::Null(_) => w.record(CST_CODE_NULL, &[]), @@ -982,6 +1048,10 @@ impl Module { let ops: Vec = e.iter().map(|&v| abs(v)).collect(); w.record(CST_CODE_AGGREGATE, &ops) } + ConstDef::DataI32(_, words) => { + let ops: Vec = words.iter().map(|&x| x as u64).collect(); + w.emit_abbrev(ab_data, ABBREV_CST_DATA, &ops); + } } } w.end_block(); @@ -1022,15 +1092,16 @@ impl Module { } w.end_block(); - // The entry's body. - w.enter_block(BLOCK_FUNCTION); + // The entry's body (abbrev width 4 -> 12 user abbreviations for hot DXIL opcodes). + w.enter_block_with_width(BLOCK_FUNCTION, 4); + let ab = FuncAbbrevs::define(&mut w); w.record(FUNC_CODE_DECLAREBLOCKS, &[order.len() as u64]); let mut inst_id = inst_base; let mut operands = Vec::new(); for &b in &order { for k in 0..self.blocks[b].len() { let i = self.blocks[b][k] as usize; - self.write_inst(&mut w, i, inst_id, &abs, &pos, &mut operands); + self.write_inst(&mut w, &ab, i, inst_id, &abs, &pos, &mut operands); if !self.is_void(self.insts[i].ty) { inst_id += 1; } @@ -1184,6 +1255,7 @@ impl Module { fn write_inst( &self, w: &mut BitWriter, + ab: &FuncAbbrevs, i: usize, inst_id: u64, abs: &dyn Fn(Value) -> u64, @@ -1209,21 +1281,22 @@ impl Module { ops.clear(); match &self.insts[i].op { Op::Bin(op, a, b, flags) => { - ops.extend_from_slice(&[rel(*a), rel(*b), *op as u64]); - if *flags != 0 { - ops.push(*flags); + if *flags == 0 { + w.emit_abbrev(ab.binop, ABBREV_BINOP, &[rel(*a), rel(*b), *op as u64]); + } else { + ops.extend_from_slice(&[rel(*a), rel(*b), *op as u64, *flags]); + w.record(FUNC_CODE_INST_BINOP, ops); } - w.record(FUNC_CODE_INST_BINOP, ops) } - Op::Cast(op, v, t) => w.record(FUNC_CODE_INST_CAST, &[rel(*v), t.0 as u64, *op as u64]), - Op::Cmp(p, a, b) => w.record(FUNC_CODE_INST_CMP2, &[rel(*a), rel(*b), *p as u64]), - Op::Select(c, t, f) => w.record(FUNC_CODE_INST_VSELECT, &[rel(*t), rel(*f), rel(*c)]), - Op::Extract(a, idx) => w.record(FUNC_CODE_INST_EXTRACTVAL, &[rel(*a), *idx as u64]), + Op::Cast(op, v, t) => w.emit_abbrev(ab.cast, ABBREV_CAST, &[rel(*v), t.0 as u64, *op as u64]), + Op::Cmp(p, a, b) => w.emit_abbrev(ab.cmp2, ABBREV_CMP2, &[rel(*a), rel(*b), *p as u64]), + Op::Select(c, t, f) => w.emit_abbrev(ab.vselect, ABBREV_VSELECT, &[rel(*t), rel(*f), rel(*c)]), + Op::Extract(a, idx) => w.emit_abbrev(ab.extract, ABBREV_EXTRACT, &[rel(*a), *idx as u64]), Op::Call(f, args) => { let fd = &self.funcs[*f as usize]; - ops.extend_from_slice(&[0, 1 << 15, fd.ty.0 as u64, rel(Value::Func(*f))]); + ops.extend_from_slice(&[fd.ty.0 as u64, rel(Value::Func(*f))]); ops.extend(args.iter().map(|&a| rel(a))); - w.record(FUNC_CODE_INST_CALL, ops) + w.emit_abbrev(ab.call, ABBREV_CALL, ops); } Op::Phi(inc) => { ops.push(self.insts[i].ty.0 as u64); @@ -1232,22 +1305,30 @@ impl Module { ops.push(signed(inst_id as i64 - abs(v) as i64)); ops.push(bb(b)); } - w.record(FUNC_CODE_INST_PHI, ops) + w.emit_abbrev(ab.phi, ABBREV_PHI, ops); } Op::Load(p, align) => { let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; - w.record(FUNC_CODE_INST_LOAD, &[rel(*p), self.insts[i].ty.0 as u64, a, 0]) + if a == 3 { + w.emit_abbrev(ab.load, ABBREV_LOAD, &[rel(*p), self.insts[i].ty.0 as u64]); + } else { + w.record(FUNC_CODE_INST_LOAD, &[rel(*p), self.insts[i].ty.0 as u64, a, 0]); + } } Op::Store(p, v, align) => { let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; - w.record(FUNC_CODE_INST_STORE, &[rel(*p), rel(*v), a, 0]) + if a == 3 { + w.emit_abbrev(ab.store, ABBREV_STORE, &[rel(*p), rel(*v)]); + } else { + w.record(FUNC_CODE_INST_STORE, &[rel(*p), rel(*v), a, 0]); + } } Op::Gep(p, idx) => { let pt = self.value_ty(*p); let (src, _) = self.pointee_of(pt).unwrap_or((pt, 0)); - ops.extend_from_slice(&[1, src.0 as u64, rel(*p)]); + ops.extend_from_slice(&[src.0 as u64, rel(*p)]); ops.extend(idx.iter().map(|&v| rel(v))); - w.record(FUNC_CODE_INST_GEP, ops) + w.emit_abbrev(ab.gep, ABBREV_GEP, ops); } Op::AtomicRmw(op, p, v) => { // [ptr, val, op, vol, ordering, synchscope (crossthread = 1)] @@ -1263,8 +1344,8 @@ impl Module { let a = align.trailing_zeros() as u64 + 1; w.record(FUNC_CODE_INST_ALLOCA, &[t.0 as u64, i32t.0 as u64, abs(*n), a | 1 << 6]) } - Op::Br(b) => w.record(FUNC_CODE_INST_BR, &[bb(*b)]), - Op::CondBr(c, t, f) => w.record(FUNC_CODE_INST_BR, &[bb(*t), bb(*f), rel(*c)]), + Op::Br(b) => w.emit_abbrev(ab.br, ABBREV_BR, &[bb(*b)]), + Op::CondBr(c, t, f) => w.emit_abbrev(ab.condbr, ABBREV_CONDBR, &[bb(*t), bb(*f), rel(*c)]), Op::Switch(v, d, cases) => { ops.extend_from_slice(&[self.value_ty(*v).0 as u64, rel(*v), bb(*d)]); for &(c, b) in cases { @@ -1284,7 +1365,12 @@ impl Module { Value::Global(g) => self.globals[g as usize].ptr, Value::Func(f) => self.type_ids[&TypeDef::Ptr(self.funcs[f as usize].ty, 0)], Value::Const(c) => match &self.consts[c as usize] { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }, Value::Inst(i) => self.insts[i as usize].ty, } @@ -1343,6 +1429,7 @@ const CST_CODE_UNDEF: u32 = 3; const CST_CODE_INTEGER: u32 = 4; const CST_CODE_FLOAT: u32 = 6; const CST_CODE_AGGREGATE: u32 = 7; +const CST_CODE_DATA: u32 = 22; const METADATA_STRING: u32 = 1; const METADATA_VALUE: u32 = 2; @@ -1371,6 +1458,66 @@ const FUNC_CODE_INST_GEP: u32 = 43; const FUNC_CODE_INST_STORE: u32 = 44; const FUNC_CODE_INST_CMPXCHG: u32 = 46; +const ABBREV_BINOP: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BINOP as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(4)]; +const ABBREV_CAST: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_CAST as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(4)]; +const ABBREV_CMP2: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_CMP2 as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(6)]; +const ABBREV_VSELECT: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_VSELECT as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5)]; +const ABBREV_EXTRACT: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_EXTRACTVAL as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(4)]; +const ABBREV_LOAD: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_LOAD as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5), AbbrevOp::Literal(3), AbbrevOp::Literal(0)]; +const ABBREV_STORE: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_STORE as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5), AbbrevOp::Literal(3), AbbrevOp::Literal(0)]; +const ABBREV_BR: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BR as u64), AbbrevOp::Vbr(6)]; +const ABBREV_CONDBR: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BR as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5)]; +const ABBREV_CALL: &[AbbrevOp] = &[ + AbbrevOp::Literal(FUNC_CODE_INST_CALL as u64), + AbbrevOp::Literal(0), + AbbrevOp::Literal(1 << 15), + AbbrevOp::Vbr(5), + AbbrevOp::Vbr(6), + AbbrevOp::ArrayVbr(5), +]; +const ABBREV_PHI: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_PHI as u64), AbbrevOp::Vbr(5), AbbrevOp::ArrayVbr(6)]; +const ABBREV_GEP: &[AbbrevOp] = &[ + AbbrevOp::Literal(FUNC_CODE_INST_GEP as u64), + AbbrevOp::Literal(1), + AbbrevOp::Vbr(5), + AbbrevOp::Vbr(5), + AbbrevOp::ArrayVbr(5), +]; + +struct FuncAbbrevs { + binop: u32, + cast: u32, + cmp2: u32, + vselect: u32, + extract: u32, + load: u32, + store: u32, + br: u32, + condbr: u32, + call: u32, + phi: u32, + gep: u32, +} + +impl FuncAbbrevs { + fn define(w: &mut BitWriter) -> Self { + Self { + binop: w.define_abbrev(ABBREV_BINOP), + cast: w.define_abbrev(ABBREV_CAST), + cmp2: w.define_abbrev(ABBREV_CMP2), + vselect: w.define_abbrev(ABBREV_VSELECT), + extract: w.define_abbrev(ABBREV_EXTRACT), + load: w.define_abbrev(ABBREV_LOAD), + store: w.define_abbrev(ABBREV_STORE), + br: w.define_abbrev(ABBREV_BR), + condbr: w.define_abbrev(ABBREV_CONDBR), + call: w.define_abbrev(ABBREV_CALL), + phi: w.define_abbrev(ABBREV_PHI), + gep: w.define_abbrev(ABBREV_GEP), + } + } +} + // ------------------------------------------------------- introspection /// What an instruction is, for analyses over the built function (e.g. the @@ -1517,6 +1664,23 @@ impl Module { _ => None, } } + + /// The `f32` value of a float constant (also unwraps `bitcast i32_const to float`). + pub fn const_f32(&self, v: Value) -> Option { + match v { + Value::Const(c) => match &self.consts[c as usize] { + ConstDef::Float(t, bits) if matches!(self.types[t.0 as usize], TypeDef::Float) => Some(f32::from_bits(*bits as u32)), + _ => None, + }, + Value::Inst(i) => match self.insts[i as usize].op { + Op::Cast(CastOp::BitCast, src, to) if matches!(self.types[to.0 as usize], TypeDef::Float) => { + self.const_u64(src).map(|b| f32::from_bits(b as u32)) + } + _ => None, + }, + _ => None, + } + } } impl Module { diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index ef37369b34..4e425e351a 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -100,7 +100,20 @@ impl Module { Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) => Cse::Dom, Op::Load(p, _) if self.is_const_global_ptr(*p) => Cse::Dom, Op::Phi(_) if cfg!(test) && std::env::var_os("XCL_SAMPLE_PHI_CSE").is_some() => Cse::Block, - Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => Cse::Dom, + Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => { + let name = &self.funcs[*f as usize].name; + // AMD RDNA4 (`amdxc64.dll`) crashes on null deref if a raw `createHandleFromHeap` + // handle is shared across distinct `annotateHandle` resource kinds or across basic + // blocks, or if `annotateHandle` / `getDimensions` crosses basic blocks. + if name.starts_with("dx.op.createHandleFromHeap") { + Cse::No + } else if name.starts_with("dx.op.annotateHandle") || name.starts_with("dx.op.getDimensions") { + Cse::Block + } else { + Cse::Dom + } + } + Op::Call(f, _) if self.funcs[*f as usize].name.starts_with("dx.op.getDimensions") => Cse::Block, Op::Call(f, _) if self.wave_call(*f) && !self.funcs[*f as usize].name.starts_with("dx.op.waveIsFirstLane") => Cse::Block, _ => Cse::No, } @@ -524,286 +537,707 @@ impl Module { vec![HashMap::new(); self.blocks.len()] } - /// Cleans up the entry function (see the module docs of `opt`). Values - /// keep their identities; replaced ones simply lose their uses. - /// - /// `XCL_DXIL_NO_OPT=phi,cse,cfg,dce,merge` (any subset, or `all`) skips passes, for bisecting. - pub fn optimize(&mut self) { - let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); - let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); - let mut order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); - // malformed IR (a use before its definition or of a void result) is left for the - // writer to report, not cleaned away - if !self.uses_well_formed(&order) { - return; + fn is_hoistable_readnone_call(&self, f: u32, args: &[Value], in_entry: &[bool]) -> bool { + let fd = &self.funcs[f as usize]; + if fd.attrs != FnAttrs::ReadNone || fd.name.ends_with(".f64") { + return false; } - // unreachable blocks: emptied (the writer drops them) - let mut reach = vec![false; self.blocks.len()]; - for &b in &order { - reach[b as usize] = true; + // Never hoist `createHandleFromHeap`, `annotateHandle`, or `getDimensions` across blocks + // (AMD RDNA4 `amdxc64` requires heap handles / annotations / dimensions to stay block-local). + let ok_name = [ + "dx.op.groupId.", + "dx.op.threadId.", + "dx.op.threadIdInGroup.", + "dx.op.flattenedThreadIdInGroup.", + "dx.op.createHandleFromBinding", + ] + .iter() + .any(|p| fd.name.starts_with(p)); + if !ok_name { + return false; } - for (b, r) in reach.iter().enumerate() { - if !r { - self.blocks[b].clear(); - } + args.iter().all(|a| match *a { + Value::Const(_) => true, + Value::Inst(j) => in_entry.get(j as usize).copied().unwrap_or(false), + _ => false, + }) + } + + /// Hoists duplicate entry-available `ReadNone` intrinsics (such as `dx.op.groupId` in + /// compact switch arms, or `createHandleFromHeap` + `annotateHandle` pairs) into entry + /// block 0 so every block shares a single dominating definition. + fn hoist_entry_readnone(&mut self, order: &[u32], repl: &mut Vec>) -> bool { + if order.is_empty() || self.blocks[0].is_empty() { + return false; } - for &b in &order { - for k in 0..self.blocks[b as usize].len() { - let i = self.blocks[b as usize][k] as usize; - if let Op::Phi(inc) = &mut self.insts[i].op { - inc.retain(|p| reach[p.1 .0 as usize]); + let mut any_changed = false; + // Two passes: pass 0 hoists `createHandleFromHeap` / `groupId`, pass 1 hoists + // `annotateHandle` whose handle argument was just hoisted into entry block 0. + for _pass in 0..2 { + let mut in_entry = vec![false; self.insts.len()]; + for &i in &self.blocks[0] { + if repl[i as usize].is_none() { + in_entry[i as usize] = true; } } + let mut counts: HashMap<(u32, Vec), usize> = HashMap::new(); + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + if repl[i].is_some() { + continue; + } + let (f, raw_args) = match &self.insts[i].op { + Op::Call(f, args) => (*f, args.clone()), + _ => continue, + }; + let args: Vec = raw_args.into_iter().map(|a| resolve(repl, a)).collect(); + if self.is_hoistable_readnone_call(f, &args, &in_entry) { + *counts.entry((f, args)).or_insert(0) += 1; + } + } + } + let mut hoisted: HashMap<(u32, Vec), Value> = HashMap::new(); + // Reuse any call already in entry block 0 first. + for k in 0..self.blocks[0].len() { + let i = self.blocks[0][k] as usize; + if repl[i].is_some() { + continue; + } + let (f, raw_args) = match &self.insts[i].op { + Op::Call(f, args) => (*f, args.clone()), + _ => continue, + }; + let args: Vec = raw_args.into_iter().map(|a| resolve(repl, a)).collect(); + let key = (f, args); + if counts.get(&key).copied().unwrap_or(0) >= 2 { + hoisted.entry(key).or_insert(Value::Inst(i as u32)); + } + } + let mut changed = false; + let term = if self.blocks[0].last().is_some_and(|&t| { + matches!( + self.insts[t as usize].op, + Op::Br(_) | Op::CondBr(..) | Op::Switch(..) | Op::Ret | Op::Unreachable + ) + }) { + self.blocks[0].pop() + } else { + None + }; + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + if repl[i].is_some() { + continue; + } + let (f, raw_args, ty) = match &self.insts[i].op { + Op::Call(f, args) => (*f, args.clone(), self.insts[i].ty), + _ => continue, + }; + let args: Vec = raw_args.into_iter().map(|a| resolve(repl, a)).collect(); + if !self.is_hoistable_readnone_call(f, &args, &in_entry) { + continue; + } + let key = (f, args); + if counts.get(&key).copied().unwrap_or(0) < 2 { + continue; + } + let entry_val = *hoisted.entry(key.clone()).or_insert_with(|| { + let id = self.insts.len() as u32; + self.insts.push(super::InstDef { op: Op::Call(key.0, key.1), ty }); + self.def_block.push(Block(0)); + self.blocks[0].push(id); + repl.push(None); + Value::Inst(id) + }); + if entry_val != Value::Inst(i as u32) { + repl[i] = Some(entry_val); + changed = true; + } + } + } + if let Some(t) = term { + self.blocks[0].push(t); + } + if !changed { + break; + } + any_changed = true; } + any_changed + } - let mut repl: Vec> = vec![None; self.insts.len()]; - - // trivial phis (all incoming values the phi itself or one value), to a fixed point - if !skip("phi") { - self.simplify_phis(&order, &mut repl); - } - - // CSE along the dominator tree (preorder walk with a scoped table) - let idom = self.idoms(&order); - let mut kids: Vec> = vec![Vec::new(); self.blocks.len()]; - for &b in order.iter().skip(1) { - if let Some(d) = idom[b as usize] { - kids[d].push(b as usize); + /// Intra-block store-to-load forwarding and dead-store elimination for non-escaping scalar + /// `alloca` slots (primarily the register slots of `compact.rs`), plus removal of stores to + /// scalar allocas that have zero surviving loads anywhere in the function. + fn opt_local_allocas(&mut self, order: &[u32], repl: &mut [Option]) -> bool { + let mut scalar_allocas: Vec = vec![false; self.insts.len()]; + let mut any_alloca = false; + for &b in order { + for &i in &self.blocks[b as usize] { + let idx = i as usize; + if repl[idx].is_some() { + continue; + } + if let Op::Alloca(ty, n, _) = self.insts[idx].op { + if self.const_u64(n) == Some(1) + && !matches!( + self.types[ty.0 as usize], + super::TypeDef::Array(..) | super::TypeDef::Struct(..) | super::TypeDef::Int(64) | super::TypeDef::Double + ) + { + scalar_allocas[idx] = true; + any_alloca = true; + } + } } } - let mut table: HashMap<(Op, Ty), Value> = HashMap::new(); - // (block, undo log length) frames; undo log holds keys to remove / restore - let mut undo: Vec<((Op, Ty), Option)> = Vec::new(); - enum Step { - Enter(usize), - Leave(usize), + if !any_alloca { + return false; } - let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; - let mut cse_replaced = false; - while let Some(step) = stack.pop() { - let b = match step { - Step::Leave(mark) => { - while undo.len() > mark { - let (k, old) = undo.pop().unwrap(); - match old { - Some(v) => table.insert(k, v), - None => table.remove(&k), - }; + // Disqualify any alloca whose address escapes (used anywhere except as ptr of Load/Store). + for &b in order { + for &i in &self.blocks[b as usize] { + let idx = i as usize; + if repl[idx].is_some() { + continue; + } + match &self.insts[idx].op { + Op::Load(p, _) => { + let _ = p; // pointer operand is valid + } + Op::Store(_p, v, _) => { + if let Value::Inst(j) = *v { + scalar_allocas[j as usize] = false; + } } + other => other.for_each_operand(|v| { + if let Value::Inst(j) = v { + scalar_allocas[j as usize] = false; + } + }), + } + } + } + if !scalar_allocas.iter().any(|&x| x) { + return false; + } + + let mut dead_store = vec![false; self.insts.len()]; + let mut loaded = vec![false; self.insts.len()]; + let mut changed = false; + + for &b in order { + let mut known: HashMap = HashMap::new(); + let mut last_store: HashMap = HashMap::new(); + let len = self.blocks[b as usize].len(); + for k in 0..len { + let i = self.blocks[b as usize][k] as usize; + if repl[i].is_some() { continue; } - Step::Enter(b) => b, - }; - stack.push(Step::Leave(undo.len())); - let mut local: HashMap<(Op, Ty), Value> = HashMap::new(); - for k in 0..self.blocks[b].len() { - let i = self.blocks[b][k] as usize; - let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); - op.map_operands(|v| resolve(&mut repl, v)); - if repl[i].is_none() { - if let Some(s) = self.simplify_op(&op, self.insts[i].ty) { - repl[i] = Some(s); - cse_replaced = true; - } else { - let kind = self.cse_kind(&op); - if kind != Cse::No { - let key = (op.clone(), self.insts[i].ty); - let t = if kind == Cse::Dom { &mut table } else { &mut local }; - if let Some(&v) = t.get(&key) { + match self.insts[i].op { + Op::Load(Value::Inst(a), _) if scalar_allocas[a as usize] => { + if let Some(&v) = known.get(&a) { + let v = resolve(repl, v); + if self.value_ty(v) == self.insts[i].ty { repl[i] = Some(v); - cse_replaced = true; - } else { - let old = t.insert(key.clone(), Value::Inst(i as u32)); - if kind == Cse::Dom { - undo.push((key, old)); - } + changed = true; + continue; } - } else if matches!(&op, Op::Call(f, _) if self.funcs[*f as usize].name == "dx.op.discard") { - // `dx.op.discard` demotes lanes mid-block, changing the active lane - // set for subsequent wave/quad intrinsics in the same basic block. - local.clear(); } + loaded[a as usize] = true; + last_store.remove(&a); + known.insert(a, Value::Inst(i as u32)); + } + Op::Store(Value::Inst(a), v, _) if scalar_allocas[a as usize] => { + let v = resolve(repl, v); + if known.get(&a).copied().map(|kv| resolve(repl, kv)) == Some(v) { + dead_store[i] = true; + changed = true; + continue; + } + if let Some(prev) = last_store.insert(a, i) { + dead_store[prev] = true; + changed = true; + } + known.insert(a, v); } + _ => {} } - self.insts[i].op = op; } - for &c in kids[b].iter().rev() { - stack.push(Step::Enter(c)); + } + + // Any scalar alloca with zero surviving loads anywhere in the function needs no stores. + for &b in order { + for &i in &self.blocks[b as usize] { + let idx = i as usize; + if !dead_store[idx] { + if let Op::Store(Value::Inst(a), _, _) = self.insts[idx].op { + if scalar_allocas[a as usize] && !loaded[a as usize] { + dead_store[idx] = true; + changed = true; + } + } + } } } - // second trivial-phi fixed point if CSE/simplification collapsed incoming values - if cse_replaced && !skip("phi") { - self.simplify_phis(&order, &mut repl); + + if changed { + for &b in order { + self.blocks[b as usize].retain(|&i| !dead_store[i as usize]); + } } - // phis may name values defined later (back edges): resolve before CFG folding so - // terminators see constants exposed by both CSE and the second trivial-phi pass. - for &b in &order { - for k in 0..self.blocks[b as usize].len() { - let i = self.blocks[b as usize][k] as usize; - self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); + changed + } + + /// Removes immediately redundant `dx.op.barrier` calls within a basic block when no + /// memory-visible side effect occurred since an equally-strong or stronger barrier. + fn elim_redundant_barriers(&mut self, order: &[u32]) -> bool { + let mut removed = false; + for &b in order { + let mut active_mask: Option = None; + let mut keep: Vec = Vec::with_capacity(self.blocks[b as usize].len()); + for &i in &self.blocks[b as usize] { + let op = &self.insts[i as usize].op; + match op { + Op::Call(f, args) if self.funcs[*f as usize].name == "dx.op.barrier" => { + let mode = args.get(1).and_then(|&v| self.const_u64(v)); + match (active_mask, mode) { + (Some(prev), Some(cur)) if (cur & !prev) == 0 => { + removed = true; + continue; + } + (Some(prev), Some(cur)) => active_mask = Some(prev | cur), + (None, Some(cur)) => active_mask = Some(cur), + _ => active_mask = None, + } + } + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => active_mask = None, + Op::Load(p, _) if !self.is_const_global_ptr(*p) => active_mask = None, + Op::Call(f, _) if self.funcs[*f as usize].attrs != FnAttrs::ReadNone => active_mask = None, + _ => {} + } + keep.push(i); + } + if keep.len() != self.blocks[b as usize].len() { + self.blocks[b as usize] = keep; } } - // CSE, trivial-phi folding, or dominating branches can prove a terminator constant. Fold - // it before DCE, then rebuild reachability and predecessor edges so unreachable blocks and - // obsolete PHI edges are pruned cleanly while preserving loop backedges. - let mut cfg_folded = false; - if !skip("cfg") { - let facts = self.branch_facts(&order); - for &b in &order { - let Some(&i) = self.blocks[b as usize].last() else { continue }; - let replacement = match self.insts[i as usize].op.clone() { - Op::CondBr(c, t, f) => match self.const_u64(c).or_else(|| facts[b as usize].get(&c).copied()) { - Some(0) => Some(Op::Br(f)), - Some(1) => Some(Op::Br(t)), - _ => None, - }, - Op::Switch(v, default, cases) => self.const_u64(v).or_else(|| facts[b as usize].get(&v).copied()).map(|needle| { - let target = cases.iter().find_map(|(case, target)| (self.const_u64(*case) == Some(needle)).then_some(*target)).unwrap_or(default); - Op::Br(target) - }), - _ => None, - }; - if let Some(op) = replacement { - self.insts[i as usize].op = op; - cfg_folded = true; + removed + } + + /// Recursively derives implied constant facts from a known boolean value `v == val` (bounded + /// depth so complex expressions stay strictly O(1)). + fn record_fact( + &self, + v: Value, + val: u64, + depth: u8, + facts: &mut HashMap, + undo: &mut Vec<(Value, Option)>, + ) { + if matches!(v, Value::Const(_)) { + return; + } + if facts.get(&v) == Some(&val) { + return; + } + let old = facts.insert(v, val); + undo.push((v, old)); + if depth == 0 { + return; + } + let Value::Inst(i) = v else { return }; + match self.insts[i as usize].op { + Op::Bin(BinOp::And, a, b, 0) if val == 1 && self.int_width(self.insts[i as usize].ty) == Some(1) => { + self.record_fact(a, 1, depth - 1, facts, undo); + self.record_fact(b, 1, depth - 1, facts, undo); + } + Op::Bin(BinOp::Or, a, b, 0) if val == 0 && self.int_width(self.insts[i as usize].ty) == Some(1) => { + self.record_fact(a, 0, depth - 1, facts, undo); + self.record_fact(b, 0, depth - 1, facts, undo); + } + Op::Bin(BinOp::Xor, a, b, 0) if self.int_width(self.insts[i as usize].ty) == Some(1) => { + if self.const_u64(b) == Some(1) { + self.record_fact(a, val ^ 1, depth - 1, facts, undo); + } else if self.const_u64(a) == Some(1) { + self.record_fact(b, val ^ 1, depth - 1, facts, undo); + } + } + Op::Cmp(Pred::Eq, a, b) if val == 1 => { + if self.int_width(self.value_ty(a)).is_some_and(|w| w <= 32) { + if let Some(k) = self.const_u64(b) { + self.record_fact(a, k, depth - 1, facts, undo); + } else if let Some(k) = self.const_u64(a) { + self.record_fact(b, k, depth - 1, facts, undo); + } } } + Op::Cmp(Pred::Ne, a, b) if val == 0 => { + if self.int_width(self.value_ty(a)).is_some_and(|w| w <= 32) { + if let Some(k) = self.const_u64(b) { + self.record_fact(a, k, depth - 1, facts, undo); + } else if let Some(k) = self.const_u64(a) { + self.record_fact(b, k, depth - 1, facts, undo); + } + } + } + _ => {} } - if cfg_folded { - order = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + } + + fn apply_facts_to_op(&mut self, op: &mut Op, facts: &HashMap) -> bool { + if facts.is_empty() { + return false; + } + let mut changed = false; + let lookup = |m: &mut Self, v: &mut Value, changed: &mut bool| { + if let Some(&k) = facts.get(v) { + let ty = m.value_ty(*v); + if m.int_width(ty).is_some_and(|w| w <= 32) { + *v = m.const_int(ty, k); + *changed = true; + } + } + }; + match op { + Op::Select(c, t, f) => { + lookup(self, c, &mut changed); + lookup(self, t, &mut changed); + lookup(self, f, &mut changed); + } + Op::CondBr(c, ..) => lookup(self, c, &mut changed), + Op::Switch(v, ..) => lookup(self, v, &mut changed), + Op::Bin(_, a, b, 0) | Op::Cmp(_, a, b) => { + lookup(self, a, &mut changed); + lookup(self, b, &mut changed); + } + Op::Cast(CastOp::ZExt | CastOp::SExt | CastOp::Trunc, v, _) => { + lookup(self, v, &mut changed); + } + _ => {} + } + changed + } + + /// Cleans up the entry function (see the module docs of `opt`). Values + /// keep their identities; replaced ones simply lose their uses. + /// + /// `XCL_DXIL_NO_OPT=phi,cse,cfg,dce,merge,alloca,facts,hoist,barrier` (any subset, or `all`) + /// skips passes, for bisecting. + pub fn optimize(&mut self) { + let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); + let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); + let order0: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + // malformed IR (a use before its definition or of a void result) is left for the + // writer to report, not cleaned away + if !self.uses_well_formed(&order0) { + return; + } + + const MAX_OPT_ITERS: usize = 4; + for _iter in 0..MAX_OPT_ITERS { + let mut iter_changed = false; + let mut order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let insts_before: usize = order.iter().map(|&b| self.blocks[b as usize].len()).sum(); + let blocks_before = order.len(); + + // unreachable blocks: emptied (the writer drops them) let mut reach = vec![false; self.blocks.len()]; - let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; for &b in &order { reach[b as usize] = true; - for succ in self.successors(b as usize) { - if let Some(p) = preds.get_mut(succ.0 as usize) { - if !p.contains(&b) { - p.push(b); - } - } - } } for (b, r) in reach.iter().enumerate() { - if !r { + if !r && !self.blocks[b].is_empty() { self.blocks[b].clear(); + iter_changed = true; } } for &b in &order { - for &i in &self.blocks[b as usize] { - let Op::Phi(inc) = &mut self.insts[i as usize].op else { break }; - inc.retain(|p| preds[b as usize].contains(&p.1 .0)); + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + if let Op::Phi(inc) = &mut self.insts[i].op { + inc.retain(|p| reach[p.1 .0 as usize]); + } } } + + let mut repl: Vec> = vec![None; self.insts.len()]; + + // trivial phis (all incoming values the phi itself or one value), to a fixed point if !skip("phi") { self.simplify_phis(&order, &mut repl); - for &b in &order { - for k in 0..self.blocks[b as usize].len() { - let i = self.blocks[b as usize][k] as usize; - self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); - } - } } - } - // dead instructions: live = side effects, terminators and their operands, transitively - let (i64t, f64t) = self.existing_i64_f64(); - let wide: Vec = i64t.into_iter().chain(f64t).collect(); - let mut live = vec![false; self.insts.len()]; - let mut work: Vec = Vec::new(); - for &b in &order { - for &i in &self.blocks[b as usize] { - if repl[i as usize].is_none() && (skip("dce") || !self.removable(&self.insts[i as usize].op, self.insts[i as usize].ty, &wide)) { - live[i as usize] = true; - work.push(i); + // intra-block scalar alloca store->load forwarding & dead-store elimination + if !skip("alloca") && self.opt_local_allocas(&order, &mut repl) { + iter_changed = true; + } + + // hoist repeated constant-argument ReadNone intrinsics (e.g. dx.op.groupId) to entry + if !skip("hoist") { + if self.hoist_entry_readnone(&order, &mut repl) { + repl.resize(self.insts.len(), None); + iter_changed = true; } } - } - while let Some(i) = work.pop() { - self.insts[i as usize].op.for_each_operand(|v| { - if let Value::Inst(j) = v { - if !live[j as usize] { - live[j as usize] = true; - work.push(j); + + // CSE + FACTS branch-condition propagation along the dominator tree + let idom = self.idoms(&order); + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in &order { + for s in self.successors(b as usize) { + if !preds[s.0 as usize].contains(&(b as usize)) { + preds[s.0 as usize].push(b as usize); } } - }); - } - for b in &mut self.blocks { - b.retain(|&i| live[i as usize]); - } - - if !skip("merge") && self.simplify_cfg() { - let order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); - let mut repl2: Vec> = vec![None; self.insts.len()]; - let mut phi_changed = false; - while !skip("phi") { - let mut changed = false; - for &b in &order { - for &i in &self.blocks[b as usize] { - let i = i as usize; - if repl2[i].is_some() { - continue; + } + let mut kids: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in order.iter().skip(1) { + if let Some(d) = idom[b as usize] { + kids[d].push(b as usize); + } + } + let use_facts = !skip("facts"); + let mut table: HashMap<(Op, Ty), Value> = HashMap::new(); + let mut undo: Vec<((Op, Ty), Option)> = Vec::new(); + let mut facts: HashMap = HashMap::new(); + let mut fact_undo: Vec<(Value, Option)> = Vec::new(); + enum Step { + Enter(usize), + Leave(usize, usize), + } + let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; + let mut cse_replaced = false; + while let Some(step) = stack.pop() { + let b = match step { + Step::Leave(mark, fmark) => { + while undo.len() > mark { + let (k, old) = undo.pop().unwrap(); + match old { + Some(v) => table.insert(k, v), + None => table.remove(&k), + }; } - let Op::Phi(inc) = &self.insts[i].op else { break }; - let me = Value::Inst(i as u32); - let mut same: Option = None; - let mut trivial = true; - for &(v, _) in inc { - let v = resolve(&mut repl2, v); - if v == me || Some(v) == same { - continue; + while fact_undo.len() > fmark { + let (k, old) = fact_undo.pop().unwrap(); + match old { + Some(v) => facts.insert(k, v), + None => facts.remove(&k), + }; + } + continue; + } + Step::Enter(b) => b, + }; + stack.push(Step::Leave(undo.len(), fact_undo.len())); + // Push dominating branch facts when `b` has a single CFG predecessor (`idom[b]`). + if use_facts && preds[b].len() == 1 { + let p = preds[b][0]; + if let Some(&term_i) = self.blocks[p].last() { + match self.insts[term_i as usize].op.clone() { + Op::CondBr(c, t, f) if t != f => { + let c = resolve(&mut repl, c); + if t.0 as usize == b { + self.record_fact(c, 1, 4, &mut facts, &mut fact_undo); + } else if f.0 as usize == b { + self.record_fact(c, 0, 4, &mut facts, &mut fact_undo); + } } - if same.is_some() { - trivial = false; - break; + Op::Switch(v, default, cases) if default.0 as usize != b => { + let matching: Vec = cases.iter().filter(|(_, t)| t.0 as usize == b).map(|(c, _)| *c).collect(); + if let [case] = matching.as_slice() { + if let Some(k) = self.const_u64(*case) { + let v = resolve(&mut repl, v); + self.record_fact(v, k, 2, &mut facts, &mut fact_undo); + } + } } - same = Some(v); + _ => {} } - if let (true, Some(v)) = (trivial, same) { - repl2[i] = Some(v); - changed = true; - phi_changed = true; + } + } + let mut local: HashMap<(Op, Ty), Value> = HashMap::new(); + for k in 0..self.blocks[b].len() { + let i = self.blocks[b][k] as usize; + let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); + op.map_operands(|v| resolve(&mut repl, v)); + if use_facts && !facts.is_empty() && self.apply_facts_to_op(&mut op, &facts) { + cse_replaced = true; + } + // Collapse chained EXEC-predicated VGPR selects under the same condition in place: + // `select(c, t, select(c, _, f2)) -> select(c, t, f2)` and + // `select(c, select(c, t2, _), f) -> select(c, t2, f)`. + if let Op::Select(c, ref mut t, ref mut f) = op { + if let Value::Inst(j) = *f { + if let Op::Select(c2, _, f2) = self.insts[j as usize].op { + if c2 == c { + *f = resolve(&mut repl, f2); + cse_replaced = true; + } + } + } + if let Value::Inst(j) = *t { + if let Op::Select(c2, t2, _) = self.insts[j as usize].op { + if c2 == c { + *t = resolve(&mut repl, t2); + cse_replaced = true; + } + } } } + if repl[i].is_none() { + if let Some(s) = self.simplify_op(&op, self.insts[i].ty) { + repl[i] = Some(s); + cse_replaced = true; + } else { + let kind = self.cse_kind(&op); + if kind != Cse::No { + let key = (op.clone(), self.insts[i].ty); + let t = if kind == Cse::Dom { &mut table } else { &mut local }; + if let Some(&v) = t.get(&key) { + repl[i] = Some(v); + cse_replaced = true; + } else { + let old = t.insert(key.clone(), Value::Inst(i as u32)); + if kind == Cse::Dom { + undo.push((key, old)); + } + } + } else if matches!(&op, Op::Call(f, _) if self.funcs[*f as usize].name == "dx.op.discard") { + // `dx.op.discard` demotes lanes mid-block, changing the active lane + // set for subsequent wave/quad intrinsics in the same basic block. + local.clear(); + } + } + } + self.insts[i].op = op; } - if !changed { - break; + for &c in kids[b].iter().rev() { + stack.push(Step::Enter(c)); } } - if phi_changed { + if cse_replaced { + iter_changed = true; + } + // second trivial-phi fixed point if CSE/simplification collapsed incoming values + if cse_replaced && !skip("phi") { + self.simplify_phis(&order, &mut repl); + } + // phis may name values defined later (back edges): resolve before CFG folding so + // terminators see constants exposed by both CSE and the second trivial-phi pass. + for &b in &order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); + } + } + // CSE, trivial-phi folding, or dominating branches can prove a terminator constant. Fold + // it before DCE, then rebuild reachability and predecessor edges so unreachable blocks and + // obsolete PHI edges are pruned cleanly while preserving loop backedges. + let mut cfg_folded = false; + if !skip("cfg") { + let bfacts = self.branch_facts(&order); for &b in &order { - for k in 0..self.blocks[b as usize].len() { - let i = self.blocks[b as usize][k] as usize; - self.insts[i].op.map_operands(|v| resolve(&mut repl2, v)); + let Some(&i) = self.blocks[b as usize].last() else { continue }; + let replacement = match self.insts[i as usize].op.clone() { + Op::CondBr(c, t, f) => match self.const_u64(c).or_else(|| bfacts[b as usize].get(&c).copied()) { + Some(0) => Some(Op::Br(f)), + Some(1) => Some(Op::Br(t)), + _ => None, + }, + Op::Switch(v, default, cases) => self.const_u64(v).or_else(|| bfacts[b as usize].get(&v).copied()).map(|needle| { + let target = cases.iter().find_map(|(case, target)| (self.const_u64(*case) == Some(needle)).then_some(*target)).unwrap_or(default); + Op::Br(target) + }), + _ => None, + }; + if let Some(op) = replacement { + self.insts[i as usize].op = op; + cfg_folded = true; + iter_changed = true; } } } - if !skip("dce") { - live.fill(false); - work.clear(); + if cfg_folded { + order = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let mut reach = vec![false; self.blocks.len()]; + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; for &b in &order { - for &i in &self.blocks[b as usize] { - if repl2[i as usize].is_none() && !self.removable(&self.insts[i as usize].op, self.insts[i as usize].ty, &wide) { - live[i as usize] = true; - work.push(i); + reach[b as usize] = true; + for succ in self.successors(b as usize) { + if let Some(p) = preds.get_mut(succ.0 as usize) { + if !p.contains(&b) { + p.push(b); + } } } } - while let Some(i) = work.pop() { - self.insts[i as usize].op.for_each_operand(|v| { - if let Value::Inst(j) = v { - if !live[j as usize] { - live[j as usize] = true; - work.push(j); - } + for (b, r) in reach.iter().enumerate() { + if !r { + self.blocks[b].clear(); + } + } + for &b in &order { + for &i in &self.blocks[b as usize] { + let Op::Phi(inc) = &mut self.insts[i as usize].op else { break }; + inc.retain(|p| preds[b as usize].contains(&p.1 .0)); + } + } + if !skip("phi") { + self.simplify_phis(&order, &mut repl); + for &b in &order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); } - }); + } } - for b in &mut self.blocks { - b.retain(|&i| live[i as usize]); + } + + if !skip("barrier") && self.elim_redundant_barriers(&order) { + iter_changed = true; + } + + // dead instructions: live = side effects, terminators and their operands, transitively + let (i64t, f64t) = self.existing_i64_f64(); + let wide: Vec = i64t.into_iter().chain(f64t).collect(); + let mut live = vec![false; self.insts.len()]; + let mut work: Vec = Vec::new(); + for &b in &order { + for &i in &self.blocks[b as usize] { + if repl[i as usize].is_none() && (skip("dce") || !self.removable(&self.insts[i as usize].op, self.insts[i as usize].ty, &wide)) { + live[i as usize] = true; + work.push(i); + } } } - debug_assert!(self.uses_well_formed(&order)); + while let Some(i) = work.pop() { + self.insts[i as usize].op.for_each_operand(|v| { + if let Value::Inst(j) = v { + if !live[j as usize] { + live[j as usize] = true; + work.push(j); + } + } + }); + } + for b in &mut self.blocks { + b.retain(|&i| live[i as usize]); + } + + if !skip("merge") && self.simplify_cfg() { + iter_changed = true; + } + + let order_after: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let insts_after: usize = order_after.iter().map(|&b| self.blocks[b as usize].len()).sum(); + debug_assert!(self.uses_well_formed(&order_after)); + if !iter_changed || (insts_after == insts_before && order_after.len() == blocks_before) { + break; + } } } @@ -1683,4 +2117,103 @@ mod tests { assert!(!s.features.contains(&Feature::Int64Ops), "pruned i64 branch must clear Int64Ops"); assert!(!s.features.contains(&Feature::ResourceHeapIndexing), "pruned heap handle must clear ResourceHeapIndexing"); } + + #[test] + fn local_alloca_store_load_forwarding_and_dse() { + let mut m = Module::new(); + m.define_entry("main"); + let i32 = m.i32(); + let slot = m.alloca(i32, 4); + let out = m.global("out", i32, 3, None, false, 4); + let c1 = m.i32c(11); + let c2 = m.i32c(22); + m.store(slot, c1, 4); + let v1 = m.load(slot, 4); + m.store(slot, c2, 4); + let v2 = m.load(slot, 4); + let sum = m.bin(BinOp::Add, v1, v2); + m.store(out, sum, 4); + m.ret(); + + m.optimize(); + + let ops: Vec<&Op> = m.blocks[0].iter().map(|&i| &m.insts[i as usize].op).collect(); + assert!(!ops.iter().any(|op| matches!(op, Op::Alloca(..))), "scalar alloca must be eliminated: {ops:?}"); + assert!(!ops.iter().any(|op| matches!(op, Op::Load(..))), "forwarded loads must be removed: {ops:?}"); + assert!( + ops.iter().any(|op| matches!(op, Op::Store(p, v, _) if *p == out && m.const_u64(*v) == Some(33))), + "store must fold forwarded 11 + 22 == 33: {ops:?}" + ); + } + + #[test] + fn hoist_entry_readnone_and_keep_heap_handles_unshared() { + use crate::gpu::dxil::container::Stage; + use crate::gpu::dxil::shader::Shader; + let mut s = Shader::new(Stage::Compute, (6, 6)); + let i32 = s.m.i32(); + let cond_ptr = s.m.global("cond", i32, 3, None, false, 4); + let out = s.m.global("out", i32, 3, None, false, 4); + let cv = s.m.load(cond_ptr, 4); + let zero = s.m.i32c(0); + let cond = s.m.cmp(Pred::Ne, cv, zero); + let b1 = s.m.new_block(); + let b2 = s.m.new_block(); + let join = s.m.new_block(); + s.m.cond_br(cond, b1, b2); + + s.m.set_block(b1); + let g1 = s.group_id(0); + let h1 = s.heap_raw_buffer_uav(zero, false); + let r1 = s.raw_load(h1, zero, 1)[0]; + let v1 = s.m.bin(BinOp::Add, g1, r1); + s.m.br(join); + + s.m.set_block(b2); + let g2 = s.group_id(0); + let h2 = s.heap_raw_buffer_uav(zero, false); + let r2 = s.raw_load(h2, zero, 1)[0]; + let v2 = s.m.bin(BinOp::Add, g2, r2); + s.m.br(join); + + s.m.set_block(join); + let p = s.m.phi(i32); + s.m.add_incoming(p, v1, b1); + s.m.add_incoming(p, v2, b2); + s.m.store(out, p, 4); + s.m.ret(); + + s.m.optimize(); + + let count_calls = |prefix: &str| -> usize { + s.m.blocks + .iter() + .flatten() + .filter(|&&i| matches!(s.m.insts[i as usize].op, Op::Call(f, _) if s.m.funcs[f as usize].name.starts_with(prefix))) + .count() + }; + assert_eq!(count_calls("dx.op.groupId."), 1, "groupId must hoist to entry block"); + assert_eq!(count_calls("dx.op.createHandleFromHeap"), 2, "createHandleFromHeap must stay unshared across blocks for RDNA4"); + assert_eq!(count_calls("dx.op.annotateHandle"), 2, "annotateHandle must stay block-local for RDNA4"); + } + + #[test] + fn redundant_barriers_eliminated_within_block() { + use crate::gpu::dxil::container::Stage; + use crate::gpu::dxil::ops::barrier; + use crate::gpu::dxil::shader::Shader; + let mut s = Shader::new(Stage::Compute, (6, 6)); + s.barrier(barrier::ALL_SYNC); + s.barrier(barrier::GROUP_SYNC); + s.barrier(barrier::ALL_SYNC); + s.m.ret(); + + s.m.optimize(); + + let barriers = s.m.blocks[0] + .iter() + .filter(|&&i| matches!(s.m.insts[i as usize].op, Op::Call(f, _) if s.m.funcs[f as usize].name == "dx.op.barrier")) + .count(); + assert_eq!(barriers, 1, "adjacent covered barriers must collapse to one"); + } } diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index 7a5e5b65c4..08f8214338 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -6,6 +6,14 @@ use super::lower::Lw; use super::module::{BinOp, Pred, Value}; use super::ops_core::op; +/// Native RDNA float lowering (`XCL_RDNA_FLOAT`, default on, `=0` disables): emits single-op +/// `dx.op.unary(Frc)` for `v_fract_f32` and eliminates redundant `== 0` checks in `mul_legacy` / +/// `fma_legacy` whenever an operand is a known finite non-zero (or zero) constant. +pub fn rdna_float_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_RDNA_FLOAT").map_or(true, |v| v.trim() != "0")) +} + impl Lw { /// `cvt_u32`: NaN / ≤ 0 → 0, ≥ 2^32 → 0xFFFFFFFF. pub fn cvt_u32(&mut self, f: Value) -> Value { @@ -69,8 +77,12 @@ impl Lw { let one = self.u(c); self.sub(h, one) } + /// `fract_f`: x - floor(x), below 1.0. pub fn fract_f(&mut self, x: Value) -> Value { + if rdna_float_enabled() { + return self.un(op::FRC, x); + } let fl = self.un(op::ROUND_NI, x); let r = self.fsub(x, fl); let one = self.fc(1.0); @@ -219,6 +231,16 @@ impl Lw { } /// `mul_legacy`: 0 · anything = 0. pub fn mul_legacy(&mut self, a: Value, b: Value) -> Value { + if rdna_float_enabled() { + let ca = self.s.m.const_f32(a); + let cb = self.s.m.const_f32(b); + if ca == Some(0.0) || cb == Some(0.0) { + return self.fc(0.0); + } + if ca.is_some_and(|x| x.is_finite() && x != 0.0) || cb.is_some_and(|x| x.is_finite() && x != 0.0) { + return self.fmul(a, b); + } + } let z = self.fc(0.0); let az = self.fcmp(Pred::FOEq, a, z); let bz = self.fcmp(Pred::FOEq, b, z); @@ -234,6 +256,16 @@ impl Lw { } /// `fma_legacy`: (a == 0 || b == 0) ? c : mad(a, b, c). pub fn fma_legacy(&mut self, a: Value, b: Value, c: Value) -> Value { + if rdna_float_enabled() { + let ca = self.s.m.const_f32(a); + let cb = self.s.m.const_f32(b); + if ca == Some(0.0) || cb == Some(0.0) { + return c; + } + if ca.is_some_and(|x| x.is_finite() && x != 0.0) || cb.is_some_and(|x| x.is_finite() && x != 0.0) { + return self.fmad(a, b, c); + } + } let z = self.fc(0.0); let az = self.fcmp(Pred::FOEq, a, z); let bz = self.fcmp(Pred::FOEq, b, z); From 33d1222dd3fceda9aa59f85df5fe4a3f5f540875 Mon Sep 17 00:00:00 2001 From: Alp Pesen <5701011+AlpPesen@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:10:41 +0300 Subject: [PATCH 009/175] DXIL: fix compact SGPR liveness for RMW/CMOV SALU and Wave32 masks inst_sreg_scc_use_def now treats all S_CMOV* as conditional writes and S_ADDK_I32/S_MULK_I32/S_BITSET* as read-modify-write on SDST, and clamps Wave32 VALU 64-bit mask defs to 1 SGPR so live s[v+1] slots are not killed. Assisted-by: Antigravity (Gemini 4 Neon) (cherry picked from commit a5233050aef2c78a68f238a69a90ea31cd23f8df) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 75 ++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 02ebe198a7..93e646cbdb 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -28,12 +28,16 @@ fn is_pure_nop(name: &str) -> bool { /// Conservative `(use_mask, def_mask)` over `s0..s105` (bits `0..106`) and `SCC` (bit `VAR_SCC`). /// Any register not provably unconditionally overwritten is omitted from `def_mask`; any unknown /// or indexed SGPR read sets all bits in `use_mask`. -fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded) -> (u128, u128) { +fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded, wave64: bool) -> (u128, u128) { use crate::gpu::rdna2::{field_value, register_scale, Variant}; if d.inst.name.starts_with("S_MOVREL") { return (ALL_SGPRS_MASK, 0); } - let cond_write = d.inst.name == "S_CMOVK_I32"; + let cond_write = d.inst.name.starts_with("S_CMOV"); + let rmw_dst = matches!( + d.inst.name, + "S_ADDK_I32" | "S_MULK_I32" | "S_BITSET0_B32" | "S_BITSET1_B32" | "S_BITSET0_B64" | "S_BITSET1_B64" + ); let (mut u, mut def) = (0u128, 0u128); for o in d.ienc.operands { if o.ty == "OPR_SSRC_SPECIAL_SCC" { @@ -76,11 +80,16 @@ fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded) -> (u128, u128) { continue; } let n = (o.size as u64).div_ceil(32).max(1); + // Wave32 VALU mask writers (V_CMP_*, V_ADD_CO_*, etc.) only write the low SGPR; do not + // mark s[v + 1] as killed. + let def_n = if !wave64 && o.output && o.size == 64 && !d.inst.name.starts_with("S_") { 1 } else { n }; for r in v..(v + n).min(106) { - if o.input || cond_write { + if o.input || (o.output && (cond_write || rmw_dst)) { u |= 1u128 << r; } - if o.output && !cond_write { + } + if o.output && !cond_write { + for r in v..(v + def_n).min(106) { def |= 1u128 << r; } } @@ -88,19 +97,19 @@ fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded) -> (u128, u128) { (u, def) } -fn compute_live_out(cfg: &Cfg, mblocks: &[MicroBlock], end_live: u128) -> Vec { +fn compute_live_out(cfg: &Cfg, mblocks: &[MicroBlock], end_live: u128, wave64: bool) -> Vec { let n = mblocks.len(); let mut b_use = vec![0u128; n]; let mut b_def = vec![0u128; n]; for (idx, blk) in mblocks.iter().enumerate() { let (mut u, mut d) = (0u128, 0u128); for &i in &blk.insts { - let (iu, id) = inst_sreg_scc_use_def(&cfg.insts[i]); + let (iu, id) = inst_sreg_scc_use_def(&cfg.insts[i], wave64); u |= iu & !d; d |= id; } if let Term::Cond(ci, ..) = blk.term { - let (iu, _) = inst_sreg_scc_use_def(&cfg.insts[ci]); + let (iu, _) = inst_sreg_scc_use_def(&cfg.insts[ci], wave64); u |= iu & !d; } b_use[idx] = u; @@ -391,7 +400,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { // bypass empty non-header jump blocks so neither `xcl_blocks` nor `FUNCTION` pays for them. let end_live = if lw.res.is_some() { ALL_SGPRS_MASK | SCC_LIVE_BIT } else { 0 }; if allow_split { - let live_out = compute_live_out(cfg, &mblocks, end_live); + let live_out = compute_live_out(cfg, &mblocks, end_live, lw.wave64); for (idx, blk) in mblocks.iter_mut().enumerate() { if let Some(r) = resolved_far_jump_reg(cfg, blk) { let clobber = (1u128 << r) | (1u128 << (r + 1)) | SCC_LIVE_BIT; @@ -505,7 +514,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { } let final_live_out = if allow_split { - compute_live_out(cfg, &mblocks, end_live) + compute_live_out(cfg, &mblocks, end_live, lw.wave64) } else { vec![ALL_SGPRS_MASK | SCC_LIVE_BIT; mblocks.len()] }; @@ -974,3 +983,51 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block } Ok(()) } + +#[cfg(test)] +mod liveness_tests { + use super::*; + use crate::gpu::rdna2; + + fn dec(name: &str, enc: &str, fields: &[(&str, u64)]) -> rdna2::Decoded { + let bytes = rdna2::encode(name, enc, fields, None).unwrap(); + rdna2::decode(&bytes, 0).unwrap() + } + + #[test] + fn cmov_and_rmw_salu_read_sdst_and_wave32_valu_keeps_hi_sgpr() { + // S_CMOV_B32 / S_CMOV_B64: conditional write reads SDST and must not kill it. + let cmov32 = dec("S_CMOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 2)]); + let (u, d) = inst_sreg_scc_use_def(&cmov32, true); + assert_ne!(u & (1u128 << 4), 0, "S_CMOV_B32 must use SDST"); + assert_eq!(d & (1u128 << 4), 0, "S_CMOV_B32 must not kill SDST"); + + let cmov64 = dec("S_CMOV_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 2)]); + let (u, d) = inst_sreg_scc_use_def(&cmov64, true); + assert_eq!(u & ((1u128 << 6) | (1u128 << 7)), (1u128 << 6) | (1u128 << 7)); + assert_eq!(d & ((1u128 << 6) | (1u128 << 7)), 0); + + // RMW SALU ops (S_ADDK_I32, S_MULK_I32, S_BITSET0_B32, S_BITSET1_B64): both use and def SDST. + for (name, enc, fields, width) in [ + ("S_ADDK_I32", "ENC_SOPK", &[("SDST", 8), ("SIMM16", 1)][..], 1u64), + ("S_MULK_I32", "ENC_SOPK", &[("SDST", 9), ("SIMM16", 3)][..], 1u64), + ("S_BITSET0_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)][..], 1u64), + ("S_BITSET1_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)][..], 2u64), + ] { + let inst = dec(name, enc, fields); + let (u, d) = inst_sreg_scc_use_def(&inst, true); + let base = fields[0].1; + let mask = if width == 2 { (1u128 << base) | (1u128 << (base + 1)) } else { 1u128 << base }; + assert_eq!(u & mask, mask, "{name} must use SDST"); + assert_eq!(d & mask, mask, "{name} must def SDST"); + } + + // Wave32 VALU mask writer (V_CMP_EQ_U32 VOP3) writes only s4, leaving s5 live. + let vcmp = dec("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 256), ("SRC1", 257)]); + let (_, d32) = inst_sreg_scc_use_def(&vcmp, false); + assert_ne!(d32 & (1u128 << 4), 0, "Wave32 V_CMP must def s4"); + assert_eq!(d32 & (1u128 << 5), 0, "Wave32 V_CMP must not kill s5"); + let (_, d64) = inst_sreg_scc_use_def(&vcmp, true); + assert_eq!(d64 & ((1u128 << 4) | (1u128 << 5)), (1u128 << 4) | (1u128 << 5)); + } +} From 9887b414b9b302fc9e456680de208b1ac85ecad7 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:06:04 +0300 Subject: [PATCH 010/175] DXIL: trigger compact form on branch-heavy shaders to prevent driver compile commit spikes compact::large() previously only checked reachable non-terminator instruction count (>= 20_000), ignoring both terminating branches and basic-block count. Branch-heavy unrolled compute shaders just below 20k non-terminator instructions (for example, cs 56c0cd3b82a00c6e) skipped compact lowering and emitted >2.6 MiB monolithic DXIL (~588k IR lines, ~32k blocks, ~36k PHIs), causing the driver compiler to commit >36 GiB of virtual memory and stall compilation. In compact form the same shader shrinks to ~160 KiB (~975 blocks, 108 PHIs). Lower the non-terminator threshold to 10_000 and add a reachable basic-block threshold (>= 2_000) in compact::large(); compact::wanted() still gates adoption on >70% deduplication and bounded table size. (cherry picked from commit 53995420bd3e7d6ea39f0e362fd5a8d4781c37b3) Port onto nvidia-dev: `large` is asked by automatic_plan here (this branch's form of `wanted`); its doc says so instead. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 13 +++++++++++-- crates/xcl/src/gpu/dxil/compact_tests.rs | 6 +++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 93e646cbdb..f4dac90a46 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -267,9 +267,18 @@ pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { repeated.then_some(p) } -/// Whether to consider compaction based on instruction count alone. +/// Reachable non-terminator instruction count threshold for trying the compact form. +const LARGE_INSTS: usize = 10_000; +/// Reachable basic-block count threshold for trying the compact form: branch-heavy +/// unrolled programs with thousands of small blocks (even below `LARGE_INSTS` +/// non-terminator instructions) expand into tens of thousands of DXIL blocks and PHIs +/// in plain form, causing excessive driver-compiler memory commit spikes. +const LARGE_BLOCKS: usize = 2_000; + +/// Whether to consider compaction based on the reachable instruction and block counts. pub fn large(cfg: &Cfg) -> bool { - cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= 20_000 + cfg.rpo.len() >= LARGE_BLOCKS + || cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= LARGE_INSTS } pub const END: u32 = u32::MAX; diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 3cff9a054a..ea9a52a654 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -61,7 +61,11 @@ fn a_large_program_that_repeats_itself_takes_the_compact_form() { return; } let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; - for (copies, compact) in [(2500, true), (2000, false)] { + // `repeated(copies)` has 4 basic blocks and 9 non-terminator instructions per copy: + // - 2500 copies (10k blocks, 22.5k insts) and 500 copies (2k blocks, 4.5k insts) cross + // the compact threshold and take the compact form; + // - 400 copies (1.6k blocks, 3.6k insts) stay below both thresholds and keep plain form. + for (copies, compact) in [(2500, true), (500, true), (400, false)] { assert_eq!(translate_full(&repeated(copies), o).unwrap().dxil.len(), size(copies, o, compact), "{copies} copies"); } } From 6fa964decc15945f32d736046e9026a552995f35 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:31:19 +0100 Subject: [PATCH 011/175] WIP: nvdev-shrink working tree as of nvs-run39 (2026-11-27) Snapshot of uncommitted work inherited from the previous agent session: ps_masks, rt_leave_out, ambient, format_alias, gpu_awake, vram_small and related d3d12x/dxil/recomp changes. Local safety commit, not for review. Co-Authored-By: Claude Mythos 5.2 --- crates/xcl/src/gpu/dxil/compact.rs | 1 + crates/xcl/src/gpu/dxil/core_tests.rs | 158 +- crates/xcl/src/gpu/dxil/graphics.rs | 40 +- crates/xcl/src/gpu/dxil/graphics_tests.rs | 107 + crates/xcl/src/gpu/dxil/kernel.rs | 100 +- crates/xcl/src/gpu/dxil/lanes.rs | 45 +- crates/xcl/src/gpu/dxil/lower.rs | 13 +- crates/xcl/src/gpu/dxil/lower_geom.rs | 5 +- crates/xcl/src/gpu/dxil/lower_gfx.rs | 60 +- crates/xcl/src/gpu/dxil/lower_image.rs | 56 +- crates/xcl/src/gpu/dxil/lower_mem.rs | 51 +- crates/xcl/src/gpu/dxil/lower_valu.rs | 251 ++- crates/xcl/src/gpu/dxil/module/opt.rs | 88 +- crates/xcl/src/gpu/dxil/module/split.rs | 21 +- crates/xcl/src/gpu/dxil/prelude.rs | 104 +- crates/xcl/src/gpu/dxil/reload.rs | 38 + crates/xcl/src/gpu/dxil/robustness_tests.rs | 3 +- crates/xcl/src/gpu/mod.rs | 1 + crates/xcl/src/gpu/recomp/emit.rs | 122 +- .../xcl/src/gpu/recomp/heap_window_tests.rs | 4 +- crates/xcl/src/gpu/recomp/mod.rs | 145 +- crates/xcl/src/gpu/recomp/ps_masks.rs | 581 +++++ crates/xcl/src/gpu/recomp/pso.rs | 30 +- crates/xcl/src/gpu/recomp/runner.rs | 34 +- crates/xcl/src/gpu/recomp/tests.rs | 102 +- crates/xcl/src/gpu/recomp/x64_masks.rs | 128 +- crates/xcl/src/gpu/rt_leave_out.rs | 183 ++ crates/xcl/src/hle/bcpack/victory.rs | 35 +- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 120 +- crates/xcl/src/hle/d3d12x/ambient.rs | 1949 +++++++++++++++++ crates/xcl/src/hle/d3d12x/bind.rs | 278 ++- crates/xcl/src/hle/d3d12x/console_heap.rs | 3 + crates/xcl/src/hle/d3d12x/depth_uav.rs | 534 ++++- crates/xcl/src/hle/d3d12x/device_x.rs | 10 +- crates/xcl/src/hle/d3d12x/dred.rs | 8 + crates/xcl/src/hle/d3d12x/format_alias.rs | 1689 ++++++++++++++ crates/xcl/src/hle/d3d12x/gpu_awake.rs | 412 ++++ crates/xcl/src/hle/d3d12x/indirect_guard.rs | 2 + crates/xcl/src/hle/d3d12x/late_release.rs | 1 + crates/xcl/src/hle/d3d12x/list_x.rs | 164 +- crates/xcl/src/hle/d3d12x/mod.rs | 4 + crates/xcl/src/hle/d3d12x/present.rs | 30 +- crates/xcl/src/hle/d3d12x/real.rs | 600 ++++- crates/xcl/src/hle/d3d12x/sparse.rs | 173 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 9 + crates/xcl/src/hle/d3d12x/vram.rs | 1056 ++++++++- crates/xcl/src/hle/d3d12x/vram_small.rs | 677 ++++++ crates/xcl/src/hle/kernelx.rs | 21 + crates/xcl/src/shaders.rs | 28 +- 49 files changed, 9911 insertions(+), 363 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/ps_masks.rs create mode 100644 crates/xcl/src/gpu/rt_leave_out.rs create mode 100644 crates/xcl/src/hle/d3d12x/ambient.rs create mode 100644 crates/xcl/src/hle/d3d12x/format_alias.rs create mode 100644 crates/xcl/src/hle/d3d12x/gpu_awake.rs create mode 100644 crates/xcl/src/hle/d3d12x/vram_small.rs diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index f4dac90a46..2f4f426bf2 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -556,6 +556,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); } + key.push(lw.ps_masks.get(&d.pc).map_or(0, |&f| f as u64 + 1)); if d.inst.name == "S_GETPC_B64" { key.push(if param_pc { d.pc.wrapping_sub(blk.pc) } else { d.pc }); } diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index b39ba4091a..a237b2170a 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -65,7 +65,7 @@ fn a_single_split_wave_of_a_compute_group_exchanges_without_a_group_barrier() { {d}"); // a mesh program's compute pass of one console wave (48 or 64 threads) exchanges the same way for threads in [48, 64] { - let ms = crate::gpu::recomp::MsInterface { outputs: vec![], threads, max_vertices: 64, max_primitives: 64 }; + let ms = crate::gpu::recomp::MsInterface { outputs: vec![], threads, max_vertices: 64, max_primitives: 64, params: None }; let d = super::validate::disassemble(&super::kernel::translate_mesh(&code, o, &ms).unwrap_or_else(|e| panic!("mesh, {threads} threads: {e}")).dxil).unwrap(); assert_eq!(syncs(&d), 1, "mesh, {threads} threads: a group barrier at the exchange: {d}"); @@ -280,6 +280,7 @@ fn direct_and_hlsl_graphics_stages_link() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let (vo, po) = (Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }, Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }); let hvs = crate::gpu::recomp::dxc::compile(&translate(&vs_code, &vo).unwrap().hlsl, "main", "vs_6_6", &[]).unwrap(); @@ -300,6 +301,131 @@ fn direct_and_hlsl_graphics_stages_link() { assert_eq!(draw(&hvs, &dps), want, "HLSL VS + direct PS"); } +/// Float16 interpolants packed two per dword, two registers in one attribute (TEXCOORD1.xyz +/// and TEXCOORD4.xyzw in attribute 0, as a retail title's world shaders have them): the PS +/// reads each half with `v_interp_p2_f16` (SRC0 bit 8: the high half) and gets that component +/// of its own element interpolated across the triangle; the float attribute after the pair +/// keeps its register. The console VS exports the packed dwords as param 0 and unpacks them +/// into the same components. Every combination of the direct and the HLSL stages, and a PC VS. +/// Before: the tables were refused, the PS converted the raw packed dword of a +/// `nointerpolation` input and attribute 1 was read from TEXCOORD4. +#[test] +fn f16_packed_attributes_interpolate_per_half() { + use crate::gpu::dxbc::SigElement as S; + use crate::gpu::recomp::{runner, translate, Mode, Options, OutParam, PsAttr, PsInterface, VsInterface}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; + if !super::graphics::tests::draw_ready() { + return; + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let el = |name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8| S { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 }; + const V: u64 = 256; + // COLOR c in v8..v11 -> halves h0..h3 in v12..v15; param 0 = (h0 | h1 << 16, h2, h3 | h0 << 16, + // h1 | h2 << 16): TEXCOORD1 = (c0, c1, c2), TEXCOORD4 = (c3, c0, c1, c2); param 1 = c reversed + let mut vs_ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 3), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", vec![("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ]; + for i in 0..4u64 { + vs_ops.push(("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 12 + i), ("SRC0", V + 8 + i)], None)); + } + for (dst, lo, hi) in [(16u64, 12u64, 13u64), (18, 15, 12), (19, 13, 14)] { + vs_ops.push(("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", dst), ("SRC0", V + lo), ("SRC1", V + hi)], None)); + } + vs_ops.push(("EXP", "ENC_EXP", vec![("TGT", 32), ("EN", 0xF), ("VSRC0", 16), ("VSRC1", 14), ("VSRC2", 18), ("VSRC3", 19)], None)); + vs_ops.push(("EXP", "ENC_EXP", vec![("TGT", 33), ("EN", 0xF), ("VSRC0", 11), ("VSRC1", 10), ("VSRC2", 9), ("VSRC3", 8)], None)); + let vs_list: Vec<(&str, &str, &[(&str, u64)], Option)> = vs_ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + let vs_code = prog(&vs_list); + let user = vec![el("TEXCOORD", 1, 0, 6, 1, 0x7), el("TEXCOORD", 4, 0, 6, 2, 0xF), el("TEXCOORD", 3, 0, 3, 3, 0xF)]; + let vsi = VsInterface { + inputs: vec![el("POSITION", 0, 0, 3, 0, 3), el("COLOR", 0, 0, 3, 1, 0xF)], + outputs: std::iter::once(el("SV_Position", 0, 1, 3, 0, 0xF)).chain(user.iter().cloned()).collect(), + attr_base: 4, + params: Some(vec![OutParam { register: 1, f16: true, pair: true }, OutParam { register: 3, f16: false, pair: false }]), + }; + // a PC VS handing over each component as a float: COLOR c -> TEXCOORD1 = (c0, c1, c2, 0), + // TEXCOORD4 = (c3, c0, c1, c2), TEXCOORD3 = c reversed + let pc_vs = "struct I { float2 pos : POSITION; float4 c : COLOR0; };\nstruct O { float4 pos : SV_Position; float4 t1 : TEXCOORD1; float4 t4 : TEXCOORD4; float4 t3 : TEXCOORD3; };\nO main(I i) { O o; o.pos = float4(i.pos, 0.0, 1.0); o.t1 = float4(i.c.xyz, 0.0); o.t4 = float4(i.c.w, i.c.xyz); o.t3 = i.c.wzyx; return o; }\n"; + let pvs = crate::gpu::recomp::dxc::compile(pc_vs, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pc_vs}")); + let psi = PsInterface { + inputs: std::iter::once(el("SV_Position", 0, 1, 3, 0, 0xF)).chain(user.iter().cloned()).collect(), + outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: Some(vec![ + PsAttr { kind: 6, register: 1, mask: 3, flat: false, f16: true, pair: Some(2) }, + PsAttr { kind: 6, register: 3, mask: 0xF, flat: false, f16: false, pair: None }, + ]), + early_depth: false, + }; + // a PS returning four values: Some((dword, high)) of attribute 0, None: attr1[k] as f32 + let ps_code = |sel: [Option<(u64, u64)>; 4]| { + let mut ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for (k, s) in sel.iter().enumerate() { + let k = k as u64; + match *s { + Some((chan, high)) => { + let attr = chan << 6 | high << 8; + ops.push(("V_INTERP_P1LL_F16", "ENC_VOP3", vec![("VDST", 8 + k), ("SRC1", V), ("SRC0", attr)], None)); + ops.push(("V_INTERP_P2_F16", "ENC_VOP3", vec![("VDST", 4 + k), ("SRC1", V + 1), ("SRC0", attr), ("SRC2", V + 8 + k)], None)); + ops.push(("V_CVT_F32_F16", "ENC_VOP1", vec![("VDST", 4 + k), ("SRC0", V + 4 + k)], None)); + } + None => { + ops.push(("V_INTERP_P1_F32", "ENC_VINTRP", vec![("VDST", 4 + k), ("VSRC", 0), ("ATTR", 1), ("ATTRCHAN", k)], None)); + ops.push(("V_INTERP_P2_F32", "ENC_VINTRP", vec![("VDST", 4 + k), ("VSRC", 1), ("ATTR", 1), ("ATTRCHAN", k)], None)); + } + } + } + ops.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + let list: Vec<(&str, &str, &[(&str, u64)], Option)> = ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + prog(&list) + }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let vt = translate(&vs_code, &Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(vt.complete(), "{:?}", vt.unsupported_why); + let hvs = crate::gpu::recomp::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl)); + let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap().dxil; + // COLOR = (x, y, x / 4 + 1 / 2, y / 2 - 1 / 4) at each vertex: exact in float16, and linear + // in the pixel's position + let color = |x: f32, y: f32| [x, y, 0.25 * x + 0.5, 0.5 * y - 0.25]; + let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1]].into_iter().chain(color(p[0], p[1]))).collect(); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 }, + ]; + // what each selection reads, as indices into COLOR (4: nothing declared there, 0) + let cases: [([Option<(u64, u64)>; 4], [usize; 4], &str); 4] = [ + ([Some((0, 0)), Some((0, 1)), Some((1, 0)), Some((2, 0))], [0, 1, 2, 3], "TEXCOORD1.xyz, TEXCOORD4.x"), + ([Some((2, 1)), Some((3, 0)), Some((3, 1)), Some((1, 1))], [0, 1, 2, 4], "TEXCOORD4.yzw, TEXCOORD1.w"), + ([Some((3, 1)), Some((2, 0)), Some((0, 1)), Some((0, 0))], [2, 3, 1, 0], "both registers, mixed halves"), + ([None, None, None, None], [3, 2, 1, 0], "the float attribute after the pair"), + ]; + for (sel, want, what) in cases { + let code = ps_code(sel); + let pt = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(pt.complete(), "{what}: {:?}", pt.unsupported_why); + assert!(!pt.hlsl.contains("nointerpolation"), "{what}: the float16 inputs interpolate\n{}", pt.hlsl); + let hps = crate::gpu::recomp::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + let dps = super::kernel::translate_pixel(&code, ko, &psi).unwrap().dxil; + let pairs = [("PC VS + HLSL PS", &pvs, &hps), ("PC VS + direct PS", &pvs, &dps), ("HLSL VS + HLSL PS", &hvs, &hps), ("direct VS + direct PS", &dvs, &dps), ("direct VS + HLSL PS", &dvs, &hps), ("HLSL VS + direct PS", &hvs, &dps)]; + for (stages, vs, ps) in pairs { + let px = runner::draw(vs, ps, &layout, &verts, 24, &[], &[], 8, [9.0; 4]).unwrap(); + for y in 0..8usize { + for x in 0..8usize { + let c = color((x as f32 + 0.5) / 4.0 - 1.0, 1.0 - (y as f32 + 0.5) / 4.0); + let expected = want.map(|k| if k == 4 { 0.0 } else { c[k] }); + let got = px[y * 8 + x]; + assert!(got.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3), "{what}, {stages}: pixel ({x},{y}) = {got:?}, expected {expected:?}"); + } + } + } + } +} + fn sig(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gpu::dxbc::SigElement { crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } } @@ -328,7 +454,7 @@ fn branchy_graphics_stages_validate() { } // v2 = front face (SPI_PS_INPUT_ENA bit 12 after the two I/J pairs of 0x3) let ps_code = body(("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 2), ("VSRC3", 5), ("DONE", 1), ("VM", 1)], None)); - let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x1002, attrs: None }; + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x1002, attrs: None, early_depth: false }; for wave64 in [true, false] { super::kernel::translate_pixel(&ps_code, KernelOptions { wave64, ..ko }, &psi).unwrap_or_else(|e| panic!("PS wave64 {wave64}: {}", &e[..e.len().min(800)])); } @@ -351,7 +477,7 @@ fn long_pixel_shader_translates_fast() { list.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let code = prog(&refs); - let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None, early_depth: false }; let t = std::time::Instant::now(); let k = super::kernel::translate_pixel(&code, KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); println!("3000 instructions: {:?}, {} B", t.elapsed(), k.dxil.len()); @@ -401,6 +527,7 @@ fn graphics_stages_with_a_branch_before_their_exports() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap_or_else(|e| panic!("VS: {}", &e[..e.len().min(600)])).dxil; @@ -588,7 +715,7 @@ fn ps_get_lod_with_a_static_sampler() { list.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let code = prog(&refs); - let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None, early_depth: false }; let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample"); @@ -1236,6 +1363,7 @@ fn raw_loads_in_root_windows_are_branchless() { outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None, + early_depth: false, }; let ps_k = super::kernel::translate_pixel(&ps_code, KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }, &psi) .expect("pixel shader multi-window load translates"); @@ -1387,3 +1515,25 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { } } } + +/// scratch_* on RDNA2: SADDR 0x7F (EXEC_HI) is the ST form (the offset alone) and an SGPR the +/// SS form, neither reads ADDR; NULL (0x7D) is SV, VADDR + offset. A program differing only +/// in ADDR translates to the same container exactly when ADDR is not read. +#[test] +fn scratch_reads_addr_only_in_the_sv_form() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let kernel = |saddr: u64, addr: u64| { + let code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 135)], None), // v2 = 7 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 137)], None), // v3 = 9 + ("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", addr), ("DATA", 0), ("SADDR", saddr), ("OFFSET", 16)], None), + ("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 4), ("ADDR", addr), ("SADDR", saddr), ("OFFSET", 20)], None), + ]); + translate(&code, ko).unwrap_or_else(|e| panic!("SADDR {saddr:#x} ADDR v{addr}: {e}")) + }; + for (saddr, form) in [(0x7F, "ST"), (4, "SS")] { + assert!(kernel(saddr, 2) == kernel(saddr, 3), "{form} (SADDR {saddr:#x}) must not read ADDR"); + } + assert!(kernel(0x7D, 2) != kernel(0x7D, 3), "SV (SADDR 0x7d) addresses VADDR + offset"); + assert!(kernel(0x7F, 2) != kernel(0x7D, 2), "ST is not the SV form"); +} diff --git a/crates/xcl/src/gpu/dxil/graphics.rs b/crates/xcl/src/gpu/dxil/graphics.rs index 239a923ea9..5dcf2f1752 100644 --- a/crates/xcl/src/gpu/dxil/graphics.rs +++ b/crates/xcl/src/gpu/dxil/graphics.rs @@ -1008,11 +1008,47 @@ impl Shader { sfi0 |= 0x10; } // Bound UAVs outside pixel/compute shaders (DXC: not for mesh shaders, - // nor for heap-indexed UAVs). - if self.stage == Stage::Vertex && self.bindings.iter().any(|b| b.class == ResClass::Uav) { + // nor for heap-indexed UAVs); >8 static UAVs require the 64-UAVs flag on every stage. + let uav_count = self.bindings.iter().filter(|b| b.class == ResClass::Uav).count(); + if self.stage == Stage::Vertex && uav_count > 0 { flags |= 1 << 16; sfi0 |= 0x4; } + if uav_count > 8 { + flags |= 1 << 15; + sfi0 |= 0x8; + } + if match self.stage { + Stage::Vertex => outs.iter().any(|e| e.e.kind == SemKind::ShadingRate), + Stage::Pixel => ins.iter().any(|e| e.e.kind == SemKind::ShadingRate), + _ => false, + } { + flags |= 1 << 24; + sfi0 |= 0x8_0000; + } + if matches!(self.stage, Stage::Pixel | Stage::Mesh) { + let (mut inner_cov, mut mesh_deriv) = (false, false); + for b in 0..self.m.block_count() { + for &inst in self.m.block_insts(Block(b as u32)) { + let InstInfo::Call(name, args) = self.m.inst_info(inst) else { continue }; + let op = args.first().and_then(|&v| self.m.const_u64(v)); + inner_cov |= name.starts_with("dx.op.innerCoverage.") && op == Some(92); + mesh_deriv |= (name.starts_with("dx.op.unary.") && op.is_some_and(|o| (83..=86).contains(&o))) + || (name.starts_with("dx.op.sample.") && op == Some(60)) + || (name.starts_with("dx.op.sampleBias.") && op == Some(61)) + || (name.starts_with("dx.op.sampleCmp.") && op == Some(64)) + || (name.starts_with("dx.op.calculateLOD.") && op == Some(81)); + } + } + if self.stage == Stage::Mesh && mesh_deriv { + flags |= 1 << 29; + sfi0 |= 0x100_0000; + } + if self.stage == Stage::Pixel && inner_cov { + flags |= 1 << 10; + sfi0 |= 0x400; + } + } if self.stage == Stage::Pixel { if outs.iter().any(|e| e.e.kind == SemKind::StencilRef) { flags |= 1 << 11; diff --git a/crates/xcl/src/gpu/dxil/graphics_tests.rs b/crates/xcl/src/gpu/dxil/graphics_tests.rs index c8f3802053..8228f179e2 100644 --- a/crates/xcl/src/gpu/dxil/graphics_tests.rs +++ b/crates/xcl/src/gpu/dxil/graphics_tests.rs @@ -1236,3 +1236,110 @@ fn ps_static_resources_match_dxc() { assert_eq!(part(&c, b"SFI0"), part(DXC_PS_RESOURCES, b"SFI0")); assert_valid(&c); } + +fn assert_flags(c: &[u8], want_sfi0: u64, want_meta: u64, label: &str) { + assert_eq!(u64::from_le_bytes(part(c, b"SFI0").unwrap().try_into().unwrap()), want_sfi0, "{label}: SFI0"); + assert_valid(c); + if crate::gpu::recomp::dxc::location().is_ok() { + let dis = validate::disassemble(c).unwrap(); + let ok = if want_meta != 0 { dis.contains(&format!("!{{i32 0, i64 {want_meta}}}")) || dis.contains(&format!("!{{i32 0, i64 {want_meta},")) } else { !dis.contains("!{i32 0, i64 ") }; + assert!(ok, "{label}: meta {want_meta:#x} in:\n{dis}"); + } +} + +fn finish_ms_with(mut s: Shader, mut io: GraphicsIo, x: Value, prim: Option) -> Vec { + let pos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let (c0, c1, c2, c3, z) = (s.m.i32c(0), s.m.i32c(1), s.m.i32c(2), s.m.i32c(3), f(&mut s, 0.0)); + io.set_mesh_output_counts(&mut s, c3, c1); + for (c, &v) in [x, z, z, z].iter().enumerate() { io.store_vertex_output(&mut s, pos, 0, c as u8, v, c0); } + io.emit_indices(&mut s, c0, &[c0, c1, c2]); + if let Some(p) = prim { io.store_primitive_output(&mut s, p, 0, 0, c0, c0); } + s.finish_graphics(io, StageInfo::Mesh { numthreads: [4, 1, 1], max_vertices: 3, max_primitives: 1, topology: Topology::Triangle, payload_bytes: 0 }) +} + +#[test] +fn ps_inner_coverage_sets_flag_only_when_live() { + for live in [true, false] { + let (mut s, mut io) = (Shader::new(Stage::Pixel, (6, 6)), GraphicsIo::new(Stage::Pixel)); + let t = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::U32, 1)); + let out = if live { io.inner_coverage(&mut s) } else { + let (dead, cont) = (s.m.new_block(), s.m.new_block()); + s.m.br(cont); s.m.set_block(dead); let _ = io.inner_coverage(&mut s); s.m.br(cont); s.m.set_block(cont); + s.m.i32c(0) + }; + io.store_output(&mut s, t, 0, 0, out); + let c = s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }); + assert_flags(&c, if live { 0x400 } else { 0 }, if live { 1 << 10 } else { 0 }, if live { "ps_inner_cov_live" } else { "ps_inner_cov_dead" }); + } +} + +#[test] +fn shading_rate_sets_flag_for_vs_and_ps_but_not_ms() { + let (mut vs, mut vio) = (Shader::new(Stage::Vertex, (6, 6)), GraphicsIo::new(Stage::Vertex)); + let vp = vio.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let vr = vio.output(SigElement::new("SV_ShadingRate", 0, SemKind::ShadingRate, CompType::U32, 1)); + let (z, r) = (f(&mut vs, 0.0), vs.m.i32c(0)); + for c in 0..4 { vio.store_output(&mut vs, vp, 0, c, z); } + vio.store_output(&mut vs, vr, 0, 0, r); + assert_flags(&vs.finish_graphics(vio, StageInfo::Vertex), 0x8_0000, 1 << 24, "vs_shading_rate"); + let (mut ps, mut pio) = (Shader::new(Stage::Pixel, (6, 6)), GraphicsIo::new(Stage::Pixel)); + let _ = pio.input(SigElement::new("SV_ShadingRate", 0, SemKind::ShadingRate, CompType::U32, 1)); + let pt = pio.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::U32, 1)); + let pz = ps.m.i32c(0); + pio.store_output(&mut ps, pt, 0, 0, pz); + assert_flags(&ps.finish_graphics(pio, StageInfo::Pixel { early_depth_stencil: false }), 0x8_0000, 1 << 24, "ps_shading_rate"); + let (mut ms, mut mio) = (Shader::new(Stage::Mesh, (6, 6)), GraphicsIo::new(Stage::Mesh)); + let mr = mio.primitive(SigElement::new("SV_ShadingRate", 0, SemKind::ShadingRate, CompType::U32, 1)); + let mz = f(&mut ms, 0.0); + assert_flags(&finish_ms_with(ms, mio, mz, Some(mr)), 0, 0, "ms_shading_rate"); +} + +#[test] +fn ms_derivatives_and_implicit_lod_set_flag_but_explicit_lod_does_not() { + use crate::gpu::dxil::ops::{CompType as OpsComp, Deriv, TexKind}; + for kind in ["deriv", "sample", "sample_bias", "sample_cmp", "calc_lod", "sample_level", "dead_deriv"] { + let (mut s, io) = (Shader::new(Stage::Mesh, (6, 6)), GraphicsIo::new(Stage::Mesh)); + let (tid, f32, z) = (s.thread_id_in_group(0), s.m.f32(), f(&mut s, 0.0)); + let u = s.m.cast(CastOp::UIToFP, tid, f32); + let val = if kind == "deriv" { s.deriv(Deriv::FineX, u) } else if kind == "dead_deriv" { let _ = s.deriv(Deriv::FineX, u); z } else { + let (tex, smp) = (s.srv_texture(0, 0, TexKind::D2, OpsComp::F32, 4), s.sampler(0, 0, kind == "sample_cmp")); + match kind { + "sample" => s.sample(tex, smp, &[u, z], &[], None)[0], + "sample_bias" => s.sample_bias(tex, smp, &[u, z], &[], z, None)[0], + "sample_cmp" => s.sample_cmp(tex, smp, &[u, z], &[], z, None)[0], + "calc_lod" => s.calculate_lod(tex, smp, &[u, z], true), + _ => s.sample_level(tex, smp, &[u, z], &[], z)[0], + } + }; + let needs = !matches!(kind, "sample_level" | "dead_deriv"); + assert_flags(&finish_ms_with(s, io, val, None), if needs { 0x100_0000 } else { 0 }, if needs { 1 << 29 } else { 0 }, kind); + } +} + +#[test] +fn graphics_64_uavs_flag_tracks_static_uav_count() { + const RAW: u64 = 1 << 4; + let run = |stage: Stage, slots: &[u32]| { + let (mut s, mut io) = (Shader::new(stage, (6, 6)), GraphicsIo::new(stage)); + let (z, mut acc) = (s.m.i32c(0), s.m.i32c(0)); + for &u in slots { let h = s.raw_uav(u, 0); let v = s.raw_load(h, z, 1)[0]; acc = s.m.bin(BinOp::Add, acc, v); } + if stage == Stage::Pixel { + let t = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::U32, 1)); + io.store_output(&mut s, t, 0, 0, acc); + return s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }); + } + let vf = { let t = s.m.f32(); s.m.cast(CastOp::UIToFP, acc, t) }; + if stage == Stage::Mesh { return finish_ms_with(s, io, vf, None); } + let p = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + for c in 0..4 { io.store_output(&mut s, p, 0, c, vf); } + s.finish_graphics(io, StageInfo::Vertex) + }; + let (nine, eight): (Vec, Vec) = ((0..9).collect(), (0..8).collect()); + for (st, slots, sfi, meta, lbl) in [ + (Stage::Vertex, &nine[..], 0xC, (1 << 15) | (1 << 16) | RAW, "vs_9uav"), + (Stage::Pixel, &nine[..], 0x8, (1 << 15) | RAW, "ps_9uav"), + (Stage::Mesh, &nine[..], 0x8, (1 << 15) | RAW, "ms_9uav"), + (Stage::Pixel, &eight[..], 0, RAW, "ps_8uav"), + (Stage::Pixel, &[8][..], 0, RAW, "ps_single_u8"), + ] { assert_flags(&run(st, slots), sfi, meta, lbl); } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index e36381b547..1885243650 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -68,12 +68,60 @@ pub struct Kernel { pub dispatch_chain: Option>, } +pub use super::lower_gfx::nan_guard_enabled; pub use super::module::split::DispatchChain; pub fn dispatch_piece_limit() -> usize { std::env::var("XCL_DIRECT_SPLIT_INSTRUCTIONS").ok().and_then(|s| s.parse().ok()).unwrap_or(12_500) } +/// `XCL_RT_GATE=miss`: every `image_bvh*_intersect_ray` misses (the four result dwords all ones, +/// as for a null BVH). Ray-tracing programs then run and write what they write when no ray hits +/// anything, instead of reading half-built/unmapped BVHs or leaving lighting outputs unwritten. +pub fn rt_all_miss() -> bool { + #[cfg(test)] + if let Some(on) = RT_ALL_MISS_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_RT_GATE").is_ok_and(|v| v.trim().eq_ignore_ascii_case("miss"))) +} + +#[cfg(test)] +thread_local! { + /// `rt_all_miss` for the translations of this test thread + pub(crate) static RT_ALL_MISS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Loop iterations a lane of a ray-tracing program may run with `XCL_RT_GATE=miss`. +pub const RT_LOOP_BUDGET: u32 = 1 << 9; + +thread_local! { + /// The translation on this thread is of a ray-tracing program (`with_rt_program`). + static RT_PROGRAM: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// `f` with the translations it makes on this thread taken as of a ray-tracing program (`rt`). +pub fn with_rt_program(rt: bool, f: impl FnOnce() -> R) -> R { + let before = RT_PROGRAM.with(|c| c.replace(rt)); + let r = f(); + RT_PROGRAM.with(|c| c.set(before)); + r +} + +/// The loop budget a lane starts with in the program being translated. +pub fn loop_budget() -> u32 { + if RT_PROGRAM.with(|c| c.get()) && rt_all_miss() { + RT_LOOP_BUDGET + } else { + super::lower::LOOP_BUDGET + } +} + +fn has_bvh_inst(insts: &[Decoded]) -> bool { + insts.iter().any(|d| d.inst.name.contains("BVH")) +} + /// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset uses automatic selection. pub fn compact_mode() -> Option { match std::env::var("XCL_DIRECT_COMPACT").as_deref() { @@ -210,7 +258,7 @@ fn translate_entry_with( fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec, Option) { let heap = mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0; let max = if heap { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; - let n = (mem_windows & !crate::gpu::recomp::HEAP_WINDOWS).clamp(1, max); + let n = (mem_windows & !(crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT)).clamp(1, max); if heap && n > 1 { let z = s.m.i32c(0); return (vec![RawUav { handle: z, binding: None }; n as usize], Some(coherent)); @@ -235,11 +283,31 @@ fn translate_on_this_thread( None => Cfg::build(code)?, }; let kernel = matches!(entry, Entry::Kernel); - let follow_loads = matches!(entry, Entry::Kernel | Entry::Compute(_)); + let follow_loads = matches!(entry, Entry::Kernel | Entry::Compute(_) | Entry::Vertex(_) | Entry::Pixel(_)); let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); let compute = matches!(entry, Entry::Compute(_)); let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); + let rt_prog = compute && rt_all_miss() && has_bvh_inst(&cfg.insts); + with_rt_program(rt_prog, || translate_on_this_thread_inner(cfg, geo, o, entry, compact, nest, rodata, leaders, kernel, follow_loads, gfx, compute, split)) +} + +#[allow(clippy::too_many_arguments)] +fn translate_on_this_thread_inner( + cfg: Cfg, + geo: Option, + o: KernelOptions, + entry: Entry, + compact: Option, + nest: Option, + rodata: Vec<(u32, Vec)>, + leaders: BTreeSet, + kernel: bool, + follow_loads: bool, + gfx: bool, + compute: bool, + split: bool, +) -> Result { let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); lw.rodata = rodata; let uses_lds = lw.lds.is_some(); @@ -587,6 +655,7 @@ impl Lw { half: z, mems, heap_mem, + heap_flat: heap_mem.is_some() && o.mem_windows & crate::gpu::recomp::HEAP_FLAT != 0, res, fmt_table: None, rodata: Vec::new(), @@ -605,6 +674,7 @@ impl Lw { track_frexp_denorm: crate::gpu::recomp::emit::tracks_frexp_f32_denorm(insts), has_f64_round_op: false, img_writes: crate::gpu::recomp::emit::image_write_srsrcs(insts), + barrier_uav_fence: crate::gpu::recomp::emit::has_uav_write_or_glc(insts), max_vgpr: insts .iter() .flat_map(|d| { @@ -635,6 +705,7 @@ impl Lw { gfx: None, gfx_half: None, whole_live: Default::default(), + ps_masks: Default::default(), guard_override: None, mask_override: None, local_masks: false, @@ -688,6 +759,9 @@ impl Lw { if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); } + if matches!(entry, Entry::Pixel(_)) && !split && std::env::var("XCL_PS_MASKS").map_or(true, |v| v.trim() != "0") { + lw.ps_masks = crate::gpu::recomp::ps_masks::forms(insts); + } // (before the storage: the spin exchange has its own slots and counters) if let (Some(t), true) = (group_threads, split) { lw.partner = match t { @@ -720,9 +794,13 @@ impl Lw { let mut dispatch_chain = None; let c = if matches!(stage, Stage::Vertex | Stage::Pixel) { let g = self.gfx.take().ok_or("graphics entry without graphics I/O")?; - let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; + let early_depth_stencil = g.ps.as_ref().is_some_and(|p| p.early_depth); + let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil } } else { super::graphics::StageInfo::Vertex }; self.s.try_finish_graphics(g.io, info) - } else if limit > 0 && (numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32 { + } else if limit > 0 + && (((numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32) + || (numthreads == [64, 1, 1] && hw == 64 && split_tid.is_none())) + { self.s.m.optimize(); // A single split wave64 meets its other half through group-shared counters its entry // zeroes (`Partner::Spin`), and the exchange's running number counts from the @@ -738,7 +816,7 @@ impl Lw { } } } else { - dispatch_chain = self.s.split_compute(numthreads, split_tid, limit).map(std::sync::Arc::new); + dispatch_chain = self.s.split_compute(numthreads, split_tid, hw, limit).map(std::sync::Arc::new); } self.s.finish_optimized(numthreads, Some(hw)) } else { @@ -783,10 +861,14 @@ fn dispatch_chain_native_wave64_builds_whole() { } lw.s.m.ret(); lw.s.m.optimize(); - // Exercise the native-wave admission gate with an otherwise partitionable CFG. + // Native Wave64 [64, 1, 1] without LDS/barriers splits into validated WaveSize(64) pieces. assert!(lw.s.m.dispatch_plan(64).is_some()); let program = lw.finish_dispatch(threads, 64, 64, None).unwrap(); - assert!(program.dispatch_chain.is_none()); + let chain = program.dispatch_chain.as_ref().expect("native wave64 [64,1,1] splits into DispatchChain"); + assert!(chain.pieces.len() >= 2); + for piece in &chain.pieces { + super::validate::validate(piece).expect("valid native wave64 split piece"); + } super::validate::validate(&program.dxil).expect("valid native wave64 whole shader"); if !runner::wave64_supported().unwrap_or(false) { @@ -886,7 +968,7 @@ fn a_dispatch_chain_leaves_the_lanes_past_a_thread_limit_out() { lw.s.m.set_block(Block(0)); lw.s.m.br(gate); lw.s.m.optimize(); - let chain = lw.s.split_compute(threads, None, 64).expect("a chain of pieces"); + let chain = lw.s.split_compute(threads, None, 32, 64).expect("a chain of pieces"); assert!(chain.pieces.len() >= 2); // the limits are read once, by the first piece let load = format!("i32 {}, i32 undef, i8 7, i32 4)", IO_THREAD_LIMIT[0] * 4); @@ -1182,7 +1264,7 @@ pub fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::R let mut vgpr = HashMap::new(); vgpr.insert(5, v5); lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); - lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, vok, pok, outputs: ms.outputs.clone() }); + lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, vok, pok, outputs: ms.outputs.clone(), params: ms.params.clone() }); } /// EXEC at entry: the console wave's threads (static per wave in the split form: no diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index dda789481b..64af7cc099 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -550,6 +550,33 @@ impl Lw { (lo, hi) } + /// Pixel-shader mask with only the live lanes' bits right besides this lane's own + /// (`recomp::ps_masks`; parity with HLSL `ballot_px_local`): `WaveActiveBallot`, which + /// leaves helper lanes out, OR this lane's bit; `own_only` leaves out the ballot too. + pub fn ballot_ps_local(&mut self, cond: Value, own_only: bool) -> (Value, Value) { + let z = self.c(0); + let b = self.u(cond); + let l31 = self.lane31; + let b = self.bin(BinOp::Shl, b, l31); + let (mut lo, mut hi) = if self.wave64 { + let u = self.upper; + (self.sel(u, z, b), self.sel(u, b, z)) + } else { + (b, z) + }; + if !own_only { + let w = self.s.wave_ballot(cond); + let (wl, wh) = match (self.wave64, self.gfx_half) { + (true, _) => (w[0], w[1]), + (false, Some(h)) => (self.sel(h, w[1], w[0]), z), + (false, None) => (w[0], z), + }; + lo = self.or(lo, wl); + hi = self.or(hi, wh); + } + (lo, hi) + } + /// Pixel-shader ballot from a precomputed 4-bit quad mask `q` (bit `p` = member `p`'s /// predicate, identical across all 4 lanes of each quad; parity with HLSL `ballot_px_quad` /// in `recomp/emit.rs`): 4 `WaveActiveBallot` passes spread each quad's member `p` from @@ -755,6 +782,16 @@ impl Lw { } self.first_lane(lo, hi) } + + /// `v_readfirstlane_b32`'s result `first` of `own` in a pixel shader: a helper lane takes its + /// own value instead so helper-only waterfall loops converge in one pass on AMD RDNA4. + pub fn helper_reads_own(&mut self, own: Value, first: Value) -> Value { + let Some(g) = self.gfx.as_mut().filter(|g| g.ps.is_some()) else { + return first; + }; + let helper = g.io.is_helper_lane(&mut self.s); + self.sel(helper, own, first) + } } #[cfg(test)] @@ -772,7 +809,7 @@ mod ps_ballot_tests { } fn ps_interface() -> PsInterface { - PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None } + PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false } } /// Pixel shader exercising `s_wqm`, `v_cndmask` + DPP `ddx`, `s_and_saveexec` + DPP `ddy`, @@ -840,8 +877,8 @@ mod ps_ballot_tests { assert!(dis.contains("dx.op.quadReadLaneAt.i32"), "wave64 {wave64}: PS VOPC must quad-read VGPR operands via quadReadLaneAt:\n{dis}"); assert!(!dis.contains("dx.op.quadOp"), "wave64 {wave64}: PS VOPC must not emit quadOp on compare results (#134):\n{dis}"); - // Standalone VOPC with no DPP / readfirstlane (so `rla` is never called): - // proves VOPC itself emits the 4 VGPR operand `quadReadLaneAt` reads and zero `quadOp`. + // Standalone VOPC with no DPP / readfirstlane (so `rla` is never called), whose + // mask only `v_cndmask` reads: the lane's own bit (`recomp::ps_masks`), no quad ops. let mut vopc_only = Vec::new(); vopc_only.extend(encode(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None).unwrap()); vopc_only.extend(encode("V_CMP_LT_F32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 2)], None).unwrap()); @@ -851,7 +888,7 @@ mod ps_ballot_tests { let kv = kernel::translate_pixel(&vopc_only, opt, &psi).expect("translate VOPC-only PS"); validate::validate(&kv.dxil).expect("validate VOPC-only PS"); let vdis = validate::disassemble(&kv.dxil).expect("disassemble VOPC-only PS"); - assert_eq!(vdis.matches("call i32 @dx.op.quadReadLaneAt.i32(").count(), 4, "wave64 {wave64}: expected 4 operand quad reads for V_CMP_LT_F32(0, v2):\n{vdis}"); + assert_eq!(vdis.matches("call i32 @dx.op.quadReadLaneAt.i32(").count(), 0, "wave64 {wave64}: V_CMP_LT_F32(0, v2) read only by v_cndmask needs no quad reads:\n{vdis}"); assert!(!vdis.contains("dx.op.quadOp"), "wave64 {wave64}: VOPC-only PS must not emit quadOp:\n{vdis}"); // Entry EXEC alone (no post-entry ballot) must stay live-lanes-only (no quad reads). diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 4bab1223fe..02a9ebdb56 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -76,6 +76,8 @@ pub struct MeshCtx { pub vok: Value, pub pok: Value, pub outputs: Vec, + /// the console's output table (`MsInterface::params`) + pub params: Option>, } /// Initial register values: loaded from `io` in the entry block on first use. @@ -124,7 +126,7 @@ impl Init { fn first(&mut self, s: &mut Shader, var: u32) -> Value { if var == VAR_BUDGET { - return s.m.i32c(LOOP_BUDGET); + return s.m.i32c(super::kernel::loop_budget()); } if var == super::lower_round::VAR_F32_MODE { return s.m.i32c(super::lower_round::MODE_INIT); @@ -199,6 +201,8 @@ pub struct Lw { /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): /// Some(globallycoherent) pub heap_mem: Option, + /// heap windows read without a branch (`recomp::HEAP_FLAT`) + pub heap_flat: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, @@ -233,6 +237,8 @@ pub struct Lw { pub has_f64_round_op: bool, /// the T# SGPRs of the program's image stores and atomics (`recomp::emit::image_write_srsrcs`) pub img_writes: Vec, + /// program writes/atomics global or image UAVs or uses `GLC=1`: `s_barrier` emits `ALL_SYNC` + pub barrier_uav_fence: bool, /// highest VGPR index referenced by the program (for `v_movrel*` outside `Entry::Kernel`) pub max_vgpr: u64, /// static samplers bound so far: (S#, comparison, handle) at `s, space1` @@ -279,6 +285,8 @@ pub struct Lw { pub gfx_half: Option, /// split form: SGPRs whole-live after each instruction (`recomp::x64_masks::by_pc`) pub whole_live: std::collections::BTreeMap, + /// pixel shaders: compares whose mask needs less than the per-quad form (`recomp::ps_masks`) + pub ps_masks: std::collections::BTreeMap, /// set when an exchange was needed where it is not supported pub exchange_error: Option, pub pc: u64, @@ -1064,7 +1072,8 @@ impl Lw { if self.barrier_waves.is_some_and(|w| w > 1) && crate::gpu::recomp::emit::safe_barrier_wanted() { return err(d, "s_barrier in a group of several hardware waves"); } - self.s.barrier(super::ops::barrier::GROUP_SYNC); + let mode = if self.barrier_uav_fence { super::ops::barrier::ALL_SYNC } else { super::ops::barrier::GROUP_SYNC }; + self.s.barrier(mode); // (split form: both halves made their LDS writes before it) self.lds_met(); Ok(()) diff --git a/crates/xcl/src/gpu/dxil/lower_geom.rs b/crates/xcl/src/gpu/dxil/lower_geom.rs index cff04b289e..f01aa7ec7a 100644 --- a/crates/xcl/src/gpu/dxil/lower_geom.rs +++ b/crates/xcl/src/gpu/dxil/lower_geom.rs @@ -42,10 +42,11 @@ impl Lw { match name { "s_barrier" if self.split && gs_phase => Some(()), "s_sendmsg" => { - // MSG_GS (2): op 1 cut, 2 emit, 3 emit + cut (stream 0); the rest: nothing + // MSG_GS (2) and MSG_GS_DONE (3): op 1 cut, 2 emit, 3 emit + cut (stream 0); + // op 0 (NOP / bare done) and other messages do nothing here. let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0); let (msg, op, stream) = (simm & 0xF, (simm >> 4) & 3, (simm >> 8) & 3); - if msg == 2 && stream == 0 { + if matches!(msg, 2 | 3) && stream == 0 && op != 0 { self.gs_emit_cut(op); } Some(()) diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index a337d470bc..83aa8f5352 100644 --- a/crates/xcl/src/gpu/dxil/lower_gfx.rs +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -14,7 +14,7 @@ use super::lower::{err, LResult, Lw}; use super::module::{Pred, Value}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded}; -use crate::gpu::recomp::{elements_at, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; +use crate::gpu::recomp::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, PsInterface, VsInterface}; /// An output element: its signature handle, components and the temporaries holding them. pub struct GfxOut { @@ -119,7 +119,7 @@ impl Lw { _ => SemKind::Arbitrary, }; let s = io.output(GSig::new(&e.name, e.index, kind, gct(e.component_type), n)); - outs.push((s, n, e.component_type == 3)); + outs.push((s, n, matches!(e.component_type, 3 | 6))); } // initial VGPRs: v0 = vertex id, v3 = instance id, the fetch shader's attribute VGPRs let mut vgpr = HashMap::new(); @@ -166,7 +166,8 @@ impl Lw { for (k, e) in ranked(&ps.inputs, false).iter().enumerate() { let attr = ps_slot_attribute(ps, k); let m = attr.and_then(|a| modes.get(&(a as u32))).cloned().unwrap_or_default(); - let float = e.component_type == 3; + // float16 read through a packed attribute interpolates like a float + let float = e.component_type == 3 || (e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some())); let interp = if !float { Interp::Constant } else { @@ -326,15 +327,22 @@ impl Lw { 32..=63 => { let vs = self.gfx().vs.clone().expect("vs"); let k = (tgt - 32) as usize; - let at = vs_param_register(&vs, k).map(|r| elements_at(&vs.outputs, true, r)).unwrap_or_default(); - for j in at { + let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); + for (j, first) in at { let (vars, n) = { let o = &self.gfx().params[j]; (o.vars.clone(), o.comps) }; for c in 0..n as usize { - if enabled(c) { - let v = comp(self, c); + // packed float16: component c is half c & 1 of dword first + c / 2 + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let mut v = comp(self, dw); + if f16 { + let h = self.lshrc(v, 16 * (c as u32 & 1)); + let x = self.s.f16_to_f32(h); + v = self.bits(x); + } self.set_out(vars[c], v); } } @@ -353,7 +361,7 @@ impl Lw { continue; } let raw = comp(self, c); - let v = match (ct, compr) { + let mut v = match (ct, compr) { (3, true) => { let f = self.s.f16_to_f32(raw); self.bits(f) @@ -361,6 +369,9 @@ impl Lw { (2, true) => self.sx16(raw), _ => raw, }; + if ct == 3 && nan_guard_enabled() { + v = self.nan_guard_bits(v); + } self.set_out(var, v); } } @@ -401,11 +412,20 @@ impl Lw { let s1 = f("SRC1"); (f("VDST"), if s1 >= 256 { s1 - 256 } else { s1 }, f("SRC0") & 0x3F, f("SRC0") >> 6 & 3) }; - let Some(slot) = ps_attribute_slot(&ps, attr as usize, chan as usize) else { return err(d, "attribute outside ISG1") }; + // a float16-packed attribute: the PC input is the component itself (SRC0 bit 8: the + // high half of the dword); a half nothing declares reads 0 + let place = match ps_attribute_f16(&ps, attr as usize).filter(|_| name.ends_with("_f16")) { + Some(regs) => ps_f16_slot(&ps, ®s, chan as usize, d.enc.name != "ENC_VINTRP" && f("SRC0") >> 8 & 1 == 1), + None => match ps_attribute_slot(&ps, attr as usize, chan as usize) { + Some(slot) => Some((slot, chan as usize)), + None => return err(d, "attribute outside ISG1"), + }, + }; let load = |lw: &mut Lw| -> Value { + let Some((slot, comp)) = place else { return lw.c(0) }; let g = lw.gfx.as_mut().expect("gfx"); let (sig, _) = g.ps_in[slot]; - let x = g.io.load_input(&mut lw.s, sig, 0, chan as u8); + let x = g.io.load_input(&mut lw.s, sig, 0, comp as u8); let i32 = lw.s.m.i32(); lw.s.m.bitcast(x, i32) }; @@ -443,4 +463,24 @@ impl Lw { } Ok(()) } + + /// `XCL_NAN_GUARD` (default ON unless `"0"`): sanitize PS float color target exports + /// (`NaN -> 0.0`, `±Inf -> ±65504.0`) using bit ops so a single bad pixel never explodes + /// temporal history / bloom cones or crushes auto-exposure on RDNA4. + pub(super) fn nan_guard_bits(&mut self, v: Value) -> Value { + let abs_v = self.andc(v, 0x7FFF_FFFF); + let is_nan = self.cmpc(super::module::Pred::UGt, abs_v, 0x7F80_0000); + let is_inf = self.cmpc(super::module::Pred::Eq, abs_v, 0x7F80_0000); + let sign = self.andc(v, 0x8000_0000); + let max_f16 = self.orc(sign, 0x477F_E000); // ±65504.0f + let no_inf = self.sel(is_inf, max_f16, v); + let zero = self.c(0); + self.sel(is_nan, zero, no_inf) + } +} + +/// Whether PS float color target exports sanitize `NaN` / `±Inf` (`XCL_NAN_GUARD`, on unless `0`). +pub fn nan_guard_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_NAN_GUARD").map_or(true, |v| v.trim() != "0")) } diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index 22aab9149f..12d3a4bb36 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -146,7 +146,26 @@ impl Lw { let b = lw.fmin(hi[0], hi[1]); let b = lw.fmin(b, hi[2]); let cv = lw.cmpc(Pred::Ne, child[k], u32::MAX); - let mut all = cv; + // Reject all-zero unmapped-page / Box32 page-straddle entries where + // `child == 0` AND all box bounds are 0 (prevents infinite BVH traversal + // loops on unmapped sparse tiles while preserving synthetic tests that use + // child index 0 with real non-zero box bounds). + let nonzero = if box32 { + let b = 4 + 6 * k; + let mut m = child[k]; + for j in 0..6 { + m = lw.or(m, words[b + j]); + } + lw.nz(m) + } else { + let b = 4 + 3 * k; + let mut m = child[k]; + for j in 0..3 { + m = lw.or(m, words[b + j]); + } + lw.nz(m) + }; + let mut all = lw.land(cv, nonzero); for c in 0..3 { let le = lw.fcmp(Pred::FOLe, mn[c], mx[c]); all = lw.land(all, le); @@ -889,6 +908,14 @@ impl Lw { }; let base = name.trim_start_matches("image_"); if base == "bvh_intersect_ray" || base == "bvh64_intersect_ray" { + // `XCL_RT_GATE=miss`: no node is read, every ray misses + if super::kernel::rt_all_miss() { + let ones = self.c(u32::MAX); + for c in 0..4u64 { + self.write32(&super::lower::Dst::V(vdata + c), ones); + } + return Ok(()); + } let wide = base == "bvh64_intersect_ray"; let r = |lw: &mut Lw, j: u64| lw.vreg(addr_reg(j)); let node = r(self, 0); @@ -918,7 +945,10 @@ impl Lw { let base_lo = self.shlc(d0, 8); let off_lo = self.shlc(nlo, 3); let a = self.add(base_lo, off_lo); - // the window: bits 32.. of the 64-bit address + // the window: bits 32.. of the 64-bit address; also verify the node is non-null + // (`full >= 0x10000`, `hi != 0`) and that both the start and end of a 112 B Box32 + // node (`full + 111`) fall within the same UMA window. + let mut bvh_valid = self.b(true); if self.mems.len() > 1 { let d1lo = self.andc(d1, 0xFF); let b64 = self.pack64(d0, d1lo); @@ -939,6 +969,15 @@ impl Lw { let full = self.add(b64, off); let (_, hi) = self.unpack64(full); self.window_hi(hi, false); + let hi_nz = self.nz(hi); + let k111 = self.c64(111); + let full_end = self.add(full, k111); + let (_, hi_end) = self.unpack64(full_end); + let same_hi = self.cmp(Pred::Eq, hi_end, hi); + let k64k = self.c64(0x1_0000); + let non_null = self.cmp(Pred::UGe, full, k64k); + let ok1 = self.land(hi_nz, same_hi); + bvh_valid = self.land(ok1, non_null); } let ty = self.andc(node, 7); let sort = { @@ -952,7 +991,8 @@ impl Lw { // The raw memory accessor returns zeros for a missing // window. Those zeros are not a box with four child IDs. let window = lw.rd(VAR_WIN); - let valid = lw.cmpc(Pred::ULt, window, lw.mems.len() as u32); + let w_ok = lw.cmpc(Pred::ULt, window, lw.mems.len() as u32); + let valid = lw.land(w_ok, bvh_valid); let tri = lw.cmpc(Pred::ULt, ty, 4); for (&t, bits) in out.iter().zip([0x7f80_0000, 0x3f80_0000, 0, 0]) { let triangle = lw.c(bits); @@ -1575,7 +1615,15 @@ impl Lw { let c = self.land(run, is); self.guarded(c, &mut |lw| { let tex = lw.s.heap_texture(ui, lkind, true, ct, 4, true); - let v4 = if ct == CompType::F32 { vals.map(|v| lw.f(v)) } else { vals }; + let v4 = if ct == CompType::F32 { + let guard = super::lower_gfx::nan_guard_enabled(); + vals.map(|v| { + let v = if guard { lw.nan_guard_bits(v) } else { v }; + lw.f(v) + }) + } else { + vals + }; lw.s.texture_store(tex, &ic, v4); Ok(()) })?; diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cb09a73e89..58b725de43 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -401,12 +401,34 @@ impl Lw { out } + /// `with_mem_many_tys` of `n` dwords for a read (`f` only loads). With `heap_flat`, no branch: + /// `f` reads window `w`, or window 0 when `w` is outside the windows or the lane is not in + /// `guard`, and those lanes then take 0 (a raw buffer read out of the view's range gives 0, + /// so the read of window 0 is harmless). One path per access: no handle phi, no block per read. pub(crate) fn with_mem_i32s( &mut self, guard: Option, n: usize, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { + if let (Some(coherent), true) = (self.heap_mem, self.heap_flat) { + let z = self.c(0); + if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) { + return vec![z; n]; + } + let w = self.rd(super::lower::VAR_WIN); + let inside = self.cmpc(Pred::ULt, w, self.mems.len() as u32); + let ok = match guard { + Some(g) if self.s.m.const_u64(g) != Some(1) => self.and(g, inside), + _ => inside, + }; + let w = self.sel(ok, w, z); + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + debug_assert_eq!(vals.len(), n); + return vals.into_iter().map(|v| self.sel(ok, v, z)).collect(); + } let i32 = self.s.m.i32(); let tys = vec![i32; n]; self.with_mem_many_tys(guard, &tys, f) @@ -2457,8 +2479,13 @@ impl Lw { } fn scratch(&mut self, d: &Decoded, op: &str) -> LResult<()> { - let saddr = Self::fv(d, "SADDR"); - let base = if saddr != 0x7D && saddr != 0x7F { self.sreg(saddr) } else { self.vreg(Self::fv(d, "ADDR")) }; + // RDNA2 has no SGPR + VGPR form (no SVE bit): SADDR 0x7F (EXEC_HI) is the ST form, + // the offset alone; NULL (0x7D) is SV, VADDR + offset; an SGPR is SS, SGPR + offset + let base = match Self::fv(d, "SADDR") { + 0x7F => self.c(0), + 0x7D => self.vreg(Self::fv(d, "ADDR")), + s => self.sreg(s), + }; let raw = Self::fv(d, "OFFSET") as u32; let off = (((raw << 20) as i32) >> 20) as u32; let a = self.addc(base, off); @@ -2567,13 +2594,23 @@ impl Lw { 13..=15 | 9 => {} 32..=63 => { let k = (tgt - 32) as usize; - let outputs = self.mesh.as_ref().expect("mesh").outputs.clone(); - let at = crate::gpu::recomp::param_registers(&outputs, true).get(k).map(|&r| crate::gpu::recomp::elements_at(&outputs, true, r)).unwrap_or_default(); - for j in at { + let (at, f16) = { + let m = self.mesh.as_ref().expect("mesh"); + crate::gpu::recomp::out_param_elements(&m.outputs, m.params.as_deref(), k) + }; + for (j, first) in at { for c in 0..4 { - if enabled(c) { + // packed float16: component c is half c & 1 of dword first + c / 2; the + // record keeps it as a float + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { let a = self.addc(vtx, (4 * (j + 1) + c) as u32); - let v = comp(self, c); + let mut v = comp(self, dw); + if f16 { + let h = self.lshrc(v, 16 * (c as u32 & 1)); + let x = self.s.f16_to_f32(h); + v = self.bits(x); + } st.push((a, v)); } } diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index b2805c5f17..d61ecbf3f5 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -5,6 +5,7 @@ use super::lower::{err, ext_encoding, Dst, LResult, Lw, Mods, VAR_VGPR}; use super::module::{BinOp, Pred, Value}; use super::ops_core::op; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; +use crate::gpu::recomp::ps_masks::Form as PsForm; /// A source operand: one dword, or a mask pair (SGPR pair / VCC). #[derive(Clone, Copy)] @@ -627,14 +628,23 @@ impl Lw { _ => self.fma_legacy(x, y, cf), }) } - "v_fma_f32" | "v_mad_f32" | "v_fma_legacy_f32" | "v_div_fmas_f32" => { + "v_fma_f32" | "v_mad_f32" | "v_fma_legacy_f32" => { let (x, y, w) = (fs!(0), fs!(1), fs!(2)); fr!(match name { - "v_fma_f32" | "v_div_fmas_f32" => self.fmad(x, y, w), + "v_fma_f32" => self.fmad(x, y, w), "v_mad_f32" => self.mad_nf(x, y, w), _ => self.fma_legacy(x, y, w), }) } + "v_div_fmas_f32" => { + let (x, y, w) = (fs!(0), fs!(1), fs!(2)); + let unscaled = self.fmad(x, y, w); + let vcc = match u.get(3).copied() { + Some(Src::Pair(l, h)) => self.lane_of(l, h), + _ => self.b(false), + }; + fr!(self.div_fmas_f32(x, y, w, vcc, unscaled)) + } "v_fmamk_f32" | "v_madmk_f32" => { let (x, w) = (fs!(0), fs!(2)); let k = self.f(b); @@ -993,6 +1003,7 @@ impl Lw { let (el, eh) = self.exec_mask(); let l = self.first_lane_live(el, eh); let t = self.read_lane_uniform(a, l); + let t = self.helper_reads_own(a, t); self.write32(&dst, t); return Ok(()); } @@ -1016,8 +1027,41 @@ impl Lw { let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); let f = self.b(false); self.write_mask(&sdst, f); - let x = fs!(0); - let r = self.bits(x); + let (s0, dd, nn) = (fs!(0), fs!(1), fs!(2)); + let (u0, du, nu) = (self.bits(s0), self.bits(dd), self.bits(nn)); + let da = self.andc(du, 0x7FFF_FFFF); + let na = self.andc(nu, 0x7FFF_FFFF); + let d_zero = self.cmpc(Pred::Eq, da, 0); + let n_zero = self.cmpc(Pred::Eq, na, 0); + let any_zero = self.lor(d_zero, n_zero); + let d_sh = self.lshrc(du, 23); + let ed = self.andc(d_sh, 0xFF); + let n_sh = self.lshrc(nu, 23); + let en = self.andc(n_sh, 0xFF); + let d_fin = self.cmpc(Pred::ULt, ed, 0xFF); + let n_fin = self.cmpc(Pred::ULt, en, 0xFF); + let both_fin = self.land(d_fin, n_fin); + // Prescale both operands by 2^+64 when d is subnormal/tiny and n*2^64 fits, or + // by 2^-64 when d is huge and n*2^-64 stays normal (factor cancels in n/d so + // rcp(d) never overflows/underflows to Inf/0 -> NaN, with SDST flag kept 0). + let d_tiny = self.cmpc(Pred::ULt, ed, 23); + let n_fits_up = self.cmpc(Pred::ULt, en, 191); + let up_cond = self.land(d_tiny, n_fits_up); + let scale_up = self.land(both_fin, up_cond); + let d_huge = self.cmpc(Pred::UGe, ed, 232); + let n_fits_dn = self.cmpc(Pred::UGe, en, 65); + let dn_cond = self.land(d_huge, n_fits_dn); + let scale_dn = self.land(both_fin, dn_cond); + let p64 = self.c(64); + let m64 = self.c(-64i32 as u32); + let up_f = self.ldexp_f(s0, p64); + let up_bits = self.bits(up_f); + let dn_f = self.ldexp_f(s0, m64); + let dn_bits = self.bits(dn_f); + let qnan = self.c(0x7FC0_0000); + let r = self.sel(scale_up, up_bits, u0); + let r = self.sel(scale_dn, dn_bits, r); + let r = self.sel(any_zero, qnan, r); self.vwrite(d, &dst, r); return Ok(()); } @@ -1040,16 +1084,19 @@ impl Lw { let cb = self.lane_of(l, h); let cin = self.u(cb); let (x, y) = if name == "v_subrev_co_ci_u32" { (b, a) } else { (a, b) }; - let (x6, y6, c6) = (self.zext64(x), self.zext64(y), self.zext64(cin)); - let w = if name == "v_add_co_ci_u32" { - let s = self.add(x6, y6); - self.add(s, c6) + let (t, carry) = if name == "v_add_co_ci_u32" { + let t0 = self.add(x, y); + let t = self.add(t0, cin); + let c0 = self.cmp(Pred::ULt, t0, x); + let c1 = self.cmp(Pred::ULt, t, t0); + (t, self.lor(c0, c1)) } else { - let s = self.sub(x6, y6); - self.sub(s, c6) + let t0 = self.sub(x, y); + let t = self.sub(t0, cin); + let c0 = self.cmp(Pred::ULt, x, y); + let c1 = self.cmp(Pred::ULt, t0, cin); + (t, self.lor(c0, c1)) }; - let (t, hi) = self.unpack64(w); - let carry = self.nz(hi); let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); self.write_mask(&sdst, carry); self.vwrite(d, &dst, t); @@ -1114,10 +1161,19 @@ impl Lw { let zz = self.fc(0.0); self.sel(lz, zz, r) } - "v_fma_f32" | "v_div_fmas_f32" => { + "v_fma_f32" => { let n = self.fmad(fa, fb, fc); self.rm_fma(ba, bb, bc, n) } + "v_div_fmas_f32" => { + let n = self.fmad(fa, fb, fc); + let unscaled = self.rm_fma(ba, bb, bc, n); + let vcc = match u.get(3).copied() { + Some(Src::Pair(l, h)) => self.lane_of(l, h), + _ => self.b(false), + }; + self.div_fmas_f32(fa, fb, fc, vcc, unscaled) + } "v_fma_legacy_f32" => { let n = self.fmad(fa, fb, fc); let r = self.rm_fma(ba, bb, bc, n); @@ -1241,6 +1297,26 @@ impl Lw { if matches!(dst, Dst::Null) && matches!(ty, "f32" | "i32" | "u32") { return Ok(()); } + // the forms `recomp::ps_masks` found enough for this mask + let form = if self.split { None } else { self.ps_masks.get(&d.pc).copied() }; + if let Some(form) = form { + let c = self.vopc_cond(d, opn, ty, ua, ub, m)?; + let (lo, hi) = if form == PsForm::Uniform { + let (el, eh) = self.exec_mask(); + let z = self.c(0); + (self.sel(c, el, z), self.sel(c, eh, z)) + } else { + let a = self.act(); + let c = self.land(a, c); + self.ballot_ps_local(c, form == PsForm::Own) + }; + if self.wave64 { + self.write64(&dst, lo, hi); + } else { + self.write32(&dst, lo); + } + return Ok(()); + } let is_vgpr = |o: &Operand| match o.field { Some("LITERAL") | None => false, Some(f) => { @@ -1276,7 +1352,17 @@ impl Lw { let sh = self.shlc(up, p); q = self.or(q, sh); } - let (lo, hi) = self.ballot_ps_quad(q); + let (mut lo, mut hi) = self.ballot_ps_quad(q); + // the quad's live lanes read this lane's EXEC bit from their own copy of EXEC, + // which a compare in the local form may have left without it (`recomp::ps_masks`) + if !self.ps_masks.is_empty() && !self.split { + let c = self.vopc_cond(d, opn, ty, ua, ub, m)?; + let a = self.act(); + let c = self.land(a, c); + let (ol, oh) = self.ballot_ps_local(c, true); + lo = self.or(lo, ol); + hi = self.or(hi, oh); + } if self.wave64 { self.write64(&dst, lo, hi); } else { @@ -1337,7 +1423,7 @@ impl Lw { "le" => self.fcmp(Pred::FOLe, a, b), "gt" => self.fcmp(Pred::FOGt, a, b), "ge" => self.fcmp(Pred::FOGe, a, b), - "lg" => self.fcmp(Pred::FONe, a, b), + "lg" => { let x = self.fcmp(Pred::FOLt, a, b); let y = self.fcmp(Pred::FOGt, a, b); self.lor(x, y) } "o" => self.fcmp(Pred::FOrd, a, b), "u" => self.fcmp(Pred::FUno, a, b), "nlt" => self.fcmp(Pred::FUGe, a, b), @@ -1345,7 +1431,7 @@ impl Lw { "nle" => self.fcmp(Pred::FUGt, a, b), "ngt" => self.fcmp(Pred::FULe, a, b), "nge" => self.fcmp(Pred::FULt, a, b), - "nlg" => self.fcmp(Pred::FUEq, a, b), + "nlg" => { let x = self.fcmp(Pred::FOLt, a, b); let y = self.fcmp(Pred::FOGt, a, b); let lg = self.lor(x, y); self.lnot(lg) } _ => return None, }); } @@ -1451,3 +1537,136 @@ impl Lw { } } } + +#[cfg(test)] +mod valu_carry_tests { + use super::super::kernel::{self, KernelOptions}; + use super::super::validate; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::runner; + + #[test] + fn valu_carry_ops_avoid_i64_and_match_gpu() { + let mut code = Vec::new(); + for &(name, enc, fields) in &[ + // v2 = v0 + v1 + cin(s0), carry -> s2 + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2u64), ("SDST", 2), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)][..]), + // v3 = v0 - v1 - cin(s0), borrow -> s4 + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 3), ("SDST", 4), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)]), + // v4 = v1 - v0 - cin(s0), borrow -> s6 + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 6), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)]), + ] { + code.extend(encode(name, enc, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = kernel::translate(&code, ko).expect("translate valu carry ops"); + validate::validate(&dxil).expect("validate valu carry ops"); + let dis = validate::disassemble(&dxil).expect("disasm valu carry ops"); + assert!(!dis.contains("64-Bit integer"), "32-bit VALU carry ops must not require Int64Ops:\n{dis}"); + assert!(!dis.contains("zext i32"), "32-bit VALU carry ops must not widen to i64:\n{dis}"); + + if !matches!(runner::wave32_supported(), Ok(true)) { + runner::skip_test("no wave32"); + return; + } + // Boundary triples (x, y, cin) covering overflow/underflow with and without carry/borrow-in. + let cases: [(u32, u32, bool); 32] = [ + (0, 0, false), + (0, 0, true), + (0, 1, false), + (0, 1, true), + (1, 0, false), + (1, 0, true), + (1, 1, false), + (1, 1, true), + (u32::MAX, 0, false), + (u32::MAX, 0, true), + (u32::MAX, 1, false), + (u32::MAX, 1, true), + (0, u32::MAX, false), + (0, u32::MAX, true), + (u32::MAX, u32::MAX, false), + (u32::MAX, u32::MAX, true), + (u32::MAX - 1, 1, false), + (u32::MAX - 1, 1, true), + (0x7FFF_FFFF, 0x8000_0000, false), + (0x7FFF_FFFF, 0x8000_0000, true), + (0x8000_0000, 0x8000_0000, false), + (0x8000_0000, 0x8000_0000, true), + (0x8000_0000, 0x7FFF_FFFF, false), + (0x8000_0000, 0x7FFF_FFFF, true), + (2, 1, false), + (2, 1, true), + (1, 2, false), + (1, 2, true), + (0x1234_5678, 0xEDCB_A987, false), + (0x1234_5678, 0xEDCB_A987, true), + (0x1234_5678, 0xEDCB_A988, false), + (0x1234_5678, 0xEDCB_A988, true), + ]; + let mut st = runner::KernelState::default(); + let mut cin_mask = 0u32; + for (l, &(x, y, cin)) in cases.iter().enumerate() { + st.vgpr[l][0] = x; + st.vgpr[l][1] = y; + if cin { + cin_mask |= 1u32 << l; + } + } + st.sgpr[0] = cin_mask; + let r = runner::run(&dxil, &st, &[]).expect("GPU run valu carry ops"); + + let mut want_add_c = 0u32; + let mut want_sub_b = 0u32; + let mut want_subrev_b = 0u32; + for (l, &(x, y, cin)) in cases.iter().enumerate() { + let c = cin as u64; + let add64 = x as u64 + y as u64 + c; + assert_eq!(r.vgpr[l][2], add64 as u32, "add_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (add64 >> 32) != 0 { + want_add_c |= 1u32 << l; + } + let sub64 = (x as u64).wrapping_sub(y as u64).wrapping_sub(c); + assert_eq!(r.vgpr[l][3], sub64 as u32, "sub_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (sub64 >> 32) != 0 { + want_sub_b |= 1u32 << l; + } + let subrev64 = (y as u64).wrapping_sub(x as u64).wrapping_sub(c); + assert_eq!(r.vgpr[l][4], subrev64 as u32, "subrev_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (subrev64 >> 32) != 0 { + want_subrev_b |= 1u32 << l; + } + } + assert_eq!(r.sgpr[2], want_add_c, "add_co_ci carry-out mask"); + assert_eq!(r.sgpr[4], want_sub_b, "sub_co_ci borrow-out mask"); + assert_eq!(r.sgpr[6], want_subrev_b, "subrev_co_ci borrow-out mask"); + } +} + +#[cfg(test)] +mod div_f32_tests { + use crate::gpu::dxil::{kernel, validate}; + use crate::gpu::rdna2; + + #[test] + fn direct_dxil_div_scale_fmas_fixup_validate_and_emit_guards() { + let mut code = Vec::new(); + // V_DIV_SCALE_F32 v4, vcc, v1, v2, v1 + code.extend(rdna2::encode("V_DIV_SCALE_F32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 106), ("SRC0", 257), ("SRC1", 258), ("SRC2", 257)], None).unwrap()); + // V_DIV_FMAS_F32 v5, v4, v2, v1 (implicit VCC) + code.extend(rdna2::encode("V_DIV_FMAS_F32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 260), ("SRC1", 258), ("SRC2", 257)], None).unwrap()); + // V_DIV_FIXUP_F32 v6, v5, v2, v1 + code.extend(rdna2::encode("V_DIV_FIXUP_F32", "ENC_VOP3", &[("VDST", 6), ("SRC0", 261), ("SRC1", 258), ("SRC2", 257)], None).unwrap()); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let dxil = kernel::translate(&code, kernel::KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }) + .expect("direct translate div sequence"); + validate::validate(&dxil).expect("dxil validate div sequence"); + let dis = validate::disassemble(&dxil).expect("dxil disassemble div sequence"); + assert!(dis.contains("2143289344"), "expected V_DIV_SCALE_F32 0x7FC00000 QNaN guard in DXIL"); + assert!(dis.contains("2139095040"), "expected V_DIV_FIXUP_F32 0x7F800000 Inf guard in DXIL"); + assert!(dis.contains("-64"), "expected V_DIV_FMAS_F32 -64 pre-rounding scale in DXIL"); + } +} diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 4e425e351a..1a4155fb7f 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -104,16 +104,18 @@ impl Module { let name = &self.funcs[*f as usize].name; // AMD RDNA4 (`amdxc64.dll`) crashes on null deref if a raw `createHandleFromHeap` // handle is shared across distinct `annotateHandle` resource kinds or across basic - // blocks, or if `annotateHandle` / `getDimensions` crosses basic blocks. - if name.starts_with("dx.op.createHandleFromHeap") { + // blocks, if `annotateHandle` crosses basic blocks, or if `getDimensions` is reused + // at all (29 `CS_RaytracingResolve` pipelines crash on RDNA4 when CSE merges + // `dx.op.getDimensions` calls, even within the same basic block). + if name.starts_with("dx.op.createHandleFromHeap") || name.starts_with("dx.op.getDimensions") { Cse::No - } else if name.starts_with("dx.op.annotateHandle") || name.starts_with("dx.op.getDimensions") { + } else if name.starts_with("dx.op.annotateHandle") { Cse::Block } else { Cse::Dom } } - Op::Call(f, _) if self.funcs[*f as usize].name.starts_with("dx.op.getDimensions") => Cse::Block, + Op::Call(f, _) if self.funcs[*f as usize].name.starts_with("dx.op.getDimensions") => Cse::No, Op::Call(f, _) if self.wave_call(*f) && !self.funcs[*f as usize].name.starts_with("dx.op.waveIsFirstLane") => Cse::Block, _ => Cse::No, } @@ -792,6 +794,56 @@ impl Module { changed } + /// Post-DCE narrowing of `dx.op.rawBufferLoad.*` component masks: if all surviving uses of a + /// load are `ExtractValue` on components `0..=max_c` (never residency status index `4` and + /// never passed whole), narrow its contiguous DXIL mask (`15`/`7`/`3`) to `(1 << (max_c + 1)) - 1`. + fn narrow_raw_buffer_loads(&mut self, order: &[u32]) -> bool { + let mut max_comp = vec![-1i8; self.insts.len()]; + for &b in order { + for &i in &self.blocks[b as usize] { + match &self.insts[i as usize].op { + Op::Extract(Value::Inst(j), idx) if *idx < 4 => { + let slot = &mut max_comp[*j as usize]; + if *slot < 99 { + *slot = (*slot).max(*idx as i8); + } + } + other => other.for_each_operand(|v| { + if let Value::Inst(j) = v { + max_comp[j as usize] = 99; + } + }), + } + } + } + let mut changed = false; + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + let mc = max_comp[i]; + if !(0..4).contains(&mc) { + continue; + } + let (mask_ty, cur_mask) = match &self.insts[i].op { + Op::Call(f, args) if args.len() == 6 && self.funcs[*f as usize].name.starts_with("dx.op.rawBufferLoad.") => { + let Some(m) = self.const_u64(args[4]) else { continue }; + (self.value_ty(args[4]), m) + } + _ => continue, + }; + let new_mask = (1u64 << (mc as u32 + 1)) - 1; + if matches!(cur_mask, 3 | 7 | 15) && new_mask < cur_mask { + let c = self.const_int(mask_ty, new_mask); + if let Op::Call(_, args) = &mut self.insts[i].op { + args[4] = c; + changed = true; + } + } + } + } + changed + } + /// Removes immediately redundant `dx.op.barrier` calls within a basic block when no /// memory-visible side effect occurred since an equally-strong or stronger barrier. fn elim_redundant_barriers(&mut self, order: &[u32]) -> bool { @@ -1228,6 +1280,10 @@ impl Module { b.retain(|&i| live[i as usize]); } + if !skip("mask") && self.narrow_raw_buffer_loads(&order) { + iter_changed = true; + } + if !skip("merge") && self.simplify_cfg() { iter_changed = true; } @@ -2216,4 +2272,28 @@ mod tests { .count(); assert_eq!(barriers, 1, "adjacent covered barriers must collapse to one"); } + + #[test] + fn raw_buffer_load_mask_narrowed_to_highest_extracted_component() { + use crate::gpu::dxil::container::Stage; + use crate::gpu::dxil::shader::Shader; + let mut s = Shader::new(Stage::Compute, (6, 6)); + let z = s.m.i32c(0); + let uav = s.heap_raw_buffer_uav(z, false); + let vals = s.raw_load(uav, z, 15); + // Only component 0 is used; components 1..3 are dead -> mask must narrow from 15 to 1. + s.raw_store(uav, z, &[vals[0]]); + s.m.ret(); + + s.m.optimize(); + + let load_masks: Vec = s.m.blocks[0] + .iter() + .filter_map(|&i| match &s.m.insts[i as usize].op { + Op::Call(f, args) if s.m.funcs[*f as usize].name.starts_with("dx.op.rawBufferLoad.") => s.m.const_u64(args[4]), + _ => None, + }) + .collect(); + assert_eq!(load_masks, vec![1], "rawBufferLoad mask 15 must narrow to 1 when only x is live"); + } } diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 3f8c21b84b..fa89bde546 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -87,10 +87,9 @@ impl Scratch { } impl Shader { - /// Start with full native wave32 groups. A fresh dispatch can assign a - /// different physical wave to a group; wave-lane index identifies the - /// continuation within a full, single-wave group. - pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { + /// Split a single-wave compute group (`[32, 1, 1]` on wave32, `[64, 1, 1]` on native wave64, + /// or a split-wave64 `[64, 1, 1]` group with `split_tid`) into a `DispatchChain`. + pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, hw: u32, limit: usize) -> Option { if self.m.globals.iter().any(|g| !g.constant && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs"))) { return None; } @@ -149,11 +148,11 @@ impl Shader { (stride, slots) = self.m.reuse_piece_slots(&plan, &slots)?; } stride.checked_mul(threads[0])?.checked_mul(4)?; - let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, &prefix)).collect::>>()?; + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, hw, &prefix)).collect::>>()?; Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) } - fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], prefix: &[u32]) -> Option> { + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], hw: u32, prefix: &[u32]) -> Option> { let src = &self.m; let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); @@ -271,7 +270,7 @@ impl Shader { // a refused piece leaves the whole program unsplit: say so let refused = |e: String| crate::xlog_warn!("compute split: piece {} of {} refused, the program stays whole: {}", stage + 1, plan.blocks.len(), e.lines().next().unwrap_or_default()); - let blob = dst.try_finish(threads, Some(32)).map_err(|e| refused(e.to_string())).ok()?; + let blob = dst.try_finish(threads, Some(hw)).map_err(|e| refused(e.to_string())).ok()?; crate::gpu::dxil::validate::validate(&blob).map_err(refused).ok()?; Some(blob) } @@ -840,7 +839,7 @@ mod tests { let plan = lw.s.m.dispatch_plan(40).expect("partition around oversized loop"); assert!(plan.blocks.iter().any(|piece| piece == &[oversized])); } - let chain = lw.s.split_compute(geometry, split.then_some(tid), 40); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 32, 40); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); let chain = if split { @@ -934,7 +933,7 @@ mod tests { assert_eq!(slot(incoming, saved), slot(outgoing, replacement)); } - let chain = lw.s.split_compute(geometry, None, limit).unwrap(); + let chain = lw.s.split_compute(geometry, None, 32, limit).unwrap(); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); let initial: Vec = (0..32).map(|i| 1009 * i + 77).collect(); let mut expected: Vec<_> = initial.iter().map(|&v| { @@ -984,7 +983,7 @@ mod tests { lw.s.m.ret(); lw.s.m.optimize(); let limit = lw.s.m.blocks.iter().map(Vec::len).max().unwrap(); - let chain = lw.s.split_compute(geometry, None, limit).expect("every piece validates"); + let chain = lw.s.split_compute(geometry, None, 32, limit).expect("every piece validates"); assert!(chain.pieces.len() >= 2); } @@ -1103,7 +1102,7 @@ mod tests { let plan = lw.s.m.dispatch_plan(64).expect("partition branch fixture"); let stage = |b| plan.blocks.iter().position(|blocks| blocks.contains(&b)).unwrap(); assert!(plan.edges.iter().any(|edge| stage(edge.to) > stage(edge.from) + 1), "exercise a forward skip over an intermediate piece"); - let chain = lw.s.split_compute(geometry, split.then_some(tid), 64); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 32, 64); let chain = if split { assert!(chain.is_none(), "a split wave64 that exchanges through counters stays whole"); None diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index 08f8214338..8c29e56c95 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -279,20 +279,97 @@ impl Lw { let y = self.fmin(y, c); self.fmax(x, y) } - /// `div_fixup` + /// `div_fixup` (RDNA2 `V_DIV_FIXUP_F32` exact special-case, sign, and overflow/underflow rules). pub fn div_fixup(&mut self, q: Value, d: Value, n: Value) -> Value { - let a = self.isnan(d); - let b = self.isnan(n); - let z = self.fc(0.0); - let dz = self.fcmp(Pred::FOEq, d, z); - let di = self.isinf(d); - let ni = self.isinf(n); - let x = self.lor(a, b); - let y = self.lor(di, ni); - let y = self.lor(dz, y); - let c = self.lor(x, y); - let r = self.fdiv(n, d); - self.sel(c, r, q) + let (qu, du, nu) = (self.bits(q), self.bits(d), self.bits(n)); + let abs = self.c(0x7FFF_FFFF); + let (qa, da, na) = (self.and(qu, abs), self.and(du, abs), self.and(nu, abs)); + let x = self.xor(du, nu); + let top = self.c(0x8000_0000); + let sign = self.and(x, top); + let inf = self.c(0x7F80_0000); + let zero = self.c(0); + let quiet = self.c(0x0040_0000); + let signed_inf = self.or(sign, inf); + let mut r = self.or(sign, qa); + let q_nan = self.cmp(Pred::UGt, qa, inf); + r = self.sel(q_nan, signed_inf, r); // overflowed quotient: ±Inf + let ff = self.c(0xFF); + let nsh = self.lshrc(nu, 23); + let en = self.and(nsh, ff); + let dsh = self.lshrc(du, 23); + let ed = self.and(dsh, ff); + let k150 = self.c(150); + let en150 = self.add(en, k150); + let under = self.cmp(Pred::ULt, en150, ed); + r = self.sel(under, sign, r); // exponent gap under -150: ±0 + let d_inf = self.cmp(Pred::Eq, da, inf); + let n_zero = self.cmp(Pred::Eq, na, zero); + let to_zero = self.lor(d_inf, n_zero); + r = self.sel(to_zero, sign, r); // x/Inf, 0/x + let d_zero = self.cmp(Pred::Eq, da, zero); + let n_inf = self.cmp(Pred::Eq, na, inf); + let to_inf = self.lor(d_zero, n_inf); + r = self.sel(to_inf, signed_inf, r); // x/0, Inf/x + let zz = self.land(d_zero, n_zero); + let ii = self.land(d_inf, n_inf); + let invalid = self.lor(zz, ii); + let nan = self.c(0xFFC0_0000); + r = self.sel(invalid, nan, r); // 0/0, Inf/Inf + let d_nan = self.cmp(Pred::UGt, da, inf); + let dq = self.or(du, quiet); + r = self.sel(d_nan, dq, r); + let n_nan = self.cmp(Pred::UGt, na, inf); + let nq = self.or(nu, quiet); + r = self.sel(n_nan, nq, r); // NaN operands, numerator wins + self.f(r) + } + + /// `v_div_fmas_f32`: fused multiply-add with exact pre-rounding `2^(±64)` scale when `vcc` is set + /// (`+64` when `exp(s2) > 127`, `-64` otherwise, matching AMD RDNA2 hardware). + pub fn div_fmas_f32(&mut self, s0: Value, s1: Value, s2: Value, vcc: Value, unscaled: Value) -> Value { + let u0 = self.bits(s0); + let u1 = self.bits(s1); + let u2 = self.bits(s2); + let s0_sh = self.lshrc(u0, 23); + let e0 = self.andc(s0_sh, 0xFF); + let s1_sh = self.lshrc(u1, 23); + let e1 = self.andc(s1_sh, 0xFF); + let s2_sh = self.lshrc(u2, 23); + let e2 = self.andc(s2_sh, 0xFF); + let up = self.cmpc(Pred::UGt, e2, 127); + + // Split +64 or -64 across s0 and s1 without intermediate overflow/underflow so the + // single fused multiply-add rounds only once at the final exponent. + let p0 = self.c(0); + let p32 = self.c(32); + let p64 = self.c(64); + let m32 = self.c(-32i32 as u32); + let m64 = self.c(-64i32 as u32); + + let hi0 = self.cmpc(Pred::UGe, e0, 223); + let hi1 = self.cmpc(Pred::UGe, e1, 223); + let up_n0_b = self.sel(hi1, p64, p32); + let up_n0 = self.sel(hi0, p0, up_n0_b); + let up_n1_b = self.sel(hi1, p0, p32); + let up_n1 = self.sel(hi0, p64, up_n1_b); + + let lo0 = self.cmpc(Pred::ULt, e0, 33); + let lo1 = self.cmpc(Pred::ULt, e1, 33); + let dn_n0_b = self.sel(lo1, m64, m32); + let dn_n0 = self.sel(lo0, p0, dn_n0_b); + let dn_n1_b = self.sel(lo1, p0, m32); + let dn_n1 = self.sel(lo0, m64, dn_n1_b); + + let n0 = self.sel(up, up_n0, dn_n0); + let n1 = self.sel(up, up_n1, dn_n1); + let n2 = self.sel(up, p64, m64); + + let sc0 = self.ldexp_f(s0, n0); + let sc1 = self.ldexp_f(s1, n1); + let sc2 = self.ldexp_f(s2, n2); + let scaled = self.fmad(sc0, sc1, sc2); + self.sel(vcc, scaled, unscaled) } /// cube_id / cube_sc / cube_tc / cube_ma pub fn cube(&mut self, name: &str, x: Value, y: Value, z: Value) -> Value { @@ -763,6 +840,7 @@ mod disable_math_refactoring_tests { outputs: vec![SigElement { name: "SV_Target".into(), index: 0, system_value: 64, component_type: 3, register: 0, mask: 0xF, rw_mask: 0xF, stream: 0 }], input_ena: 0x0F00, attrs: None, + early_depth: false, } } diff --git a/crates/xcl/src/gpu/dxil/reload.rs b/crates/xcl/src/gpu/dxil/reload.rs index 47beaa5103..96dfc2cdf1 100644 --- a/crates/xcl/src/gpu/dxil/reload.rs +++ b/crates/xcl/src/gpu/dxil/reload.rs @@ -365,6 +365,44 @@ mod tests { assert_eq!(buffer_loads(&[LOAD, ADD, store, LOAD, sum, END]), buffer_loads(&[LOAD, ADD, store, sum, END]) + 1, "a store in between: loaded again"); } + #[test] + fn graphics_stages_emit_a_repeated_load_once() { + use super::super::kernel::{translate_pixel, translate_vertex, KernelOptions}; + use crate::gpu::recomp::{PsInterface, VsInterface}; + + let encode = |insts: &[I]| -> Vec { + insts.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect() + }; + let count_loads = |dxil: &[u8]| -> usize { + super::super::validate::validate(dxil).expect("valid DXIL"); + let dis = super::super::validate::disassemble(dxil).expect("disassemble"); + dis.lines().filter(|l| l.contains("@dx.op.rawBufferLoad") && l.contains(" = call ")).count() + }; + let opts = KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; + let sum: I = ("S_ADD_U32", "ENC_SOP2", &[("SDST", 21), ("SSRC0", 20), ("SSRC1", 12)]); + let store: I = ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 2), ("SADDR", 125)]); + let once_code = encode(&[LOAD, ADD, END]); + let repeat_code = encode(&[LOAD, ADD, LOAD, sum, END]); + let store_once_code = encode(&[LOAD, ADD, store, sum, END]); + let store_repeat_code = encode(&[LOAD, ADD, store, LOAD, sum, END]); + + let vs = VsInterface::default(); + let vs_once = count_loads(&translate_vertex(&once_code, opts, &vs).expect("VS once").dxil); + let vs_repeat = count_loads(&translate_vertex(&repeat_code, opts, &vs).expect("VS repeat").dxil); + assert_eq!(vs_repeat, vs_once, "VS repeated s_load_dwordx4 should reuse cached values"); + let vs_store_once = count_loads(&translate_vertex(&store_once_code, opts, &vs).expect("VS store once").dxil); + let vs_store_repeat = count_loads(&translate_vertex(&store_repeat_code, opts, &vs).expect("VS store repeat").dxil); + assert_eq!(vs_store_repeat, vs_store_once + 4, "VS store should invalidate reload across 4 windows"); + + let ps = PsInterface::default(); + let ps_once = count_loads(&translate_pixel(&once_code, opts, &ps).expect("PS once").dxil); + let ps_repeat = count_loads(&translate_pixel(&repeat_code, opts, &ps).expect("PS repeat").dxil); + assert_eq!(ps_repeat, ps_once, "PS repeated s_load_dwordx4 should reuse cached values"); + let ps_store_once = count_loads(&translate_pixel(&store_once_code, opts, &ps).expect("PS store once").dxil); + let ps_store_repeat = count_loads(&translate_pixel(&store_repeat_code, opts, &ps).expect("PS store repeat").dxil); + assert_eq!(ps_store_repeat, ps_store_once + 4, "PS store should invalidate reload across 4 windows"); + } + /// Every output operand type of the instruction tables is one `changes` knows: a new one /// must be looked at here, not passed over. #[test] diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index faa3f79d8f..b27a64358b 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -68,6 +68,7 @@ fn translate_all() -> Vec> { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; @@ -117,7 +118,7 @@ fn a_group_barrier_of_several_hardware_waves_is_left_to_the_hlsl_path() { // (the kernel form of the tests is no thread group of a title's: its barrier stays) kernel::translate(&code, o(true, true)).expect("kernel"); // a mesh program's compute pass: two console waves a group, as a retail title's - let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64 }; + let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64, params: None }; for split in [true, false] { let e = kernel::translate_mesh(&code, o(true, split), &ms(128)).err().unwrap_or_else(|| panic!("a mesh pass translated (split {split})")); assert!(e.contains("s_barrier in a group of several hardware waves"), "{e}"); diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index 0264fdb555..13c6d68bce 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -12,6 +12,7 @@ pub(crate) mod fence; pub mod pack; pub mod rdna2; pub mod recomp; +pub mod rt_leave_out; mod rdna2_spec; mod rdna2_xbox; pub mod shader; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 7f08cda47e..766558a9c7 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; -use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; use super::upper_lanes::Read; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -73,6 +73,9 @@ pub(super) struct Em { /// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits, /// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`. safe_barrier: bool, + /// program writes/atomics global or image UAVs or uses `GLC=1`: `s_barrier` must also flush + /// global device memory (`AllMemoryBarrierWithGroupSync` / `AllMemoryBarrier`) on RDNA4. + barrier_uav_fence: bool, /// the T# SGPRs of the program's image stores and atomics (`image_write_srsrcs`) img_writes: Vec, /// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`) @@ -82,6 +85,23 @@ pub(super) struct Em { pub writes_lds: bool, } +/// True when the program writes or atomically updates global/image memory or performs a +/// globally-coherent (`GLC=1`) memory access. On RDNA4, `s_barrier` in such shaders must emit +/// a global UAV fence (`AllMemoryBarrierWithGroupSync` / `barrier::ALL_SYNC`) so L0/L1 caches +/// become visible across waves/workgroups alongside LDS/TGSM. +pub fn has_uav_write_or_glc(insts: &[Decoded]) -> bool { + insts.iter().any(|d| { + if !matches!(d.enc.name, "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_SMEM") { + return false; + } + if rdna2::field_value(d.enc, &d.words, "GLC") == Some(1) { + return true; + } + let n = d.inst.name; + n.contains("STORE") || n.contains("ATOMIC") + }) +} + /// The T# SGPRs (SRSRC) of a program's image stores and atomics, at most 16, sorted. An /// image_load reads through the UAV (`tw0 + 1`) where the invocation stored to the same image /// before (`xcl_iw{srsrc}` holds `tw0 + 1` of the last such store): the SRV need not see a @@ -629,6 +649,7 @@ impl Em { dynamic_f16_rm: false, track_frexp_denorm: false, safe_barrier: false, + barrier_uav_fence: false, img_writes: Vec::new(), coherent_mem: false, writes_lds: false, @@ -651,6 +672,7 @@ impl Em { pub fn configure_round_modes(&mut self, insts: &[Decoded], stop_at_endpgm: bool) { self.track_frexp_denorm = tracks_frexp_f32_denorm(insts); self.img_writes = image_write_srsrcs(insts); + self.barrier_uav_fence = has_uav_write_or_glc(insts); let mut writes_nonzero_dp = false; let mut has_s_barrier = false; for d in insts { @@ -1306,20 +1328,26 @@ impl Em { match name { "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" => Flow::End, "s_barrier" => { + let sync_fn = if self.barrier_uav_fence { "AllMemoryBarrierWithGroupSync" } else { "GroupMemoryBarrierWithGroupSync" }; + let mem_fn = if self.barrier_uav_fence { "AllMemoryBarrier" } else { "GroupMemoryBarrier" }; if self.x64() && matches!(self.opt.mode, Mode::Geometry(_)) { // split ES+GS: the GS phase runs in the lower hardware wave alone (one console // wave: nothing to wait for), a group barrier there would wait for the other - self.line("if (xcl_es_phase) GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("if (xcl_es_phase) {sync_fn}();")); } else if matches!(self.opt.mode, Mode::Compute(_) | Mode::Mesh(_)) { if self.safe_barrier { - self.line("xcl_s_barrier();"); + if self.barrier_uav_fence { + self.line("AllMemoryBarrier(); xcl_s_barrier(); AllMemoryBarrier();"); + } else { + self.line("xcl_s_barrier();"); + } } else if self.compute_or_mesh_hw_waves() == Some(1) { - self.line("GroupMemoryBarrier();"); + self.line(&format!("{mem_fn}();")); } else { - self.line("GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("{sync_fn}();")); } } else if matches!(self.opt.mode, Mode::Kernel | Mode::Geometry(_)) { - self.line("GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("{sync_fn}();")); } // split wave64: both halves made their LDS writes before the barrier (a half // without a partner has nothing to wait for) @@ -1329,10 +1357,13 @@ impl Em { Flow::Next } "s_sendmsg" if matches!(self.opt.mode, Mode::Geometry(_)) => { - // MSG_GS (2): op 1 cut, 2 emit, 3 emit + cut (stream 0); GS_DONE (3) – nothing to do + // MSG_GS (2) and MSG_GS_DONE (3): op 1 cut, 2 emit, 3 emit + cut (stream 0) let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0); let (msg, op, stream) = (simm & 0xF, (simm >> 4) & 3, (simm >> 8) & 3); - if let (2, 0, Mode::Geometry(g)) = (msg, stream, &self.opt.mode) { + if let (2 | 3, 0, Mode::Geometry(g)) = (msg, stream, &self.opt.mode) { + if op == 0 { + return Flow::Next; + } let maxt = g.max_vertex_count.saturating_sub(2).max(1); let act = self.act(); if op & 2 != 0 { @@ -2348,18 +2379,26 @@ impl Em { // param N is a register: channel c goes to component c of every element there let k = (tgt - 32) as usize; let params = ranked(&vs.outputs, true); - let at = vs_param_register(vs, k).map(|r| elements_at(&vs.outputs, true, r)).unwrap_or_default(); + let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); } - for j in at { + for (j, first) in at { let e = params[j]; let n = out_comps(e); for c in 0..n { - if enabled(c) { - let v = Self::exp_comp(srcs, compr, c); - let v = if e.component_type == 3 { format!("asfloat({v})") } else { format!("{v}") }; + // packed float16: component c is half c & 1 of dword first + c / 2 + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let v = Self::exp_comp(srcs, compr, dw); + let v = if f16 { + format!("f16tof32({v} >> {}u)", 16 * (c & 1)) + } else if e.component_type == 3 { + format!("asfloat({v})") + } else { + format!("{v}") + }; let comp = if n == 1 { String::new() } else { format!("[{c}]") }; st.push(format!("xo.p{j}{comp} = {v};")); } @@ -2380,6 +2419,11 @@ impl Em { (2, false) => format!("(int){raw}"), (_, _) => raw, }; + let v = if e.component_type == 3 && crate::gpu::dxil::kernel::nan_guard_enabled() { + format!("((asuint({v}) & 0x7FFFFFFFu) > 0x7F800000u ? 0.0f : clamp({v}, -65504.0f, 65504.0f))") + } else { + v + }; st.push(format!("xo.t{tgt}[{c}] = {v};")); } } else { @@ -2410,15 +2454,19 @@ impl Em { // param N is a register: its record slot is that of every element there (the // pass-through reads an element's slot as the whole register, as for the GS) let k = (tgt - 32) as usize; - let at = param_registers(&ms.outputs, true).get(k).map(|&r| elements_at(&ms.outputs, true, r)).unwrap_or_default(); + let (at, f16) = out_param_elements(&ms.outputs, ms.params.as_deref(), k); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); } - for j in at { + for (j, first) in at { for c in 0..4 { - if enabled(c) { - st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {});", 4 * (j + 1) + c, Self::exp_comp(srcs, compr, c))); + // packed float16 (as in the VS): the record keeps each half as a float + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let v = Self::exp_comp(srcs, compr, dw); + let v = if f16 { format!("asuint(f16tof32({v} >> {}u))", 16 * (c & 1)) } else { v }; + st.push(format!("if (xcl_vok) res.Store((xcl_vtx + {}u) * 4u, {v});", 4 * (j + 1) + c)); } } } @@ -2459,10 +2507,21 @@ impl Em { fn interp(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> { let Mode::Pixel(ps) = &self.opt.mode else { return Err("interpolation outside PS") }; let (vdst, ij, attr, chan) = Self::interp_fields(d); - let Some(slot) = ps_attribute_slot(ps, attr as usize, chan as usize) else { - return Err("attribute outside ISG1"); + // a float16-packed attribute (two registers, two components per dword): the PC input + // is the component itself, interpolated as a float – SRC0 bit 8 picks the high half + let high = d.enc.name != "ENC_VINTRP" && rdna2::field_value(d.enc, &d.words, "SRC0").unwrap_or(0) >> 8 & 1 == 1; + let src = match ps_attribute_f16(ps, attr as usize).filter(|_| name.ends_with("_f16")) { + Some(regs) => match ps_f16_slot(ps, ®s, chan as usize, high) { + Some((slot, comp)) => format!("xi.a{slot}[{comp}]"), + None => "0.0f".to_string(), + }, + None => { + let Some(slot) = ps_attribute_slot(ps, attr as usize, chan as usize) else { + return Err("attribute outside ISG1"); + }; + format!("xi.a{slot}[{chan}]") + } }; - let src = format!("xi.a{slot}[{chan}]"); let act = self.act(); match name { "v_interp_p1_f32" | "v_interp_p1ll_f16" | "v_interp_p1lv_f16" => { @@ -4460,12 +4519,17 @@ impl Em { Ok(()) } - /// scratch_*: per-lane private memory (`xcl_scratch`); address = SADDR or VADDR + offset. + /// scratch_*: per-lane private memory (`xcl_scratch`); address = SADDR, VADDR or 0, + offset. fn scratch(&mut self, d: &Decoded, op: &str) -> Result<(), &'static str> { let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); self.uses_scratch = true; - let saddr = f("SADDR"); - let base = if saddr != 0x7D && saddr != 0x7F { self.sreg(saddr) } else { self.vreg(f("ADDR")) }; + // RDNA2 has no SGPR + VGPR form (no SVE bit): SADDR 0x7F (EXEC_HI) is the ST form, + // the offset alone; NULL (0x7D) is SV, VADDR + offset; an SGPR is SS, SGPR + offset + let base = match f("SADDR") { + 0x7F => "0u".to_string(), + 0x7D => self.vreg(f("ADDR")), + s => self.sreg(s), + }; let raw = f("OFFSET") as u32; let off = (((raw << 20) as i32) >> 20) as u32; let t = self.t(); @@ -5350,7 +5414,9 @@ static uint xcl_cap = 1u << 16; // the mode of the attribute this input is read through (none: never read) let attr = ps_slot_attribute(ps, k); let mut m = attr.and_then(|a| self.ps_modes.get(&(a as u32))).cloned().unwrap_or_default(); - if e.component_type != 3 { + // float16 read through a packed attribute interpolates like a float + let f16 = e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some()); + if e.component_type != 3 && !f16 { m = "nointerpolation".into(); } let _ = writeln!(h, " {m} {}4 a{k} : {};", hlsl_type(e), e.semantic()); @@ -5377,7 +5443,13 @@ static uint xcl_cap = 1u << 16; if !self.ps_writes_mask && !ps.outputs.iter().any(|e| matches!(e.system_value, 64 | 65 | 67 | 68)) { h.push_str(" float4 xcl_unused : SV_Target7;\n"); } - h.push_str("};\nXclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n"); + h.push_str("};\n"); + // the console tests depth first: without it the PC runs (and keeps the memory + // writes of) hidden pixels too + if ps.early_depth { + h.push_str("[earlydepthstencil]\n"); + } + h.push_str("XclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n"); if self.ps_writes_mask { h.push_str(" xo.xcl_mask = 0xFFFFFFFFu;\n"); } diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 1ae5c75a4e..098a610e52 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -396,8 +396,8 @@ fn heap_windows_graphics_stages_validate() { ps_code.extend(e("S_ENDPGM", "ENC_SOPP", &[])); let vs = VsInterface { inputs: vec![], outputs: vec![sig("SV_Position", 1, 0)], attr_base: 4, params: None }; - let ps = PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0, attrs: None }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 3, max_primitives: 1 }; + let ps = PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0, attrs: None, early_depth: false }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 3, max_primitives: 1, params: None }; let has_dxc = super::dxc::location().is_ok(); for windows in [4u32, crate::gpu::uma::MAX_HEAP_WINDOWS as u32] { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 7f876ee9ca..dc0d08c65b 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -61,6 +61,7 @@ pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; pub mod partition; +pub mod ps_masks; pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; @@ -85,6 +86,11 @@ pub const MEM_HEAP_BASE: u32 = 4; /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; +/// Flag in a memory-windows count next to `HEAP_WINDOWS` (`pso::mem_windows`, the caches' keys): +/// the direct DXIL translator reads heap windows without a branch (`Lw::with_mem_i32s`). The +/// HLSL path ignores it. +pub const HEAP_FLAT: u32 = 0x200; + pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { windows <= crate::gpu::uma::MAX_WINDOWS || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) @@ -119,7 +125,7 @@ pub struct VsInterface { pub attr_base: u64, /// the OSG1 register of each `exp param N` from the console's table (`vs_output_table`; /// None: the N-th distinct register) - pub params: Option>, + pub params: Option>, } impl VsInterface { @@ -153,6 +159,9 @@ pub struct PsInterface { pub input_ena: u32, /// the console's PS input table (`ps_input_table`; None: attributes in register order) pub attrs: Option>, + /// DB_SHADER_CONTROL.DEPTH_BEFORE_SHADER (`ps_shader_control`): depth and stencil are tested + /// before the program runs (`[earlydepthstencil]`), so it runs only for pixels that pass + pub early_depth: bool, } /// Mesh (NGG) shader interface. @@ -164,6 +173,8 @@ pub struct MsInterface { pub threads: u32, pub max_vertices: u32, pub max_primitives: u32, + /// the console's output table, as `VsInterface::params` + pub params: Option>, } /// dwords before the vertices of a mesh record: vertex count, primitive count, 2 spare @@ -255,6 +266,7 @@ impl GsInterface { threads: 64, max_vertices: (GS_PRIMS_PER_GROUP * mvc).clamp(1, 256), max_primitives: (GS_PRIMS_PER_GROUP * mvc.saturating_sub(2).max(1)).clamp(1, 256), + params: None, } } } @@ -392,6 +404,19 @@ pub struct PsAttr { pub register: u8, pub mask: u8, pub flat: bool, + /// float16 values, two per dword (record flag 8) – see `f16_registers` + pub f16: bool, + /// the record names a second register (flag 16; the same register again: not named) + pub pair: Option, +} + +/// One `exp param N` of the console's output table: its first OSG1 register; `f16`: float16 +/// values, two per dword (`pair`: more than one dword – a second register may follow). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OutParam { + pub register: u32, + pub f16: bool, + pub pair: bool, } /// The PS input table of an FSSM: SPI_PS_INPUT_ENA and, per `v_interp attrN`, the register it @@ -399,6 +424,11 @@ pub struct PsAttr { /// mask, attribute number, 0, 0, register again, 1 flat / 2 interpolated; then the record count /// (+0x100) and SPI_PS_INPUT_ENA (+0x110). Checked on every cached PS of three titles (472, 34, /// 1): consistent, and covering every attribute the code reads. +/// +/// A title that packs its float16 interpolants (378 such records in 362 PS of one): byte 7 also +/// has 8 (float16, two per dword) and 16 (byte 5 = the second register of the attribute), and +/// byte 6 is the register counted after that packing (below the DXIL register from the first +/// pair on). pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { let base = 0x130 + fssm_shift(fssm)?; let rd = |o: usize| fssm.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); @@ -409,20 +439,35 @@ pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { let mut out = Vec::with_capacity(n); for k in 0..n { let r = fssm.get(base + 8 * k..base + 8 * k + 8)?; - if r[3] as usize != k || r[4] != 0 || r[5] != 0 || r[6] != r[1] { + let (f16, pair) = (r[7] & 8 != 0, r[7] & 16 != 0); + if r[3] as usize != k || r[4] != 0 || (!pair && r[5] != 0) || (pair && !f16) || r[6] > r[1] { return None; } - out.push(PsAttr { kind: r[0], register: r[1], mask: r[2], flat: r[7] == 1 }); + out.push(PsAttr { kind: r[0], register: r[1], mask: r[2], flat: r[7] & 3 == 1, f16, pair: pair.then_some(r[5]) }); } Some((ena, out)) } +/// DB_SHADER_CONTROL bit 12 (DEPTH_BEFORE_SHADER, as AMD's GFX10.3 register headers name it): +/// the compiler sets it for `[earlydepthstencil]`. +pub const DEPTH_BEFORE_SHADER: u32 = 1 << 12; + +/// DB_SHADER_CONTROL of an FSSM: the dword after SPI_PS_INPUT_ENA in the PS input table +/// (`ps_input_table`, +0x114; the same layout VIctory's `native.rs` reads it from). +pub fn ps_shader_control(fssm: &[u8]) -> Option { + let o = 0x130 + fssm_shift(fssm)? + 0x114; + fssm.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())) +} + /// The VS output table of an FSSM: per `exp param N`, the OSG1 register it writes. 32 records /// of 6 bytes at +0x1D4 (+ the sub-version shift): kind (6 user, 0 position), register, param /// number, 0, 0, 0; the record count after them (+0xC0). Usually param N = the N-th output /// register, but not always (a Fortnite VS exports its SV_Position register as a param). -/// Checked on every cached VS of three titles (984, 13, 1). -pub fn vs_output_table(fssm: &[u8]) -> Option> { +/// Checked on every cached VS of three titles (984, 13, 1). The same table describes a mesh +/// (NGG) program's params. A float16 param (two values per dword) has 1 in the last byte, 3 +/// when it takes more than one dword, and then repeats its register in byte 3 (442 MS of one +/// title); the table does not name the second register of a pair (`f16_registers`). +pub fn vs_output_table(fssm: &[u8]) -> Option> { let base = 0x1D4 + fssm_shift(fssm)?; let n = fssm.get(base + 0xC0..base + 0xC4).map(|b| u32::from_le_bytes(b.try_into().unwrap()))? as usize; if n > 32 { @@ -431,14 +476,78 @@ pub fn vs_output_table(fssm: &[u8]) -> Option> { let mut out = Vec::with_capacity(n); for k in 0..n { let r = fssm.get(base + 6 * k..base + 6 * k + 6)?; - if r[2] as usize != k || r[3..6] != [0, 0, 0] { + let f16 = r[5] & 1 == 1; + if r[2] as usize != k || r[4] != 0 || !matches!(r[5], 0 | 1 | 3) || (r[3] != 0 && !(f16 && r[3] == r[1])) { return None; } - out.push(r[1] as u32); + out.push(OutParam { register: r[1] as u32, f16, pair: r[5] == 3 }); } Some(out) } +/// Where a float16-packed param / attribute keeps its registers: (register, first dword). +/// The console's compiler puts two float16 components in a dword – component c of a register +/// in dword c / 2, the even one in the low half – and up to two registers in one param: the +/// second follows the dwords the first one's components take (2 for .xyz / .xyzw, 1 for .xy). +/// The registers pair up in order, so where a table does not name the second one it is the +/// next float16 register that starts no param of its own (`claimed`). Checked against the +/// code of a retail title: every `v_interp_p2_f16` channel / half of 376 packed attributes +/// (362 PS) is a declared component (2 more read one past a .xy register), and the enable +/// mask of every `exp param` of 383 packed params (442 MS) is exactly these dwords. +pub fn f16_registers(sig: &[SigElement], first: u32, second: Option, pair: bool, claimed: &dyn Fn(u32) -> bool) -> Vec<(u32, usize)> { + let second = match second { + Some(r) if r != first => Some(r), + _ if !pair => None, + _ => sig.iter().filter(|e| e.component_type == 6 && e.system_value == 0 && e.register > first && !claimed(e.register)).map(|e| e.register).min(), + }; + let width = sig.iter().filter(|e| e.system_value == 0 && e.register == first).map(|e| 8 - e.mask.leading_zeros() as usize).max().unwrap_or(4); + std::iter::once((first, 0)).chain(second.map(|r| (r, width.div_ceil(2)))).collect() +} + +/// The registers of `exp param N` with the first dword of each (`f16_registers`), and whether +/// they hold packed float16: the console's table, else the N-th distinct register. +pub fn out_param_registers(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize) -> Option<(Vec<(u32, usize)>, bool)> { + match params { + Some(t) => { + let p = t.get(n)?; + if !p.f16 { + return Some((vec![(p.register, 0)], false)); + } + Some((f16_registers(outputs, p.register, None, p.pair, &|r| t.iter().any(|q| q.register == r)), true)) + } + None => param_registers(outputs, true).get(n).map(|&r| (vec![(r, 0)], false)), + } +} + +/// The elements `exp param N` writes (places in `ranked(outputs, true)`), each with the first +/// dword of its register, and whether the param holds packed float16 (`out_param_registers`). +pub fn out_param_elements(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize) -> (Vec<(usize, usize)>, bool) { + let (regs, f16) = out_param_registers(outputs, params, n).unwrap_or_default(); + (regs.iter().flat_map(|&(r, first)| elements_at(outputs, true, r).into_iter().map(move |j| (j, first))).collect(), f16) +} + +/// The registers of a float16-packed PS attribute with the first dword of each (None: the +/// attribute is not packed). +pub fn ps_attribute_f16(ps: &PsInterface, attr: usize) -> Option> { + let t = ps.attrs.as_ref()?; + let a = t.get(attr).filter(|a| a.f16)?; + let claimed = |r: u32| t.iter().any(|b| b.register as u32 == r || b.pair.is_some_and(|p| p as u32 == r)); + Some(f16_registers(&ps.inputs, a.register as u32, a.pair.map(|p| p as u32), a.pair.is_some(), &claimed)) +} + +/// The place in `ranked(inputs, false)` and the component of the float16 in half `high` of +/// dword `chan` of a packed attribute (`regs`: `ps_attribute_f16`). None: no such component. +pub fn ps_f16_slot(ps: &PsInterface, regs: &[(u32, usize)], chan: usize, high: bool) -> Option<(usize, usize)> { + let &(r, first) = regs.iter().rev().find(|&&(_, first)| first <= chan)?; + let comp = 2 * (chan - first) + high as usize; + if comp > 3 { + return None; + } + let all = ranked(&ps.inputs, false); + let slot = all.iter().position(|e| e.register == r && e.mask >> comp & 1 == 1).or_else(|| all.iter().position(|e| e.register == r))?; + Some((slot, comp)) +} + /// The register `v_interp attr` reads: the console's table, else the attr-th distinct register. pub fn ps_attribute_register(ps: &PsInterface, attr: usize) -> Option { match &ps.attrs { @@ -459,7 +568,10 @@ pub fn ps_attribute_slot(ps: &PsInterface, attr: usize, chan: usize) -> Option Option { let r = ranked(&ps.inputs, false).get(slot)?.register; match &ps.attrs { - Some(t) => t.iter().position(|a| a.register as u32 == r), + Some(t) => t + .iter() + .position(|a| a.register as u32 == r) + .or_else(|| (0..t.len()).find(|&k| ps_attribute_f16(ps, k).is_some_and(|regs| regs.iter().any(|&(x, _)| x == r)))), None => param_registers(&ps.inputs, false).iter().position(|&x| x == r), } } @@ -467,7 +579,7 @@ pub fn ps_slot_attribute(ps: &PsInterface, slot: usize) -> Option { /// The register `exp param N` of a VS writes: the console's table, else the N-th distinct one. pub fn vs_param_register(vs: &VsInterface, n: usize) -> Option { match &vs.params { - Some(t) => t.get(n).copied(), + Some(t) => t.get(n).map(|p| p.register), None => param_registers(&vs.outputs, true).get(n).copied(), } } @@ -496,7 +608,9 @@ pub fn interface(blob: &[u8], sh: &super::xbox::XboxShader, f: &super::xbox::Fss Some((ena, t)) => (ena, Some(t)), None => (f.data.get(0x248..0x24C).map(|b| u32::from_le_bytes(b.try_into().unwrap()))?, None), }; - Some(Mode::Pixel(PsInterface { inputs, outputs, input_ena: ena, attrs })) + // only where the input table was found: elsewhere the layout is not known + let early_depth = attrs.is_some() && ps_shader_control(&f.data).is_some_and(|c| c & DEPTH_BEFORE_SHADER != 0); + Some(Mode::Pixel(PsInterface { inputs, outputs, input_ena: ena, attrs, early_depth })) } // ES variant of a VS (before a GS) and the GS itself, each translatable on its own ("VS", 2) => Some(Mode::Geometry(GsInterface { es_inputs: inputs, es_outputs: outputs, max_vertex_count: 1, ..Default::default() })), @@ -516,6 +630,7 @@ pub fn interface(blob: &[u8], sh: &super::xbox::XboxShader, f: &super::xbox::Fss threads, max_vertices: (p.ms_max_vertices as u32).clamp(1, 256), max_primitives: (p.ms_max_primitives as u32).clamp(1, 256), + params: vs_output_table(&f.data), })) } _ => None, @@ -1634,8 +1749,12 @@ pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { pub fn translate(code: &[u8], opt: &Options) -> Result { let program = code; let normalized; - let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { - normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; + let opt = if opt.mem_windows & (HEAP_WINDOWS | HEAP_FLAT) != 0 { + normalized = Options { + mem_windows: opt.mem_windows & !(HEAP_WINDOWS | HEAP_FLAT), + heap_windows: opt.heap_windows || opt.mem_windows & HEAP_WINDOWS != 0, + ..opt.clone() + }; &normalized } else { opt @@ -1836,7 +1955,7 @@ mod attribute_tests { f[0x10] = 5; f[0x1D4..0x1D4 + 18].copy_from_slice(&[6, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 6, 2, 2, 0, 0, 0]); f[0x1D4 + 0xC0] = 3; - assert_eq!(vs_output_table(&f), Some(vec![0, 1, 2])); + assert_eq!(vs_output_table(&f).map(|t| t.iter().map(|p| p.register).collect::>()), Some(vec![0, 1, 2])); f[0x1D4 + 8] = 7; assert_eq!(vs_output_table(&f), None); } diff --git a/crates/xcl/src/gpu/recomp/ps_masks.rs b/crates/xcl/src/gpu/recomp/ps_masks.rs new file mode 100644 index 0000000000..026f8a2a4b --- /dev/null +++ b/crates/xcl/src/gpu/recomp/ps_masks.rs @@ -0,0 +1,581 @@ +//! Pixel shaders (#2083): which compare masks need each helper lane's bit from its quad. +//! +//! On the console a pixel shader's masks hold helper lanes' bits; here `WaveActiveBallot` +//! leaves them out, so `Lw::ballot_ps_quad` rebuilds every quad's four bits from quad reads +//! of the compare's operands. That costs four ballots and up to eight quad reads per compare. +//! Most masks need less. With `WaveActiveBallot(c) | own bit` (HLSL `ballot_px_local`) every +//! lane's copy of the mask has the live lanes' bits and its own bit right, so EXEC +//! predication, `v_cndmask` selectors and carry-ins stay exact in helper lanes, and so do the +//! values they compute; only another helper lane's bit can be wrong. This forward analysis +//! frees a compare when nothing reads such a bit: +//! - bitwise SALU (and, or, xor, andn2, not, mov, cselect, saveexec, wrexec) carries the mask on; +//! - any other SALU read, SCC or VCCZ of it, a VALU / SMEM scalar operand refuse it; +//! - so do cross-lane instructions while EXEC carries it: DPP, `ds_swizzle` / `bpermute`, +//! permlane read their source lane's bit of the reader's EXEC, `v_readfirstlane` the +//! first set one (waterfall loops); +//! - a branch on such an EXEC (EXECZ, or SCC of a write to EXEC) lets copies of the mask take +//! different paths: lanes that skip have their own bit 0, but the SGPRs and SCC the region +//! writes differ after it (refused if read), and so does EXEC if the region widens it; +//! - a register known to be a subset of the entry EXEC (the live lanes: the kill mask) has +//! no helper bits at all, so it is exact whatever it was computed from. +//! A compare that keeps the per-quad form under such an EXEC ORs in its own bit, which the +//! quad's other lanes may not have seen (`Lw::vopc`). + +use crate::gpu::rdna2::{self, Decoded, Variant, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; +use super::x64_masks; +use std::collections::BTreeMap; + +const VCC: u128 = 3 << 106; +const EXEC: u128 = 3 << 126; + +fn fv(d: &Decoded, f: &str) -> Option { + rdna2::field_value(d.enc, &d.words, f) +} +fn b64(n: &str) -> bool { + n.ends_with("_B64") || n.contains("_B64_") +} +fn regs(code: u64, n: u64) -> u128 { + if code < 128 { ((1u128 << n) - 1) << code } else { 0 } +} +fn is_salu(d: &Decoded) -> bool { + matches!(d.enc.name, "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPK" | "ENC_SOPC") +} +pub fn is_site(d: &Decoded) -> bool { + let n = d.inst.name; + n.starts_with("V_CMP") && d.variant == Variant::Plain && !n.starts_with("V_CMP_F_") && !n.starts_with("V_CMPX_F_") +} +fn bitwise(n: &str) -> bool { + n.contains("_SAVEEXEC_") + || n.contains("_WREXEC") + || ["S_AND_B", "S_OR_B", "S_XOR_B", "S_ANDN2_B", "S_ORN2_B", "S_NAND_B", "S_NOR_B", "S_XNOR_B", "S_NOT_B", "S_MOV_B32", "S_MOV_B64", "S_CMOV_B", "S_CSELECT_B"] + .iter() + .any(|p| n.starts_with(p)) +} +fn writes_scc(n: &str) -> bool { + (bitwise(n) && !n.starts_with("S_MOV") && !n.starts_with("S_CMOV") && !n.starts_with("S_CSELECT")) + || ["S_CMP", "S_BITCMP", "S_ADD_", "S_ADDC_", "S_SUB_", "S_SUBB_", "S_MIN_", "S_MAX_", "S_LSHL", "S_LSHR", "S_ASHR", "S_BFE_", "S_ABSDIFF", "S_WQM", "S_BCNT", "S_QUADMASK", "S_ABS_", "S_ADDK", "S_CMPK"] + .iter() + .any(|p| n.starts_with(p)) +} +fn reads_scc(n: &str) -> bool { + n.starts_with("S_CSELECT") || n.starts_with("S_CMOV") || n.starts_with("S_ADDC") || n.starts_with("S_SUBB") +} +/// every SGPR the instruction writes (also the partial writes `uses` leaves out) +fn writes(d: &Decoded) -> u128 { + let n = d.inst.name; + if n.starts_with("S_MOVRELD") { + return !0; + } + let (_, mut w) = x64_masks::uses(d); + if is_salu(d) { + if let Some(s) = fv(d, "SDST") { + w |= regs(s, if b64(n) { 2 } else { 1 }); + } + } + w +} +fn per_lane(d: &Decoded) -> u128 { + let n = d.inst.name; + if !(matches!(n, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") || n.starts_with("V_DIV_FMAS")) { + return 0; + } + match fv(d, "SRC2") { + Some(v) if d.enc.name.contains("VOP3") => regs(v, 2), + _ => VCC, + } +} +fn xlane(d: &Decoded) -> bool { + matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) + || matches!(d.inst.name, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" | "V_READFIRSTLANE_B32") +} + +#[derive(Clone, Copy, PartialEq, Default)] +struct St { + t: u128, + a: u128, + scc: u8, +} +impl St { + fn join(self, o: St) -> St { + St { t: self.t | o.t, a: self.a | o.a, scc: self.scc.max(o.scc) } + } +} + +/// SGPRs known to be a subset of a reference mask after `d`, from those before it +/// (`set`; EXEC's bit 126 in it: EXEC is). AND / ANDN2 keep a bounded first operand's +/// bound, OR / XOR / CSELECT need both, a compare's mask is a subset of EXEC. +fn subset_after(d: &Decoded, set: u128) -> u128 { + let n = d.inst.name; + let w = writes(d); + let mut out = set & !w; + let e_in = set >> 126 & 1 != 0; + if n.starts_with("V_CMP") { + if e_in { + out |= w; + } + return out; + } + if !is_salu(d) { + return out; + } + let wd = if b64(n) { 2 } else { 1 }; + let isb = |c: Option| c.is_some_and(|c| c == 128 || { let r = regs(c, wd); r != 0 && r & !set == 0 }); + let (s0, s1, sd) = (fv(d, "SSRC0"), fv(d, "SSRC1"), fv(d, "SDST")); + let sdr = sd.map_or(0, |v| regs(v, wd)); + if n.contains("_SAVEEXEC_") { + if e_in { + out |= sdr; + } + let ex = if n.starts_with("S_AND_SAVEEXEC") { + isb(s0) || e_in + } else if n.starts_with("S_ANDN1_SAVEEXEC") { + e_in + } else if n.starts_with("S_ANDN2_SAVEEXEC") { + isb(s0) + } else if n.starts_with("S_OR_SAVEEXEC") || n.starts_with("S_XOR_SAVEEXEC") { + isb(s0) && e_in + } else { + false + }; + if ex { + out |= EXEC; + } + return out; + } + let b = if n.starts_with("S_ANDN2_WREXEC") { + isb(s0) + } else if n.starts_with("S_ANDN1_WREXEC") { + isb(s1) + } else if n.starts_with("S_MOV_B") { + isb(s0) + } else if n.starts_with("S_AND_B") { + isb(s0) || isb(s1) + } else if n.starts_with("S_ANDN2_B") { + isb(s0) + } else if n.starts_with("S_OR_B") || n.starts_with("S_XOR_B") || n.starts_with("S_CSELECT_B") { + isb(s0) && isb(s1) + } else { + false + }; + if b { + out |= w; + } + out +} + +/// SGPRs that are a subset of the live lanes (the entry EXEC) after each instruction: +/// their helper-lane bits are 0, so the local form leaves them exact +fn live_subsets(insts: &[Decoded], succ: &[Vec]) -> Vec { + let n = insts.len(); + let mut zin = vec![!0u128; n]; + let mut seen = vec![false; n]; + zin[0] = EXEC; + seen[0] = true; + let mut work = vec![0usize]; + let mut queued = vec![false; n]; + queued[0] = true; + while let Some(i) = work.pop() { + queued[i] = false; + let o = subset_after(&insts[i], zin[i]); + for &j in &succ[i] { + let nz = if seen[j] { zin[j] & o } else { o }; + if !seen[j] || nz != zin[j] { + seen[j] = true; + zin[j] = nz; + if !queued[j] { + queued[j] = true; + work.push(j); + } + } + } + } + (0..n).map(|i| if seen[i] { subset_after(&insts[i], zin[i]) } else { !0 }).collect() +} + +/// A conditional branch's region (forward: up to its target; backward: the loop) and what +/// differs after it when copies of the mask disagree on taking it. +struct Region { + joins: Vec, + /// SGPRs it writes + w: u128, + scc: bool, + /// it widens EXEC, or runs something EXEC does not mask (v_writelane, scalar stores, + /// messages) that the lanes skipping it would miss + bad: bool, +} + +/// The form each pixel-shader compare's mask can take, by address (compares not in it +/// keep the per-quad form of `Lw::ballot_ps_quad`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Form { + /// never read whole: the lane's own bit + Own, + /// read whole, but no other lane's helper bit is: `WaveActiveBallot | own bit` + Local, + /// both operands scalar / constant: `cond ? EXEC : 0` + Uniform, +} + +pub fn forms(insts: &[Decoded]) -> BTreeMap { + let n = insts.len(); + let mut out = BTreeMap::new(); + if n == 0 { + return out; + } + let pcs: std::collections::BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let mut indirect = vec![false; n]; + let succ: Vec> = insts + .iter() + .enumerate() + .map(|(i, d)| { + let next = if i + 1 < n { Some(i + 1) } else { None }; + if let Some(t) = d.far_target { + return pcs.get(&t).copied().into_iter().collect(); + } + if d.inst.flags & F_INDIRECT != 0 || d.inst.name == "S_SETPC_B64" || d.inst.name == "S_SWAPPC_B64" { + indirect[i] = true; + return Vec::new(); + } + let mut v = Vec::new(); + if let Some(t) = rdna2::branch_target(d) { + v.extend(pcs.get(&t).copied()); + if d.inst.flags & F_CONDITIONAL != 0 { + v.extend(next); + } + } else if d.inst.flags & F_TERMINATOR == 0 { + v.extend(next); + } + v + }) + .collect(); + let z = live_subsets(insts, &succ); + // conditional branches: the region whose execution may differ between copies + let mut region: Vec> = (0..n).map(|_| None).collect(); + for (b, d) in insts.iter().enumerate() { + if d.inst.flags & F_CONDITIONAL == 0 { + continue; + } + let Some(t) = rdna2::branch_target(d).and_then(|t| pcs.get(&t).copied()) else { continue }; + let (lo, hi, mut joins) = if t > b { (b + 1, t, vec![t]) } else { (t, b + 1, vec![b + 1]) }; + if t <= b { + for k in lo..hi { + for &s in &succ[k] { + if (s < lo || s >= hi) && !joins.contains(&s) { + joins.push(s); + } + } + } + } + let (mut w, mut scc, mut bad) = (0u128, false, false); + let mut bound: u128 = EXEC; + for k in lo..hi.min(n) { + let dk = &insts[k]; + w |= writes(dk) & !EXEC; + scc |= writes_scc(dk.inst.name); + bound = subset_after(dk, bound); + let nk = dk.inst.name; + bad |= writes(dk) & EXEC != 0 && bound >> 126 & 1 == 0 + || nk == "V_WRITELANE_B32" + || nk.starts_with("S_SENDMSG") + || dk.enc.name == "ENC_SMEM" && (nk.contains("STORE") || nk.contains("ATOMIC")); + } + region[b] = Some(Region { joins, w, scc, bad }); + } + let live = x64_masks::whole_live_out(insts, false); + for site in 0..n { + let d = &insts[site]; + if !is_site(d) { + continue; + } + let dst = writes(d); + if dst == 0 { + continue; + } + if live[site] & dst == 0 && !d.inst.name.starts_with("V_CMPX") { + out.insert(d.pc, Form::Own); + continue; + } + // both operands scalar / constant: the mask is `cond ? EXEC : 0`, no ballot needed + let uniform = d.enc.name.contains("VOP3") && fv(d, "SRC0").is_some_and(|v| v < 256) && fv(d, "SRC1").is_some_and(|v| v < 256); + if uniform { + out.insert(d.pc, Form::Uniform); + } else if run(insts, &succ, &indirect, &z, ®ion, site).is_ok() { + out.insert(d.pc, Form::Local); + } + } + out +} + +fn run(insts: &[Decoded], succ: &[Vec], indirect: &[bool], z: &[u128], region: &[Option], site: usize) -> Result<(), &'static str> { + let n = insts.len(); + let mut sin = vec![St::default(); n]; + let mut extra = vec![St::default(); n]; + let mut div = vec![false; n]; + let mut work = vec![site]; + let mut queued = vec![false; n]; + queued[site] = true; + while let Some(i) = work.pop() { + queued[i] = false; + let st = sin[i].join(extra[i]); + if st == St::default() && i != site { + continue; + } + let d = &insts[i]; + let nm = d.inst.name; + let (whole, _) = x64_masks::uses(d); + let w = writes(d); + if (whole | per_lane(d)) & st.a != 0 { + return Err("read of a diverged register"); + } + if indirect[i] && (st.t | st.a) != 0 { + return Err("indirect jump"); + } + let mut o = St { t: st.t & !w, a: st.a & !w, scc: st.scc }; + let mut branch_div = false; + if d.enc.name == "ENC_SOPP" { + if nm.starts_with("S_CBRANCH_EXEC") { + branch_div = st.t & EXEC != 0; + } else if nm.starts_with("S_CBRANCH_SCC") { + if st.scc == 2 { + return Err("branch on SCC of a mask"); + } + branch_div = st.scc == 1; + } else if nm.starts_with("S_CBRANCH_VCC") { + if st.t & VCC != 0 { + return Err("branch on VCCZ"); + } + } else if whole & st.t != 0 { + return Err("other SOPP read"); + } + } else if is_salu(d) { + let rt = whole & st.t != 0; + if reads_scc(nm) && st.scc != 0 { + return Err("SCC read (cselect / cmov / addc)"); + } + if rt && !bitwise(nm) { + return Err(if nm.starts_with("S_CMP") || nm.starts_with("S_BITCMP") { + "s_cmp / s_bitcmp" + } else if nm.starts_with("S_WQM") { + "s_wqm" + } else { + "other SALU" + }); + } + match () { + _ if nm.contains("_SAVEEXEC_") || nm.contains("_WREXEC") => { + let et = st.t & EXEC != 0; + let srct = whole & !EXEC & st.t != 0; + let sd = w & !EXEC; + if et || srct { + o.t |= EXEC; + } + if nm.contains("_WREXEC") { + if et || srct { + o.t |= sd; + } + } else if et { + o.t |= sd; + } + } + _ => { + if rt { + o.t |= w; + } + } + } + if writes_scc(nm) { + // SCC of a bitwise op is its result != 0: exact when the result is live-only + let exact = w & !EXEC & !z[i] == 0 && (w & EXEC == 0 || z[i] >> 126 & 1 != 0); + o.scc = if rt && !exact { if w & EXEC != 0 { 1 } else { 2 } } else { 0 }; + } + } else if d.enc.name == "ENC_SMEM" { + if whole & st.t != 0 { + return Err("SMEM operand"); + } + } else { + // VALU / VMEM / DS / export + if st.a & EXEC != 0 { + return Err("diverged EXEC"); + } + let exec_data = d.variant == Variant::Plain && ["SRC0", "SRC1", "SRC2"].iter().any(|f| matches!(fv(d, f), Some(126 | 127))); + if whole & !EXEC & st.t != 0 || exec_data && st.t & EXEC != 0 { + return Err("VALU / VMEM scalar operand"); + } + if st.t & EXEC != 0 && xlane(d) { + return Err(match d.variant { + Variant::Dpp16 | Variant::Dpp8 => "DPP under the mask", + _ if nm == "V_READFIRSTLANE_B32" => "readfirstlane under the mask", + _ => "ds_swizzle / permute under the mask", + }); + } + if is_site(d) && (i == site || st.t & EXEC != 0) { + o.t |= w; + } + } + o.t &= !z[i]; + if branch_div && !div[i] { + div[i] = true; + if let Some(r) = ®ion[i] { + if r.bad { + return Err("branch on the mask over EXEC changes or unmasked work"); + } + for &j in &r.joins { + let e = St { t: 0, a: r.w, scc: if r.scc { 2 } else { 0 } }; + let ne = extra[j].join(e); + if ne != extra[j] { + extra[j] = ne; + if !queued[j] { + queued[j] = true; + work.push(j); + } + } + } + } + } + for &j in &succ[i] { + let ns = sin[j].join(o); + if ns != sin[j] { + sin[j] = ns; + if !queued[j] { + queued[j] = true; + work.push(j); + } + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::rdna2::encode; + + const V: u64 = 256; + type I = (&'static str, &'static str, Vec<(&'static str, u64)>); + + /// The form of every compare in `prog` (wave64; `S_ENDPGM` appended), in order. + fn forms_of(prog: &[I]) -> Vec> { + let mut code: Vec = prog.iter().flat_map(|(n, e, f)| encode(n, e, f, None).unwrap_or_else(|err| panic!("{n}: {err}"))).collect(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut insts = Vec::new(); + let mut off = 0; + while off < code.len() { + let d = rdna2::decode(&code[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + let f = forms(&insts); + insts.iter().filter(|d| is_site(d)).map(|d| f.get(&d.pc).copied()).collect() + } + fn sop1(n: &'static str, d: u64, s: u64) -> I { + (n, "ENC_SOP1", vec![("SDST", d), ("SSRC0", s)]) + } + fn sop2(n: &'static str, d: u64, a: u64, b: u64) -> I { + (n, "ENC_SOP2", vec![("SDST", d), ("SSRC0", a), ("SSRC1", b)]) + } + fn cmp(src1: u64) -> I { + ("V_CMP_LT_F32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", src1)]) + } + fn dpp(dst: u64, src: u64) -> I { + ("V_MOV_B32", "VOP1_VOP_DPP16", vec![("VDST", dst), ("SRC0", 0xFA), ("VSRC0", src), ("DPP_CTRL", 0xB1), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]) + } + fn branch(n: &'static str, words: u64) -> I { + (n, "ENC_SOPP", vec![("SIMM16", words)]) + } + + #[test] + fn masks_read_lane_by_lane_or_restored_before_derivatives_take_the_cheap_forms() { + let wqm = sop1("S_WQM_B64", 126, 126); + // v_cndmask alone reads it: the own bit + assert_eq!(forms_of(&[wqm.clone(), cmp(2), ("V_CNDMASK_B32", "ENC_VOP2", vec![("VDST", 4), ("SRC0", 128), ("VSRC1", 2)])]), [Some(Form::Own)]); + // EXEC from it, restored before the DPP derivative: the local form + let save = sop1("S_AND_SAVEEXEC_B64", 22, 106); + let mov = ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", V + 3)]); + let restore = sop1("S_MOV_B64", 126, 22); + assert_eq!(forms_of(&[wqm.clone(), cmp(3), save.clone(), mov.clone(), restore.clone(), dpp(8, 7)]), [Some(Form::Local)]); + // the DPP under that EXEC reads the source lane's bit of the reader's copy: kept + assert_eq!(forms_of(&[wqm.clone(), cmp(3), save, mov, dpp(8, 7), restore]), [None]); + // scalar operands: cond ? EXEC : 0 + let ucmp = ("V_CMP_LT_F32", "ENC_VOP3", vec![("VDST", 106), ("SRC0", 4), ("SRC1", 128)]); + assert_eq!(forms_of(&[wqm, ucmp, sop1("S_AND_SAVEEXEC_B64", 22, 106), dpp(8, 7)]), [Some(Form::Uniform)]); + } + + #[test] + fn masks_read_across_lanes_keep_the_quad_form() { + let wqm = sop1("S_WQM_B64", 126, 126); + // s_cbranch_vccz: a helper lane's bit alone sends the live lanes into the block + assert_eq!(forms_of(&[wqm.clone(), cmp(2), sop2("S_AND_B64", 106, 126, 106), branch("S_CBRANCH_VCCZ", 1), ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", 128)])]), [None]); + // waterfall loop: v_readfirstlane picks the first lane of an EXEC that carries the mask + let body: Vec = vec![ + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 4), ("SRC0", V + 2)]), + ("V_CMP_EQ_F32", "ENC_VOPC", vec![("SRC0", 4), ("VSRC1", 2)]), + sop1("S_AND_SAVEEXEC_B64", 26, 106), + sop2("S_XOR_B64", 126, 26, 126), + ]; + let mut prog = vec![wqm, sop1("S_MOV_B64", 24, 126)]; + prog.extend(body); + prog.push(branch("S_CBRANCH_EXECNZ", (-5i64) as u16 as u64)); + prog.push(sop1("S_MOV_B64", 126, 24)); + assert_eq!(forms_of(&prog), [None]); + } + + #[test] + fn a_kill_mask_of_live_lanes_stays_exact() { + // s20 = the entry EXEC (live lanes only); a v_cmpx kill clears its lanes from it, and + // the branch on SCC (any pixel left) sees no helper bit: the local form is enough + let prog: Vec = vec![ + sop1("S_MOV_B64", 20, 126), + sop1("S_WQM_B64", 126, 126), + ("V_CMPX_LT_F32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 2)]), + sop2("S_ANDN2_B64", 20, 20, 126), + branch("S_CBRANCH_SCC0", 2), + sop1("S_WQM_B64", 2, 20), + sop2("S_AND_B64", 126, 126, 2), + ]; + assert_eq!(forms_of(&prog), [Some(Form::Local)]); + } + + #[test] + fn vop3_sdst_and_literal_encodings_are_recognized() { + // VOP3_SDST_ENC: V_ADD_CO_CI_U32 and V_SUB_CO_CI_U32 read carry-in from SRC2, not VCC. + for (op, src2) in [("V_ADD_CO_CI_U32", 20u64), ("V_SUB_CO_CI_U32", 22u64)] { + let bytes = rdna2::encode( + op, + "VOP3_SDST_ENC", + &[("VDST", 1), ("SDST", 106), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", src2)], + None, + ) + .unwrap(); + let inst = rdna2::decode(&bytes, 0).unwrap(); + assert_eq!(inst.enc.name, "VOP3_SDST_ENC"); + assert_eq!(per_lane(&inst), regs(src2, 2)); + } + + // Scalar-vs-literal VOP3 compare is recognized as Form::Uniform. + let mut bytes = Vec::new(); + bytes.extend(rdna2::encode("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None).unwrap()); + let cmp_pc = bytes.len() as u64; + bytes.extend( + rdna2::encode( + "V_CMP_LT_F32", + "ENC_VOP3", + &[("VDST", 106), ("SRC0", 4), ("SRC1", 255)], + Some(0x3F80_0000), + ) + .unwrap(), + ); + bytes.extend(rdna2::encode("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 106)], None).unwrap()); + bytes.extend(rdna2::encode("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 3)], None).unwrap()); + bytes.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + let mut insts = Vec::new(); + let mut off = 0; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + assert_eq!(forms(&insts).get(&cmp_pc), Some(&Form::Uniform)); + } +} diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 70e0bcc5ee..a9890986f8 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -82,7 +82,10 @@ pub fn fspx(blob: &[u8]) -> Option> { pub fn mem_windows() -> u32 { let title = TITLE_WINDOWS.load(std::sync::atomic::Ordering::Relaxed); if title != 0 { - return windows_for(title & !super::HEAP_WINDOWS, title & super::HEAP_WINDOWS != 0 && !SWITCH_FORM.with(|s| s.get())); + return windows_for( + title & !(super::HEAP_WINDOWS | super::HEAP_FLAT), + title & super::HEAP_WINDOWS != 0 && !SWITCH_FORM.with(|s| s.get()), + ); } let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); windows_for(n, heap_windows() && !SWITCH_FORM.with(|s| s.get())) @@ -103,12 +106,19 @@ pub fn set_title_windows(windows: u32) { /// not be made, or a pipeline the driver refused with them, lost every shader on HLSL). fn windows_for(n: u32, heap: bool) -> u32 { if n > 1 && heap { - n | super::HEAP_WINDOWS + n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 } } else { n.min(crate::gpu::uma::MAX_WINDOWS as u32) } } +/// `XCL_HEAP_FLAT` (default on with heap windows; `=0` to disable): the direct DXIL translator +/// reads heap windows without a branch per access (`HEAP_FLAT`). +pub fn heap_flat() -> bool { + static ENV: OnceLock = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").map_or(true, |v| v.trim() != "0")) +} + thread_local! { /// this thread translates in the switch form (`in_switch_form`) static SWITCH_FORM: std::cell::Cell = const { std::cell::Cell::new(false) }; @@ -293,6 +303,14 @@ mod translated { let id = if Backend::current() != Backend::Hlsl { identity_for(&id.to_string(), &format!("dispatch-split-{}", crate::gpu::dxil::kernel::dispatch_piece_limit())) } else { id }; + // `XCL_RT_GATE=miss`: ray-tracing programs are another output + let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::rt_all_miss() { + identity_for(&id.to_string(), "xcl-rt-all-miss") + } else { id }; + // `XCL_NAN_GUARD=0`: disabling PS float NaN/Inf sanitization changes pixel DXIL + let id = if Backend::current() != Backend::Hlsl && !crate::gpu::dxil::kernel::nan_guard_enabled() { + identity_for(&id.to_string(), "xcl-nan-guard-0") + } else { id }; // `XCL_X_LDS_ORDER=0`: the split wave64 form without its LDS order, in both translators let id = if crate::gpu::recomp::emit::lds_order_wanted() { id } else { identity_for(&id.to_string(), "xcl-x-lds-order-0") }; // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity @@ -1544,15 +1562,17 @@ mod shader_cache_tests { #[test] fn the_switch_form_never_asks_for_more_windows_than_root_uavs() { let heap = super::super::HEAP_WINDOWS; + let flat = if heap_flat() { super::super::HEAP_FLAT } else { 0 }; + let flags = super::super::HEAP_WINDOWS | super::super::HEAP_FLAT; assert_eq!(windows_for(16, false), 4); assert_eq!(windows_for(8, false), 4); - assert_eq!(windows_for(16, true), 16 | heap); - assert_eq!((windows_for(4, false), windows_for(4, true)), (4, 4 | heap)); + assert_eq!(windows_for(16, true), 16 | heap | flat); + assert_eq!((windows_for(4, false), windows_for(4, true)), (4, 4 | heap | flat)); assert_eq!((windows_for(1, false), windows_for(1, true)), (1, 1)); for n in [1u32, 2, 4, 8, 16] { for h in [false, true] { let w = windows_for(n, h); - assert!(super::super::valid_window_count((w & !heap) as usize, w & heap != 0), "{n} windows, heap {h}: {w:#x}"); + assert!(super::super::valid_window_count((w & !flags) as usize, w & heap != 0), "{n} windows, heap {h}: {w:#x}"); } } } diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index ce0c1527ed..b602ccc065 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -158,7 +158,23 @@ impl TexDim { } } -/// A texture for kernel tests: SRV at heap index 2·i, UAV (if `uav`) at 2·i + 1. +/// The typeless depth-stencil format of a stencil view format (None: not a stencil view). +fn stencil_resource(view: DXGI_FORMAT) -> Option { + match view { + DXGI_FORMAT_X24_TYPELESS_G8_UINT => Some(DXGI_FORMAT_R24G8_TYPELESS), + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT => Some(DXGI_FORMAT_R32G8X24_TYPELESS), + _ => None, + } +} + +/// The plane a test texture's data and SRV are in: 1 for a stencil view. +fn first_plane(t: &TestTexture) -> u32 { + u32::from(stencil_resource(t.format).is_some()) +} + +/// A texture for kernel tests: SRV at heap index 2·i, UAV (if `uav`) at 2·i + 1. A D2 texture in +/// a stencil view format (X24_TYPELESS_G8_UINT, X32_TYPELESS_G8X24_UINT) is a depth-stencil +/// buffer whose stencil plane holds `data` (one byte a texel); its SRV is that view of plane 1. pub struct TestTexture { pub dim: TexDim, pub format: DXGI_FORMAT, @@ -274,15 +290,21 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t Height: t.height, DepthOrArraySize: depth_or_array as u16, MipLevels: 1, - Format: t.format, + Format: stencil_resource(t.format).unwrap_or(t.format), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Flags: if t.uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + Flags: if t.uav { + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + } else if stencil_resource(t.format).is_some() { + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL + } else { + D3D12_RESOURCE_FLAG_NONE + }, ..Default::default() } }; let subs = if t.dim == TexDim::D3 { 1 } else { t.depth }; let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); subs as usize]; let mut size = 0u64; - dev.GetCopyableFootprints(&rd, 0, subs, total, Some(fps.as_mut_ptr()), None, None, Some(&mut size)); + dev.GetCopyableFootprints(&rd, first_plane(t), subs, total, Some(fps.as_mut_ptr()), None, None, Some(&mut size)); total = (total + size + 511) & !511; plans.push(fps); descs.push(rd); @@ -340,7 +362,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t list.CopyBufferRegion(&r, 0, upload.as_ref().unwrap(), fps[0].Offset, rd.Width); } for (k, fp) in fps.iter().enumerate().filter(|_| t.dim != TexDim::Buffer) { - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: first_plane(t) + k as u32 } }; let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(upload.as_ref().unwrap()), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, @@ -361,7 +383,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t } TexDim::D2 => { sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - sv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }; + sv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 1, PlaneSlice: first_plane(t), ..Default::default() }; uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; } TexDim::D2Array => { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 5573d7ea39..77fef9258a 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1845,7 +1845,7 @@ fn gpu_wave32_pixel_carry_preserves_adjacent_mask_at_triangle_edges() { ]; let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let ps = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 15)], - outputs: vec![el("SV_Target", 0, 64, 3, 0, 15)], input_ena: 0x300, attrs: None }; + outputs: vec![el("SV_Target", 0, 64, 3, 0, 15)], input_ena: 0x300, attrs: None, early_depth: false }; let t = translate(&code, &Options { wave64: false, mode: Mode::Pixel(ps), ..Default::default() }).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let ps = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap(); @@ -1900,6 +1900,7 @@ fn gpu_graphics_vs_ps_draw() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let (vo, po) = (Options { mode: Mode::Vertex(vsi), wave64: true, ..Default::default() }, Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }); let vt = translate(&vs_code, &vo).unwrap(); @@ -1984,6 +1985,7 @@ fn ps_exp_vm_hlsl_and_direct_dxil_codegen() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let po = Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }; for (name, ps_code, has_vm) in ps_exp_vm_cases() { @@ -2033,6 +2035,7 @@ fn gpu_ps_exp_vm_controls_pixel_survival() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let vo = Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }; let po = Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }; @@ -2218,6 +2221,7 @@ fn gpu_rect_list_corners() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let outputs = vsi.outputs.clone(); let vt = translate(&vs_code, &Options { mode: Mode::Vertex(vsi), wave64: true, ..Default::default() }).unwrap(); @@ -2288,6 +2292,7 @@ fn draw_psi() -> super::PsInterface { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, } } @@ -2801,7 +2806,7 @@ fn helper_lane_masks_ps(wave64: bool) -> super::Translation { ps_code.extend(encode("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", back)], None).unwrap()); ps_code.extend(enc(&tail)); ps_code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); - let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; translate(&ps_code, &Options { mode: Mode::Pixel(psi), wave64, ..Default::default() }).unwrap() } } @@ -3413,6 +3418,69 @@ fn global_dword_addtid_address_is_saddr_plus_4_per_lane() { } } +/// scratch_* (ENC_FLAT_SCRATCH) has three address forms on RDNA2 and no SGPR + VGPR one: +/// SADDR 0x7F (EXEC_HI) is ST, the offset alone; NULL (0x7D) is SV, VADDR + offset; an SGPR +/// is SS, SGPR + offset. ADDR is read only in the SV form. +#[test] +fn scratch_address_forms_follow_saddr() { + let scr = |n: &'static str, f: &[(&str, u64)]| encode(n, "ENC_FLAT_SCRATCH", f, None).unwrap(); + let mut code = Vec::new(); + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 5), ("SADDR", 0x7F), ("OFFSET", 16)])); + code.extend(scr("SCRATCH_LOAD_DWORD", &[("VDST", 7), ("ADDR", 2), ("SADDR", 0x7D), ("OFFSET", 0xFFC)])); + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 5), ("SADDR", 4), ("OFFSET", 8)])); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let t = translate(&code, &Options::default()).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + assert!(t.hlsl.contains("uint t1_a = 0u + 0x00000010u;"), "ST: the offset alone\n{}", t.hlsl); + assert!(t.hlsl.contains("uint t2_a = v2 + 0xFFFFFFFCu;"), "SV: VADDR + the signed offset\n{}", t.hlsl); + assert!(t.hlsl.contains("uint t3_a = s4 + 0x00000008u;"), "SS: the SGPR + offset\n{}", t.hlsl); + if super::dxc::location().is_ok() { + super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); + } +} + +/// On hardware: the ST scratch form addresses the offset alone whatever ADDR holds, SS the +/// SGPR + offset, and SV the lane's VADDR + offset. +#[test] +fn gpu_scratch_address_forms() { + if !gpu_ready() { + return; + } + let scr = |n: &'static str, f: &[(&str, u64)]| encode(n, "ENC_FLAT_SCRATCH", f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut code = Vec::new(); + // [16] = 0x55 (SV, v3 = 0), then ST writes [16] (ADDR = v2 is not read), SV reads it back + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 3), ("DATA", 9), ("SADDR", 0x7D), ("OFFSET", 16)])); + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 5), ("SADDR", 0x7F), ("OFFSET", 16)])); + code.extend(scr("SCRATCH_LOAD_DWORD", &[("VDST", 20), ("ADDR", 3), ("SADDR", 0x7D), ("OFFSET", 16)])); + // SS: s4 (8) + 32 = [40], read back through SV + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 6), ("SADDR", 4), ("OFFSET", 32)])); + code.extend(scr("SCRATCH_LOAD_DWORD", &[("VDST", 21), ("ADDR", 3), ("SADDR", 0x7D), ("OFFSET", 40)])); + // [0x100] = 0x55 (ST), SV writes [0x100 + v2], ST reads [0x100]: lanes with v2 = 0 see the SV store + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 9), ("SADDR", 0x7F), ("OFFSET", 0x100)])); + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 7), ("SADDR", 0x7D), ("OFFSET", 0x100)])); + code.extend(scr("SCRATCH_LOAD_DWORD", &[("VDST", 22), ("ADDR", 2), ("SADDR", 0x7F), ("OFFSET", 0x100)])); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[4] = 8; + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l32 = l as u32; + r[2] = 4 * (l32 % 4); + r[3] = 0; + r[5] = 0xA0 + l32; + r[6] = 0xB0 + l32; + r[7] = 0xC0 + l32; + r[9] = 0x55; + } + let r = runner::run_code(&code, &st, &[0u32; 16]).unwrap(); + for (l, v) in r.vgpr.iter().enumerate().take(64) { + let l32 = l as u32; + assert_eq!(v[20], 0xA0 + l32, "lane {l}: ST store at the offset alone"); + assert_eq!(v[21], 0xB0 + l32, "lane {l}: SS store at s4 + offset"); + assert_eq!(v[22], if l % 4 == 0 { 0xC0 + l32 } else { 0x55 }, "lane {l}: SV store at v2 + offset, ST load at the offset"); + } +} + /// On hardware: every lane touches its own dword (EA = SADDR + 4·lane + OFFSET), the /// "off" SADDR sentinel gives a zero base and the signed offset can point below the base. #[test] @@ -3679,7 +3747,7 @@ fn gpu_mesh_mode_two_passes() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0), sig("TEXCOORD", 0, 1)], threads: 128, max_vertices: 128, max_primitives: 128 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0), sig("TEXCOORD", 0, 1)], threads: 128, max_vertices: 128, max_primitives: 128, params: None }; let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) }; @@ -3779,7 +3847,7 @@ fn gpu_mesh_mode_exports_stay_inside_the_record() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 128, max_vertices: 64, max_primitives: 32 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 128, max_vertices: 64, max_primitives: 32, params: None }; let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) }; @@ -3858,6 +3926,7 @@ fn mesh_passthrough_strips_rdna2_edge_flag_bits() { threads: 128, max_vertices: 128, max_primitives: 128, + params: None, }; let unsplit = mesh_passthrough(&ms); assert!(unsplit.contains("uint3(p & 0x1FFu, (p >> 10) & 0x1FFu, (p >> 20) & 0x1FFu)"), "{unsplit}"); @@ -3899,7 +3968,7 @@ fn mesh_split_accounts_vertex_chunks() { outputs.push(sig("TEXCOORD", 0, k + 1, k)); } outputs.push(sig("SV_ClipDistance", 2, 21, 0)); - let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128 }; + let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128, params: None }; let elems = passthrough_elements(&ms, None); assert_eq!(elems, 21); // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit (96 would be 33792 B), so at @@ -3956,7 +4025,7 @@ fn mesh_layout_independent_of_group_count() { } outputs.push(sig("SV_ClipDistance", 2, 21, 0)); // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit; 80 declared do not - let ms = MsInterface { outputs, threads: 128, max_vertices: 80, max_primitives: 1 }; + let ms = MsInterface { outputs, threads: 128, max_vertices: 80, max_primitives: 1, params: None }; let elems = passthrough_elements(&ms, None); assert_eq!(elems, 21); // one triangle: its 3 copies fit one compact group, so the dispatch count is 1 @@ -4212,7 +4281,7 @@ fn gpu_mesh_mode_reads_memory_windows() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 64, max_primitives: 64 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 64, max_primitives: 64, params: None }; let list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", V)], None), // thread @@ -5981,10 +6050,10 @@ fn gpu_more_atomics_sub_dword_scratch_valu() { code.extend(glbl("GLOBAL_STORE_SHORT_D16_HI", &[("ADDR", 2), ("DATA", 62), ("SADDR", 2), ("OFFSET", 0x100)])); code.extend(glbl("GLOBAL_LOAD_USHORT", &[("VDST", 63), ("ADDR", 2), ("SADDR", 2), ("OFFSET", 0x100)])); // scratch (per lane): a dword at 2 · lane + 16, a byte at 2 · lane + 40 - code.extend(enc("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 11), ("SADDR", 0x7F), ("OFFSET", 16)])); - code.extend(enc("SCRATCH_STORE_BYTE", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 36), ("SADDR", 0x7F), ("OFFSET", 40)])); - code.extend(enc("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 64), ("ADDR", 2), ("SADDR", 0x7F), ("OFFSET", 16)])); - code.extend(enc("SCRATCH_LOAD_UBYTE", "ENC_FLAT_SCRATCH", &[("VDST", 65), ("ADDR", 2), ("SADDR", 0x7F), ("OFFSET", 40)])); + code.extend(enc("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 11), ("SADDR", 0x7D), ("OFFSET", 16)])); + code.extend(enc("SCRATCH_STORE_BYTE", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 36), ("SADDR", 0x7D), ("OFFSET", 40)])); + code.extend(enc("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 64), ("ADDR", 2), ("SADDR", 0x7D), ("OFFSET", 16)])); + code.extend(enc("SCRATCH_LOAD_UBYTE", "ENC_FLAT_SCRATCH", &[("VDST", 65), ("ADDR", 2), ("SADDR", 0x7D), ("OFFSET", 40)])); // VALU let vv = |n: u64| V + n; code.extend(vop3("V_SAD_U8", &[("VDST", 66), ("SRC0", vv(22)), ("SRC1", vv(23)), ("SRC2", vv(24))])); @@ -6829,7 +6898,7 @@ fn isa_coverage() { let Ok(mut code) = encode(inst.name, enc, fields, lit) else { continue }; code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let ok = std::panic::catch_unwind(|| { - try_mode(&code, Mode::Kernel) || try_mode(&code, Mode::Pixel(super::PsInterface { inputs: vec![], outputs: vec![], input_ena: 0x7F, attrs: None })) + try_mode(&code, Mode::Kernel) || try_mode(&code, Mode::Pixel(super::PsInterface { inputs: vec![], outputs: vec![], input_ena: 0x7F, attrs: None, early_depth: false })) }) .unwrap_or(false); let e = per_enc.entry(enc.trim_start_matches("ENC_")).or_default(); @@ -7235,7 +7304,7 @@ fn far_jumps_are_direct_branches() { /// programs with cross-half operations included; native wave64 and wave32 programs unchanged. #[test] fn mesh_split_wave64_form() { - let ms = super::MsInterface { threads: 128, max_vertices: 64, max_primitives: 64, outputs: vec![] }; + let ms = super::MsInterface { threads: 128, max_vertices: 64, max_primitives: 64, outputs: vec![], params: None }; let lane = prog(&[("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)], None)]); let branch = prog(&[("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)], None)]); for code in [&lane, &branch] { @@ -9239,7 +9308,7 @@ fn ps_mrtz_sample_mask_writes_sv_coverage() { ("EXP", "ENC_EXP", mrtz, None), ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1), ("VM", 1)], None), ]); - let psi = PsInterface { inputs: vec![], outputs, input_ena: 0x2, attrs: None }; + let psi = PsInterface { inputs: vec![], outputs, input_ena: 0x2, attrs: None, early_depth: false }; let pt = translate(&code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); if super::dxc::location().is_ok() { @@ -9291,6 +9360,7 @@ fn ps_interp_p0_preserves_bits_and_p2_converts_to_float() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let pt = translate(&ps_code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); @@ -10933,7 +11003,7 @@ fn list_loop_ps() -> super::Translation { code.extend(ins("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", back)], None)); code.extend(tail); code.extend(ins("S_ENDPGM", "ENC_SOPP", &[], None)); - let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; translate(&code, &Options { mode: Mode::Pixel(psi), wave64: false, ..Default::default() }).unwrap() } @@ -11014,7 +11084,7 @@ fn mask_loop_ps() -> super::Translation { ] .concat(), ); - let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; translate(&code, &Options { mode: Mode::Pixel(psi), wave64: false, ..Default::default() }).unwrap() } diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index 132625dc20..bd523b7a86 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -109,6 +109,7 @@ struct DynOp { n: u8, is_write: bool, is_src0: bool, + is_per_lane_mask: bool, } impl DynOp { @@ -118,6 +119,7 @@ impl DynOp { n: 1, is_write: false, is_src0: false, + is_per_lane_mask: false, }; } @@ -199,9 +201,6 @@ impl UsePlanTable { { continue; } - if !o.output && per_lane && f == "SRC2" { - continue; - } let idx = plan.op_len as usize; if idx < MAX_DYN_OPS && n <= u8::MAX as u64 { plan.ops[idx] = DynOp { @@ -210,6 +209,7 @@ impl UsePlanTable { n: n as u8, is_write: o.output && !keeps, is_src0: f == "SRC0", + is_per_lane_mask: !o.output && per_lane && f == "SRC2", }; plan.op_len += 1; } else { @@ -271,8 +271,9 @@ fn use_plans() -> &'static UsePlanTable { fn uses_fallback(d: &Decoded) -> (Regs, Regs) { let name = d.inst.name; if name.starts_with("S_MOVREL") { - let src = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0).min(124); - return (range(src, 124 - src) | M0 | EXEC, 0); + let raw = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0); + let src = raw.min(124); + return (range(src, 124 - src) | scalar_code(raw, 1) | M0 | EXEC, 0); } let (mut whole, mut written) = (0 as Regs, 0 as Regs); let per_lane = reads_mask_per_lane(name); @@ -293,10 +294,10 @@ fn uses_fallback(d: &Decoded) -> (Regs, Regs) { } for o in d.ienc.operands { let n = (o.size as u64).div_ceil(32).max(1); - let regs = match (o.field, o.ty) { - (_, "OPR_VCC") => VCC, - (_, "OPR_EXEC" | "OPR_SDST_EXEC") => EXEC, - (_, "OPR_SDST_M0") => M0, + let (regs, code) = match (o.field, o.ty) { + (_, "OPR_VCC") => (VCC, None), + (_, "OPR_EXEC" | "OPR_SDST_EXEC") => (EXEC, None), + (_, "OPR_SDST_M0") => (M0, None), (None, _) | (Some("LITERAL"), _) => continue, (Some(f), ty) => { if o.implicit || !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"].iter().any(|k| ty.contains(k)) { @@ -305,7 +306,8 @@ fn uses_fallback(d: &Decoded) -> (Regs, Regs) { if f == "SRC0" && d.variant != Variant::Plain { continue; } - scalar_code(rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f), n) + let code = rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); + (scalar_code(code, n), Some(code)) } }; if o.output { @@ -314,7 +316,11 @@ fn uses_fallback(d: &Decoded) -> (Regs, Regs) { } else { written |= regs; } - } else if !(per_lane && (o.ty == "OPR_VCC" || o.field == Some("SRC2"))) { + } else if per_lane && o.field == Some("SRC2") { + if matches!(code, Some(251 | 252)) { + whole |= regs; + } + } else if !(per_lane && o.ty == "OPR_VCC") { whole |= regs; } } @@ -335,8 +341,9 @@ fn uses_with_table(d: &Decoded, table: &UsePlanTable) -> (Regs, Regs) { // `smovrel`: s[src + m0] is read, s[dst + m0] written (s_movrelsd_2: both) – any // register from the encoded one up to s123, VCC included; nothing for certain // overwritten - let src = extract_ranges(&d.words, plan.movrel_ssrc0).min(124); - return (range(src, 124 - src) | M0 | EXEC, 0); + let raw = extract_ranges(&d.words, plan.movrel_ssrc0); + let src = raw.min(124); + return (range(src, 124 - src) | scalar_code(raw, 1) | M0 | EXEC, 0); } let mut whole = plan.const_whole; let mut written = plan.const_written; @@ -361,6 +368,12 @@ fn uses_with_table(d: &Decoded, table: &UsePlanTable) -> (Regs, Regs) { continue; } let code = extract_ranges(&d.words, op.ranges) * op.scale as u64; + if op.is_per_lane_mask { + if matches!(code, 251 | 252) { + whole |= scalar_code(code, op.n as u64); + } + continue; + } let regs = scalar_code(code, op.n as u64); if op.is_write { written |= regs; @@ -1062,6 +1075,85 @@ mod tests { assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); } + #[test] + fn sdwa_vop2_carry_always_overwrites_vcc_even_with_omod_bit47() { + const CBRANCH_VCCZ: I = ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 0)]); + // RDNA2 VOP2 carry-out SDWA uses VOP2_VOP_SDWA ([47:40] = DST_SEL/DST_UNUSED/CLAMP/OMOD), + // never VOP2_VOP_SDWA_SDST_ENC: OMOD=2 sets bit 47, yet carry-out still overwrites VCC. + for name in ["V_ADD_CO_CI_U32", "V_SUB_CO_CI_U32", "V_SUBREV_CO_CI_U32"] { + let f = [ + ("VDST", 4), ("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 1), + ("SRC0_SEL", 6), ("SRC1_SEL", 6), + ("DST_SEL", 6), ("DST_UNUSED", 2), ("CLAMP", 1), ("OMOD", 2), + ]; + let bytes: Vec = [ + rdna2::encode(CMP.0, CMP.1, CMP.2, None).unwrap(), + rdna2::encode(name, "VOP2_VOP_SDWA", &f, None).unwrap(), + rdna2::encode(CBRANCH_VCCZ.0, CBRANCH_VCCZ.1, CBRANCH_VCCZ.2, None).unwrap(), + rdna2::encode(ENDPGM.0, ENDPGM.1, ENDPGM.2, None).unwrap(), + ] + .concat(); + let p = program(&bytes); + assert_eq!(uses(&p[1]), uses_fallback(&p[1])); + assert_eq!(uses(&p[1]).1, VCC, "{name} VOP2_VOP_SDWA OMOD=2 must overwrite only VCC"); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106) && mask_needed(&live, 1, 106), "{name} kills prior VCC"); + } + } + + #[test] + fn s_movreld_with_src_vccz_marks_vcc_whole_live() { + for name in ["S_MOVRELD_B32", "S_MOVRELD_B64"] { + let p = asm(&[CMP, (name, "ENC_SOP1", &[("SDST", 2), ("SSRC0", 251)]), ENDPGM]); + assert_eq!(uses(&p[1]), uses_fallback(&p[1])); + assert_eq!(uses(&p[1]).0 & VCC, VCC, "{name} SSRC0=251 must read whole VCC"); + assert_eq!(uses(&p[1]).1, 0, "{name} must not kill destination"); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "{name} SSRC0=251 keeps VCC live"); + let execz = asm(&[(name, "ENC_SOP1", &[("SDST", 2), ("SSRC0", 252)]), ENDPGM]); + assert_eq!(uses(&execz[0]), uses_fallback(&execz[0])); + assert_eq!(uses(&execz[0]).0, M0 | EXEC, "{name} SSRC0=252 reads M0 | EXEC"); + let m0_src = asm(&[(name, "ENC_SOP1", &[("SDST", 2), ("SSRC0", 124)]), ENDPGM]); + assert_eq!(uses(&m0_src[0]).0, M0 | EXEC, "{name} SSRC0=124 sets no spurious bit 125"); + } + } + + #[test] + fn vop3_per_lane_mask_ops_with_src_vccz_mark_vcc_whole_live() { + let cases: [(&str, &str, &[(&str, u64)]); 4] = [ + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 251)]), + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2), ("SDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 251)]), + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2), ("SDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 251)]), + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2), ("SDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 251)]), + ]; + for (name, enc, f) in cases { + let p = asm(&[CMP, (name, enc, f), ENDPGM]); + assert_eq!(uses(&p[1]), uses_fallback(&p[1])); + assert_eq!(uses(&p[1]).0 & VCC, VCC, "{name} SRC2=251 must read whole VCC"); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "{name} SRC2=251 keeps VCC live"); + } + // SRC2=106 (VCC) and SRC2=2 (s[2:3]) stay lane-local; SRC2=252 (SRC_EXECZ) marks whole EXEC. + const CMP_S2: I = ("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", V + 1)]); + for (src2, cmp, pair) in [(106, CMP, 106), (2, CMP_S2, 2)] { + for (name, enc, extra) in [ + ("V_CNDMASK_B32", "ENC_VOP3", None), + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", Some(("SDST", 4))), + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", Some(("SDST", 4))), + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", Some(("SDST", 4))), + ] { + let mut f = vec![("VDST", 2), ("SRC0", V), ("SRC1", V + 1), ("SRC2", src2)]; + if let Some(s) = extra { f.push(s); } + let bytes: Vec = [rdna2::encode(cmp.0, cmp.1, cmp.2, None).unwrap(), rdna2::encode(name, enc, &f, None).unwrap(), rdna2::encode(ENDPGM.0, ENDPGM.1, ENDPGM.2, None).unwrap()].concat(); + let p = program(&bytes); + assert_eq!(uses(&p[1]), uses_fallback(&p[1])); + assert_eq!(uses(&p[1]).0 & range(pair, 2), 0, "{name} SRC2={src2} stays lane-local"); + assert!(!mask_needed(&whole_live_out(&p, false), 0, pair), "{name} SRC2={src2} needs no exchange"); + } + } + let execz = asm(&[("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 252)]), ENDPGM]); + assert_eq!(uses(&execz[0]), uses_fallback(&execz[0])); + assert_eq!(uses(&execz[0]).0 & EXEC, EXEC, "V_CNDMASK_B32 SRC2=252 must read whole EXEC"); + } + /// Reference instruction-level solver matching the original implementation verbatim. fn whole_live_out_reference(insts: &[Decoded], end_reads_all: bool) -> Vec { let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); @@ -1198,6 +1290,16 @@ mod tests { }; assert_eq!(uses(&d), uses_fallback(&d), "{} ({}, {variant:?})", inst.name, enc.name); } + if matches!(enc.name, "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC") { + for bits in 0u32..8 { + let ext = (next_u32() & !((1 << 15) | (1 << 23) | (1 << 31))) + | ((bits & 1) << 15) + | (((bits >> 1) & 1) << 23) + | (((bits >> 2) & 1) << 31); + let d = Decoded { pc: 0, inst, ienc, enc, words: vec![next_u32(), ext], len: 8, literal: None, variant: Variant::Sdwa, far_target: None }; + assert_eq!(uses(&d), uses_fallback(&d), "{} ({}, Sdwa bits={bits})", inst.name, enc.name); + } + } } } } diff --git a/crates/xcl/src/gpu/rt_leave_out.rs b/crates/xcl/src/gpu/rt_leave_out.rs new file mode 100644 index 0000000000..762acb7114 --- /dev/null +++ b/crates/xcl/src/gpu/rt_leave_out.rs @@ -0,0 +1,183 @@ +//! `XCL_RT_LEAVE_OUT=[,…]` (off by default): compute programs whose shader +//! container holds one of the fragments are left out – the title's pipeline gets the dummy +//! compute program a console shader that cannot be translated gets, so its dispatches are +//! skipped, and the shader preparation and `xcl shaders --precompile` pass them over. +//! +//! What it is for: a title's ray-tracing programs that shade the hits of rays or start rays +//! (on a retail title about 1,000 programs, ~1 MB of DXIL each, the largest of its cold driver +//! compiles) do nothing while the title has built no acceleration structure: every ray misses. +//! The fragments name those programs (a name in the container's debug data; find it with +//! `xcl rpf --find`); XCL's source names no title's programs. +//! +//! So that leaving them out stays harmless, XCL watches the acceleration structures the +//! title's views name (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE` in unified +//! memory) and warns once when one of them gets a root node: from then on rays can hit, and +//! the programs left out would have shaded those hits. +//! +//! Ported from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later), commit +//! `1f69d67`, `crates/victory-gpu/src/pipeline/make.rs` (`left_out`: `VICTORY_RT_RESOLVE`, +//! `VICTORY_ACTIVATE_RAYS`, `VICTORY_BVH_BUILDER`; there since codec_d's `8cc31ab`). +//! Changes (2026-11-27): the programs are named by the user's fragments instead of names in +//! the source; one switch; the structure watch and its warning are new; the preparation and +//! the precompile pass the programs over. + +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +/// Fragments shorter than this are refused: they would match bytes of any container. +const SHORTEST: usize = 6; +/// Acceleration structures remembered for the watch (distinct addresses). +const MOST_STRUCTURES: usize = 4096; + +/// The fragments of a `XCL_RT_LEAVE_OUT` value: comma-separated, trimmed, at least +/// [`SHORTEST`] bytes each (shorter ones are dropped). +pub fn fragments_of(value: &str) -> Vec> { + value.split(',').map(str::trim).filter(|f| f.len() >= SHORTEST).map(|f| f.as_bytes().to_vec()).collect() +} + +/// Whether `container` holds one of `fragments`. +pub fn holds_any(container: &[u8], fragments: &[Vec]) -> bool { + fragments.iter().any(|f| container.windows(f.len()).any(|w| w == f.as_slice())) +} + +fn fragments() -> &'static [Vec] { + static F: OnceLock>> = OnceLock::new(); + F.get_or_init(|| { + let Ok(v) = std::env::var("XCL_RT_LEAVE_OUT") else { return Vec::new() }; + let f = fragments_of(&v); + let dropped = v.split(',').map(str::trim).filter(|s| !s.is_empty() && s.len() < SHORTEST).count(); + if f.is_empty() { + crate::xlog_warn!("XCL_RT_LEAVE_OUT: no fragment of at least {SHORTEST} bytes – nothing is left out"); + } else { + crate::xlog_info!( + "XCL_RT_LEAVE_OUT: compute programs holding one of {} fragment(s) are left out while rays cannot hit{}", + f.len(), + if dropped > 0 { format!(" ({dropped} shorter than {SHORTEST} bytes ignored)") } else { String::new() } + ); + } + f + }) +} + +/// Whether the switch is on (at least one usable fragment). +pub fn enabled() -> bool { + !fragments().is_empty() +} + +static LEFT_OUT: AtomicU64 = AtomicU64::new(0); + +/// Whether the compute program in `container` is left out; counts and logs the first few. +pub fn left_out(container: &[u8]) -> bool { + if !enabled() || !holds_any(container, fragments()) { + return false; + } + let n = LEFT_OUT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 3 || n.is_power_of_two() { + crate::xlog_info!( + "XCL_RT_LEAVE_OUT: compute program of record {:016x} left out (#{n}): its dispatches are skipped", + crate::gpu::shader::fnv64(container) + ); + } + true +} + +/// How many compute programs were left out so far. +pub fn left_out_count() -> u64 { + LEFT_OUT.load(Ordering::Relaxed) +} + +static STRUCTURES: Mutex> = Mutex::new(BTreeSet::new()); + +/// An acceleration structure in unified memory that a title's view names (only kept while the +/// switch is on). +pub fn note_structure(va: u64) { + if enabled() { + let mut s = STRUCTURES.lock().unwrap(); + if s.len() < MOST_STRUCTURES { + s.insert(va); + } + } +} + +/// The root node id in an acceleration structure's header: `None` while it has none (0 or +/// all ones, as before a build). +pub fn root_of(header: &[u8]) -> Option { + let at = crate::gpu::bvh::ROOT_AT; + let root = u32::from_le_bytes(header.get(at..at + 4)?.try_into().ok()?); + (root != 0 && root != u32::MAX).then_some(root) +} + +/// Looks at the structures views named (called every few hundred frames): warns once when one +/// has a root node, since the programs left out would then have hits to shade. +pub fn check_structures() { + static WARNED: AtomicBool = AtomicBool::new(false); + if !enabled() || WARNED.load(Ordering::Relaxed) { + return; + } + let all: Vec = STRUCTURES.lock().unwrap().iter().copied().collect(); + let header = crate::gpu::bvh::HEADER_BYTES; + for va in all { + let p = va as usize; + if !crate::gpu::shader::readable(p, header) { + continue; + } + // SAFETY: `readable` just checked the range; title memory, only read + let bytes = unsafe { std::slice::from_raw_parts(p as *const u8, header) }; + if let Some(root) = root_of(bytes) { + if !WARNED.swap(true, Ordering::Relaxed) { + crate::xlog_warn!( + "XCL_RT_LEAVE_OUT: the acceleration structure at {va:#x} has a root node ({root:#x}) now – rays can hit, and the {} compute program(s) left out would shade those hits; run without XCL_RT_LEAVE_OUT for this title", + left_out_count() + ); + } + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fragments_are_trimmed_and_short_ones_dropped() { + let f = fragments_of(" ResolveA ,abc, ,LongerName,"); + assert_eq!(f, vec![b"ResolveA".to_vec(), b"LongerName".to_vec()]); + assert!(fragments_of("").is_empty()); + assert!(fragments_of("short").is_empty()); + } + + #[test] + fn a_container_is_matched_by_any_fragment_anywhere() { + let mut container = vec![0u8; 64]; + container.extend_from_slice(b"\x00prog_Example_Name_x\x00"); + container.extend_from_slice(&[0xFF; 32]); + assert!(holds_any(&container, &fragments_of("Other_Name,Example_Name"))); + assert!(!holds_any(&container, &fragments_of("Example_Names"))); + assert!(!holds_any(&container, &[])); + // a fragment at the very end still matches + assert!(holds_any(b"xxxxEnd_of_it", &fragments_of("End_of_it"))); + } + + #[test] + fn a_header_without_a_root_has_none() { + let mut h = vec![0u8; crate::gpu::bvh::HEADER_BYTES]; + assert_eq!(root_of(&h), None); + let at = crate::gpu::bvh::ROOT_AT; + h[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(root_of(&h), None); + h[at..at + 4].copy_from_slice(&0x25u32.to_le_bytes()); + assert_eq!(root_of(&h), Some(0x25)); + assert_eq!(root_of(&h[..at]), None, "a header too short to hold the root"); + } + + #[test] + fn a_built_structure_from_the_builder_has_a_root() { + // XCL's own builder writes the console layout the watch reads + let tris = crate::gpu::bvh::tests::random_tris(8, 3); + let b = crate::gpu::bvh::build(&tris, 0); + let root = root_of(&b.data).expect("a built structure has a root id"); + assert_eq!(root, b.root); + } +} diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index f1046cd515..31e1230391 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -592,10 +592,21 @@ fn pbits(mode: u16) -> bool { matches!(mode, 0 | 1 | 3 | 6 | 7) } +/// The channel rotation of a BC7 block: only modes 4 and 5 have the 2-bit +/// field; in the other modes those control bits mean something else, and +/// reading them as a rotation swapped channels (upstream VIctory PR #3111). +fn rotation(ctrl: u16) -> usize { + if matches!(ctrl & 7, 4 | 5) { + usize::from(ctrl >> 3 & 3) + } else { + 0 + } +} + /// Channel precisions: the p-bit is red's lowest bit; rotation swaps alpha /// with the rotated channel. fn bc7_precision(ctrl: u16) -> [u8; 4] { - let (mode, rot) = (ctrl & 7, usize::from(ctrl >> 3 & 3)); + let (mode, rot) = (ctrl & 7, rotation(ctrl)); let mut p = BC7_BITS[usize::from(mode)]; if rot != 0 { p.swap(3, rot - 1); @@ -700,7 +711,7 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { let mode = ctrl & 7; let subsets = usize::from((ctrl & 0xff) >> 6); let part = usize::from(ctrl >> 8 & 63); - let rot = usize::from(ctrl >> 3 & 3); + let rot = rotation(ctrl); let mut w = Bits::default(); w.put(1 << mode, u32::from(mode) + 1); match mode { @@ -1009,3 +1020,23 @@ fn bc6<'a>( Ok(()) } +#[cfg(test)] +mod rotation_tests { + use super::*; + + #[test] + fn bc7_rotation_is_read_only_in_modes_4_and_5() { + for mode in 0u16..8 { + for rot in 0u16..4 { + let ctrl = (rot << 3) | mode; + let want = if matches!(mode, 4 | 5) { usize::from(rot) } else { 0 }; + assert_eq!(rotation(ctrl), want, "mode {mode} rot {rot}"); + let prec = bc7_precision(ctrl); + if !matches!(mode, 4 | 5) { + assert_eq!(prec, bc7_precision(mode), "non-4/5 mode {mode} must ignore rot bits {rot}"); + } + } + } + } +} + diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index e113fa9e05..cc75f07a5c 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -59,6 +59,16 @@ struct State { /// PC list → recordings so far (a Reset or creation starts the next one) recordings: HashMap, resubmits: u64, + /// Title allocators released while their submitted GPU fences are still running: held until + /// every fence completes (`release_finished`, polled at `PresentX`) so two-pass buffers, + /// UMA arenas, and dispatch-chain scratch are never freed out from under active GPU work. + pending_releases: Vec, +} + +struct PendingRelease { + marks: Vec<(ID3D12Fence, u64)>, + made: Vec, + cleanup: Box, } struct LastSubmit { @@ -283,6 +293,19 @@ pub fn in_flight(list: usize) -> bool { g.as_ref().and_then(|s| s.last_submit.get(&list)).is_some_and(|l| unsafe { super::real::fence_completed(&l.fence) } < l.value) } +/// Snapshot of every currently in-flight title-queue `(fence, value)` pair (`completed < value`). +/// Used by `vram_small` so freed sub-allocated blocks are never recycled while GPU work submitted +/// at release time is still running (even across multi-second pipeline-compile stalls that outlast `COOL`). +pub(super) fn pending_gpu_marks() -> Vec<(ID3D12Fence, u64)> { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return Vec::new() }; + s.fences + .values() + .filter(|(f, v)| *v > 0 && unsafe { super::real::fence_completed(f) } < *v) + .map(|(f, v)| (f.clone(), *v)) + .collect() +} + /// `lists` were just submitted to `queue`. pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { if !enabled() || queue.is_null() { @@ -347,6 +370,95 @@ pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { busy } +/// Like `forget`, but when `alloc` (or any of its put-aside backings) still has unfinished GPU +/// fence marks, defers running `cleanup` (and resetting/dropping any XCL-created spare PC +/// allocators) until all those fences complete (`release_finished`). Returns `true` if deferred, +/// `false` if all GPU work was already done and the caller should run cleanup immediately. +pub unsafe fn release_when_done(alloc: usize, cleanup: Box) -> bool { + let (deferred, immediate_made) = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { + return false; + }; + s.types.remove(&alloc); + let mut mine: Vec = s.aside.remove(&alloc).unwrap_or_default(); + mine.extend(s.cur.remove(&alloc)); + mine.push(alloc); + let mut seen = HashSet::with_capacity(mine.len()); + mine.retain(|b| seen.insert(*b)); + let mut pending_marks: Vec<(ID3D12Fence, u64)> = Vec::new(); + let mut made_busy: Vec = Vec::new(); + let mut made_free: Vec = Vec::new(); + for b in mine { + let mut busy = false; + if let Some(gone) = s.backings.remove(&b) { + for l in gone.users { + s.of_list.remove(&l); + } + for (_, (f, v)) in gone.marks { + if super::real::fence_completed(&f) < v { + pending_marks.push((f, v)); + busy = true; + } + } + } + if b != alloc { + if busy { + made_busy.push(b); + } else { + made_free.push(b); + } + } + } + if pending_marks.is_empty() { + (false, made_free) + } else { + s.pending_releases.push(PendingRelease { + marks: pending_marks, + made: made_busy, + cleanup, + }); + (true, made_free) + } + }; + for b in immediate_made { + super::real::dispatch_chain::allocator_reset(b); + super::console_list::allocator_reset(b as *mut c_void); + drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); + } + deferred +} + +/// Run deferred `release_when_done` cleanups whose GPU fences have all completed (polled once +/// per `PresentX`, outside `STATE` so cleanups and COM drops cannot re-enter `STATE`). +pub unsafe fn release_finished() { + let done: Vec = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if s.pending_releases.is_empty() { + return; + } + let mut ready = Vec::new(); + let mut i = 0; + while i < s.pending_releases.len() { + if s.pending_releases[i].marks.iter().all(|(f, v)| super::real::fence_completed(f) >= *v) { + ready.push(s.pending_releases.swap_remove(i)); + } else { + i += 1; + } + } + ready + }; + for item in done { + (item.cleanup)(); + for b in item.made { + super::real::dispatch_chain::allocator_reset(b); + super::console_list::allocator_reset(b as *mut c_void); + drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); + } + } +} + /// 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). @@ -418,13 +530,15 @@ unsafe fn title_reset_with(alloc: *mut c_void, reset: impl FnMut(*mut c_void) -> hr } -/// The PC allocators of the title's allocator `a` (the one in use and those put aside) whose -/// submits the GPU has passed: the recordings on them that have ended need their memory no more. +/// The PC allocators of the title's allocator `a` (the one in use and those put aside) with no +/// live recordings left on them and whose submits the GPU has passed: only then can their UMA +/// arenas and two-pass scratch/record buffers go back safely (a put-aside backing whose lists +/// have not been submitted yet has empty `marks`, so `idle()` alone would free them too early). unsafe fn done_with(s: &State, a: usize) -> Vec { let cur = s.cur.get(&a).copied().unwrap_or(a); std::iter::once(cur) .chain(s.aside.get(&a).into_iter().flatten().copied()) - .filter(|b| s.backings.get(b).is_none_or(|x| x.idle())) + .filter(|b| s.backings.get(b).is_none_or(|x| x.free())) .collect() } diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs new file mode 100644 index 0000000000..75c6ce3aac --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -0,0 +1,1949 @@ +//! Sky-following stand-in ambient lighting when ray-traced indirect illumination is gated off. +//! +//! When `XCL_RT_GATE` holds back ray-traced indirect lighting passes, screen-space probe resolve +//! (`CS_ScreenProbes_TemporalResolve`) receives no ray-traced bounce irradiance (leaving foliage, +//! cloth, and indoor shadows dark or corrupted) and reflection history (`CS_UpdateHistory`) can +//! retain unoccluded sky glare indoors. +//! +//! Controlled by `XCL_AMBIENT`: +//! * `auto` (default): active only while `XCL_RT_GATE` is holding back BVH traversal. +//! * `sky` / `1` / `on`: always active. +//! * `0` / `off` / `none`: disabled. +//! +//! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, +//! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`. + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; +use std::time::Instant; + +use windows::core::{Interface, PCSTR}; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::console_list::{Layout, Param}; +use super::{list_x, present, real}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + Off, + Auto, + Sky, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Config { + mode: Mode, + gain: f32, + power: f32, + least: f32, + ao: f32, + reflect: f32, + settle_ms: f32, + air: f32, +} + +impl Default for Config { + fn default() -> Self { + Self { + mode: Mode::Auto, + gain: 0.22, + power: 0.65, + least: 0.02, + ao: 0.55, + reflect: 0.50, + settle_ms: 250.0, + air: 0.0, + } + } +} + +fn parse_mode(raw: Option<&str>) -> Mode { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("0" | "off" | "none" | "false") => Mode::Off, + Some("sky" | "1" | "on" | "true") => Mode::Sky, + _ => Mode::Auto, + } +} + +fn env_f32(name: &str, default: f32, lo: f32, hi: f32) -> f32 { + std::env::var(name) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| v.is_finite()) + .map_or(default, |v| v.clamp(lo, hi)) +} + +fn config() -> &'static Config { + static CFG: OnceLock = OnceLock::new(); + CFG.get_or_init(|| { + let def = Config::default(); + let raw = std::env::var("XCL_AMBIENT").ok(); + Config { + mode: parse_mode(raw.as_deref()), + gain: env_f32("XCL_AMBIENT_GAIN", def.gain, 0.0, 8.0), + power: env_f32("XCL_AMBIENT_POWER", def.power, 0.1, 4.0), + least: env_f32("XCL_AMBIENT_LEAST", def.least, 0.0, 2.0), + ao: env_f32("XCL_AMBIENT_AO", def.ao, 0.0, 1.0), + reflect: env_f32("XCL_AMBIENT_REFLECT", def.reflect, 0.05, 4.0), + settle_ms: env_f32("XCL_AMBIENT_SETTLE_MS", def.settle_ms, 0.0, 10_000.0), + air: env_f32("XCL_AMBIENT_AIR", def.air, 0.0, 16.0), + } + }) +} + +/// Time-based EMA smoothing factor `1 - exp(-dt / tau)` for sky-dome ambient settling. +/// Snaps immediately (`1.0`) on the first captured sample or when `settle_ms <= 0`. +fn settle_alpha(dt_s: f32, settle_ms: f32, first_sample: bool) -> f32 { + if first_sample || settle_ms <= 0.0 { + return 1.0; + } + let dt = dt_s.clamp(0.0, 2.0); + let tau = (settle_ms * 1e-3).max(1e-4); + (1.0 - (-dt / tau).exp()).clamp(0.0, 1.0) +} + +fn monotonic_us() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + let base = EPOCH.get_or_init(Instant::now); + (base.elapsed().as_micros() as u64).saturating_add(1) +} + +/// Whether sky-following stand-in ambient tracking is enabled (`XCL_AMBIENT != 0/off`). +pub fn enabled() -> bool { + config().mode != Mode::Off +} + +/// Whether stand-in ambient passes should currently execute. +pub fn active() -> bool { + match config().mode { + Mode::Off => false, + Mode::Sky => true, + Mode::Auto => rays_find_nothing(real::bvh_traversal_allowed(), crate::gpu::dxil::kernel::rt_all_miss()), + } +} + +/// The title's rays bring no light: traversal is held back, or runs with every ray missing. +fn rays_find_nothing(traversal_allowed: bool, every_ray_misses: bool) -> bool { + !traversal_allowed || every_ray_misses +} + +/// Role of a console shader identified from FSSM/container metadata. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PassRole { + SkyDome, + TemporalResolve, + ReflectionHistory, + InscatteringVolume, +} + +fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool { + if needle.is_empty() || haystack.len() < needle.len() { + return false; + } + haystack.windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle)) +} + +fn classify_ps(blob: &[u8]) -> Option { + if contains_ascii_ci(blob, b"ps_sky_paraboloid_reflection") { + Some(PassRole::SkyDome) + } else { + None + } +} + +fn classify_cs(blob: &[u8]) -> Option { + if contains_ascii_ci(blob, b"CS_ScreenProbes_TemporalResolve") { + Some(PassRole::TemporalResolve) + } else if contains_ascii_ci(blob, b"CS_UpdateHistory") { + Some(PassRole::ReflectionHistory) + } else if contains_ascii_ci(blob, b"CS_AccumulateLocalLightInscatteringVolume") { + Some(PassRole::InscatteringVolume) + } else { + None + } +} + +static PSO_ROLES: RwLock>> = RwLock::new(None); +static HAS_SKY_PSO: AtomicBool = AtomicBool::new(false); +static HAS_CS_PSO: AtomicBool = AtomicBool::new(false); + +pub(super) fn note_graphics_pso(pso: usize, ps: Option<&[u8]>) { + if pso == 0 || !enabled() { + return; + } + if let Some(role) = ps.and_then(classify_ps) { + PSO_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, role); + HAS_SKY_PSO.store(true, Ordering::Release); + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: ambient: tracked sky paraboloid PSO {pso:#x}"); + } + } +} + +/// Whether a compute shader blob belongs to a pass handled by stand-in ambient lighting +/// (`CS_ScreenProbes_TemporalResolve` / `CS_UpdateHistory` / +/// `CS_AccumulateLocalLightInscatteringVolume`). +pub(super) fn is_ambient_compute(blob: &[u8]) -> bool { + classify_cs(blob).is_some() +} + +pub(super) fn note_compute_pso(pso: usize, cs: &[u8]) { + if pso == 0 || !enabled() { + return; + } + if let Some(role) = classify_cs(cs) { + PSO_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, role); + HAS_CS_PSO.store(true, Ordering::Release); + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: ambient: tracked {role:?} compute PSO {pso:#x}"); + } + } +} + +#[inline] +pub(super) fn has_sky_psos() -> bool { + HAS_SKY_PSO.load(Ordering::Relaxed) +} + +#[inline] +pub(super) fn has_compute_psos() -> bool { + HAS_CS_PSO.load(Ordering::Relaxed) +} + +fn role_of(pso: usize) -> Option { + if pso == 0 { + return None; + } + PSO_ROLES.read().unwrap().as_ref()?.get(&pso).copied() +} + +/// Descriptor-heap view metadata indexed by BOTH console slot UMA address (`slot.at`, globally +/// unique across all shader-visible and CPU-only heaps) and `GLOBAL` heap descriptor index +/// (`slot.index` when hosted in `GLOBAL`) so both `CopyDescriptors*` and inline title `memcpy` +/// resolve without CPU-only heap index collisions. +#[derive(Clone, Copy, Debug)] +struct ViewEntry { + res: usize, + fmt: i32, + is_uav: bool, +} + +#[derive(Default)] +struct ViewSlots { + by_addr: HashMap, + by_idx: HashMap, +} + +static VIEW_SLOTS: RwLock> = RwLock::new(None); +static HAS_VIEW_SLOTS: AtomicBool = AtomicBool::new(false); + +fn is_ambient_uav_format(fmt: i32) -> bool { + // R16G16B16A16_FLOAT (10), R11G11B10_FLOAT (26), R32G32B32A32_FLOAT (2), R32_UINT (42, R9G9B9E5 packed) + matches!(fmt, 10 | 26 | 2 | 42) +} + +fn is_depth_srv_format(fmt: i32) -> bool { + // R32_FLOAT (41), R24_UNORM_X8_TYPELESS (46), R32_FLOAT_X8X24_TYPELESS (21), R16_UNORM (56) + matches!(fmt, 41 | 46 | 21 | 56) +} + +fn is_depth_resource_format(fmt: i32) -> bool { + matches!(fmt, 19 | 20 | 39 | 40 | 44 | 45 | 53 | 55) +} + +/// Record a 2D texture UAV or depth SRV written at console slot address `slot_at` (and optional +/// `GLOBAL` descriptor index `global_index`, 0 when on a CPU-only / unhosted heap). +pub(super) fn note_descriptor(slot_at: usize, global_index: u32, res: usize, fmt: i32, res_fmt: i32, is_uav: bool) { + if !enabled() || (slot_at == 0 && global_index == 0) { + return; + } + if res == 0 { + if HAS_VIEW_SLOTS.load(Ordering::Relaxed) { + if let Some(s) = VIEW_SLOTS.write().unwrap().as_mut() { + if slot_at != 0 { + s.by_addr.remove(&slot_at); + } + if global_index != 0 { + s.by_idx.remove(&global_index); + } + } + } + return; + } + let keep = if is_uav { + is_ambient_uav_format(fmt) + } else { + is_depth_srv_format(fmt) && is_depth_resource_format(res_fmt) + }; + let mut g = VIEW_SLOTS.write().unwrap(); + if keep { + let s = g.get_or_insert_with(ViewSlots::default); + let ve = ViewEntry { res, fmt, is_uav }; + if slot_at != 0 { + s.by_addr.insert(slot_at, ve); + } + if global_index != 0 { + s.by_idx.insert(global_index, ve); + } + HAS_VIEW_SLOTS.store(true, Ordering::Release); + } else if let Some(s) = g.as_mut() { + if slot_at != 0 { + s.by_addr.remove(&slot_at); + } + if global_index != 0 { + s.by_idx.remove(&global_index); + } + } +} + +/// Evict any cached descriptor entries referencing a destroyed resource so stale raw pointers +/// are never dereferenced during dispatch lookup. +pub(super) fn forget_resource(res: usize) { + if res == 0 || !HAS_VIEW_SLOTS.load(Ordering::Relaxed) { + return; + } + if let Some(s) = VIEW_SLOTS.write().unwrap().as_mut() { + s.by_addr.retain(|_, v| v.res != res); + s.by_idx.retain(|_, v| v.res != res); + } +} + +/// Propagate view metadata when `CopyDescriptors*` copies from `src_at` (with pre-copy T# word 0 +/// `src_global_index`) to `dst_at` (with destination `GLOBAL` index `dst_global_index`, 0 if unhosted). +pub(super) fn copy_descriptor(src_at: usize, src_global_index: u32, dst_at: usize, dst_global_index: u32) { + if !enabled() || !HAS_VIEW_SLOTS.load(Ordering::Relaxed) || (src_at == dst_at && src_global_index == dst_global_index) { + return; + } + let entry = VIEW_SLOTS.read().unwrap().as_ref().and_then(|s| { + s.by_addr + .get(&src_at) + .or_else(|| (src_global_index != 0).then(|| s.by_idx.get(&src_global_index)).flatten()) + .copied() + }); + let mut g = VIEW_SLOTS.write().unwrap(); + match entry { + Some(v) => { + let s = g.get_or_insert_with(ViewSlots::default); + if dst_at != 0 { + s.by_addr.insert(dst_at, v); + } + if dst_global_index != 0 { + s.by_idx.insert(dst_global_index, v); + } + } + None => { + if let Some(s) = g.as_mut() { + if dst_at != 0 { + s.by_addr.remove(&dst_at); + } + if dst_global_index != 0 { + s.by_idx.remove(&dst_global_index); + } + } + } + } +} + +fn is_sky_dome_target(rd: &D3D12_RESOURCE_DESC) -> bool { + rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && rd.Width == 128 + && rd.Height == 128 + && matches!(rd.Format, DXGI_FORMAT_R16G16B16A16_FLOAT | DXGI_FORMAT_R16G16B16A16_TYPELESS) + && rd.SampleDesc.Count == 1 +} + +/// Match a screen-space resolve/reflection output UAV against dispatch grid dimensions, returning +/// a lower-is-better score when compatible (`None` if incompatible). +/// `TemporalResolve` writes diffuse screen-probe light as packed `R9G9B9E5` in `R32_UINT` (`fmt 42`); +/// restricting `TemporalResolve` to `R32_UINT` avoids accidentally overwriting a `R11G11B10_FLOAT` +/// (`fmt 26`) HDR scene color buffer bound in the same descriptor heap. +fn score_dispatch_target_for_role(role: PassRole, rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; 3]) -> Option { + if role == PassRole::TemporalResolve && view_fmt != 42 { + return None; + } + if role == PassRole::ReflectionHistory && view_fmt == 42 { + return None; + } + score_dispatch_target(rd, view_fmt, groups) +} + +fn score_dispatch_target(rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; 3]) -> Option { + if rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D + || rd.DepthOrArraySize != 1 + || rd.SampleDesc.Count != 1 + || rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 + || !is_ambient_uav_format(view_fmt) + { + return None; + } + let w = rd.Width as u32; + let h = rd.Height; + if w < 64 || h < 64 { + return None; + } + // Indirect or 1D tiled dispatch (`groups[0] == 0` or `groups[1] <= 1`): match screen-space 2D + // float UAV targets (>= 128x72), preferring larger resolution. + if groups[0] == 0 || groups[1] <= 1 { + if w < 128 || h < 72 { + return None; + } + return Some(u64::MAX - (w as u64).saturating_mul(h as u64)); + } + let max_w = groups[0].saturating_mul(64); + let max_h = groups[1].saturating_mul(64); + let min_w = (groups[0] / 2).max(64); + let min_h = (groups[1] / 2).max(64); + if w < min_w || w > max_w || h < min_h || h > max_h { + return None; + } + // Console compute shaders commonly use [8, 8, 1] or Wave32 [8, 4, 1] thread groups + // (e.g. [320, 360, 1] -> 2560x1440 at 8x4 or 1280x720 at 4x2); score by closest fit. + let d88 = (w as i64 - groups[0].saturating_mul(8) as i64).unsigned_abs() + + (h as i64 - groups[1].saturating_mul(8) as i64).unsigned_abs(); + let d84 = (w as i64 - groups[0].saturating_mul(8) as i64).unsigned_abs() + + (h as i64 - groups[1].saturating_mul(4) as i64).unsigned_abs(); + let d42 = (w as i64 - groups[0].saturating_mul(4) as i64).unsigned_abs() + + (h as i64 - groups[1].saturating_mul(2) as i64).unsigned_abs(); + Some(d88.min(d84).min(d42)) +} + +fn is_air_volume_uav_format(fmt: i32) -> bool { + // R16G16B16A16_FLOAT (10), R11G11B10_FLOAT (26) + matches!(fmt, 10 | 26) +} + +/// Match a 3D volumetric inscattering froxel UAV against dispatch grid dimensions, returning +/// a lower-is-better score when compatible (`None` if incompatible). +fn score_volume_target(rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; 3]) -> Option { + if rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D + || rd.SampleDesc.Count != 1 + || rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 + || !is_air_volume_uav_format(view_fmt) + { + return None; + } + let w = rd.Width as u32; + let h = rd.Height; + let d = rd.DepthOrArraySize as u32; + if w < 16 || h < 16 || d < 4 { + return None; + } + if groups[0] == 0 || groups[1] <= 1 { + return Some(u64::MAX - (w as u64).saturating_mul(h as u64).saturating_mul(d as u64)); + } + let max_w = groups[0].saturating_mul(32); + let max_h = groups[1].saturating_mul(32); + let min_w = (groups[0] / 2).max(16); + let min_h = (groups[1] / 2).max(16); + if w < min_w || w > max_w || h < min_h || h > max_h { + return None; + } + let dw = (w as i64 - groups[0].saturating_mul(8) as i64) + .unsigned_abs() + .min((w as i64 - groups[0].saturating_mul(4) as i64).unsigned_abs()); + let dh = (h as i64 - groups[1].saturating_mul(8) as i64) + .unsigned_abs() + .min((h as i64 - groups[1].saturating_mul(4) as i64).unsigned_abs()); + let dd = if groups[2] <= 1 { + 0 + } else { + (d as i64 - groups[2] as i64) + .unsigned_abs() + .min((d as i64 - groups[2].saturating_mul(2) as i64).unsigned_abs()) + .min((d as i64 - groups[2].saturating_mul(4) as i64).unsigned_abs()) + .min((d as i64 - groups[2].saturating_mul(8) as i64).unsigned_abs()) + }; + Some(dw + dh + dd) +} + +#[cfg(test)] +fn matches_dispatch_target(rd: &D3D12_RESOURCE_DESC, groups: [u32; 3]) -> bool { + score_dispatch_target(rd, rd.Format.0, groups).is_some() +} + +/// Compute scalar/RGB stand-in sky level (mirrors the GPU `sky_reduce_cs` transfer curve). +#[cfg(test)] +fn sky_transfer(mean_rgb: [f32; 3], gain: f32, power: f32, least: f32) -> [f32; 3] { + [ + gain * mean_rgb[0].max(0.0).powf(power) + least, + gain * mean_rgb[1].max(0.0).powf(power) + least, + gain * mean_rgb[2].max(0.0).powf(power) + least, + ] +} + +// --------------------------------------------------------------------------------------- +// Internal D3D12 compute pipelines & per-device rotating descriptor ring +// --------------------------------------------------------------------------------------- + +/// Rotating groups of 3 descriptors (`t0` SRV, `u0` UAV, `u1` UAV) in our private shader-visible +/// heap so back-to-back in-flight dispatches never overwrite descriptors still read by the GPU. +const RING_GROUPS: u32 = 256; +const GROUP_SLOTS: u32 = 3; + +struct AmbientDevice { + rs: ID3D12RootSignature, + reduce_pso: ID3D12PipelineState, + fill_pso: ID3D12PipelineState, + fill_write_pso: ID3D12PipelineState, + fill_r9_pso: ID3D12PipelineState, + reflect_pso: ID3D12PipelineState, + air_pso: ID3D12PipelineState, + sky_copy: ID3D12Resource, + sky_level: ID3D12Resource, + dummy_depth: ID3D12Resource, + heap: ID3D12DescriptorHeap, + heap_cpu: u64, + heap_gpu: u64, + inc: u32, + next_group: AtomicU32, + sky_ready: AtomicBool, + last_sky_us: AtomicU64, +} + +unsafe impl Send for AmbientDevice {} +unsafe impl Sync for AmbientDevice {} + +static DEVICES: Mutex>>>> = Mutex::new(None); + +fn compile_cs_sm5(src: &str) -> Option> { + unsafe { + let mut blob = None; + let r = D3DCompile( + src.as_ptr() as *const c_void, + src.len(), + PCSTR::null(), + None, + None, + PCSTR(b"main\0".as_ptr()), + PCSTR(b"cs_5_0\0".as_ptr()), + 0, + 0, + &mut blob, + None, + ); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +const SKY_REDUCE_HLSL: &str = r#" +Texture2D sky_tex : register(t0); +RWStructuredBuffer sky_level : register(u0); +cbuffer C : register(b0) { + float gain; + float power; + float least; + float settle_alpha; + uint _u4; + uint _u5; + uint _u6; + uint _u7; +}; +groupshared float3 gs_sum[64]; +[numthreads(8, 8, 1)] +void main(uint3 gtid : SV_GroupThreadID, uint gidx : SV_GroupIndex) { + float3 acc = float3(0.0, 0.0, 0.0); + uint x0 = gtid.x * 16; + uint y0 = gtid.y * 16; + [loop] + for (uint dy = 0; dy < 16; ++dy) { + [loop] + for (uint dx = 0; dx < 16; ++dx) { + float3 c = sky_tex.Load(int3(int(x0 + dx), int(y0 + dy), 0)).rgb; + if (all(isfinite(c))) { + acc += clamp(c, 0.0, 16.0); + } + } + } + gs_sum[gidx] = acc * (1.0 / 256.0); + GroupMemoryBarrierWithGroupSync(); + [unroll] + for (uint s = 32; s > 0; s >>= 1) { + if (gidx < s) { + gs_sum[gidx] += gs_sum[gidx + s]; + } + GroupMemoryBarrierWithGroupSync(); + } + if (gidx == 0) { + float3 mean_rgb = max(gs_sum[0] * (1.0 / 64.0), 0.0); + float3 target = gain * pow(mean_rgb, power) + least; + float4 prev = sky_level[0]; + float a = saturate(settle_alpha); + float3 level = (a >= 0.999 || !all(isfinite(prev.rgb)) || prev.w <= 0.0) + ? target + : lerp(prev.rgb, target, a); + float lum = dot(level, float3(0.2126, 0.7152, 0.0722)); + sky_level[0] = float4(level, lum); + } +} +"#; + +/// Screen-space radiance floor + 8-tap IGN-rotated golden-angle horizon crease AO + outlier +/// probe tile suppression (requires typed UAV load on `out_uav`). +const AMBIENT_FILL_HLSL: &str = r#" +Texture2D depth_tex : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint depth_w; + uint depth_h; + uint has_depth; + float ao_strength; + uint sky_ready; + float fallback_level; +}; +float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { + float d0 = depth_tex.Load(int3(dc, 0)); + if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { + return 1.0; + } + float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); + float base_ang = ign * 6.2831853; + float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); + float inv_d0 = 1.0 / max(d0, 1e-5); + float occ = 0.0; + [unroll] + for (uint i = 0; i < 4; ++i) { + float ang = base_ang + float(i) * 0.78539816; + float t = frac(ign * 0.61803399 + (float(i) + 0.5) * 0.25); + float rad = clamp(max_rad * sqrt(t), 1.5, 16.0); + int2 ofs = int2(int(round(cos(ang) * rad)), int(round(sin(ang) * rad))); + float dp = depth_tex.Load(int3(clamp(dc + ofs, int2(0, 0), maxc), 0)); + float dn = depth_tex.Load(int3(clamp(dc - ofs, int2(0, 0), maxc), 0)); + float rp = (dp - d0) * inv_d0; + float rn = (dn - d0) * inv_d0; + float wp = (isfinite(dp) && dp > 1e-6 && dp < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rp))) : 0.0; + float wn = (isfinite(dn) && dn > 1e-6 && dn < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rn))) : 0.0; + float conc = max(0.0, rp * wp + rn * wn); + occ += saturate((conc - 0.003) * 4.5); + } + return saturate(1.0 - ao_strength * saturate(occ * 0.25)); +} +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + float3 amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + float ao = 1.0; + if (has_depth != 0 && depth_w > 0 && depth_h > 0) { + int2 dc = int2( + int(min((tid.x * depth_w) / max(width, 1u), depth_w - 1)), + int(min((tid.y * depth_h) / max(height, 1u), depth_h - 1)) + ); + int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); + ao = horizon_crease_ao(tid.xy, dc, maxc); + } + float3 amb_ao = amb * ao; + float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.02); + float cap_lum = 4.0 * amb_lum; + float4 cur = out_uav[tid.xy]; + float3 existing = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + if (existing.g < 0.5 * min(existing.r, existing.b) && max(existing.r, existing.b) > 0.02) { + existing = float3(0.0, 0.0, 0.0); + } + float cur_lum = dot(existing, float3(0.2126, 0.7152, 0.0722)); + if (cur_lum > cap_lum) { + existing *= (cap_lum / max(cur_lum, 1e-6)); + } + float ch_cap = cap_lum * 1.5; + existing = min(existing, float3(ch_cap, ch_cap, ch_cap)); + float3 out_rgb = max(existing, amb_ao); + out_uav[tid.xy] = float4(out_rgb, isfinite(cur.a) ? cur.a : 1.0); +} +"#; + +/// Screen-space diffuse probe radiance floor + 8-tap IGN-rotated horizon crease AO for +/// `CS_ScreenProbes_TemporalResolve` targets stored as `R9G9B9E5_SHAREDEXP` packed in `R32_UINT`. +const AMBIENT_FILL_R9G9B9E5_HLSL: &str = r#" +Texture2D depth_tex : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint depth_w; + uint depth_h; + uint has_depth; + float ao_strength; + uint sky_ready; + float fallback_level; +}; +float3 unpack_r9g9b9e5(uint v) { + float scale = exp2(float(v >> 27) - 24.0); + return float3(float(v & 511u), float((v >> 9) & 511u), float((v >> 18) & 511u)) * scale; +} +uint pack_r9g9b9e5(float3 c) { + c = clamp(c, 0.0, 65408.0); + float top = max(c.r, max(c.g, c.b)); + int e = clamp(int(floor(log2(max(top, 1e-9)))) + 16, 0, 31); + float inv_s = exp2(float(24 - e)); + uint3 m = min(uint3(floor(c * inv_s + 0.5)), uint3(511u, 511u, 511u)); + return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); +} +float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { + float d0 = depth_tex.Load(int3(dc, 0)); + if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { + return 1.0; + } + float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); + float base_ang = ign * 6.2831853; + float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); + float inv_d0 = 1.0 / max(d0, 1e-5); + float occ = 0.0; + [unroll] + for (uint i = 0; i < 4; ++i) { + float ang = base_ang + float(i) * 0.78539816; + float t = frac(ign * 0.61803399 + (float(i) + 0.5) * 0.25); + float rad = clamp(max_rad * sqrt(t), 1.5, 16.0); + int2 ofs = int2(int(round(cos(ang) * rad)), int(round(sin(ang) * rad))); + float dp = depth_tex.Load(int3(clamp(dc + ofs, int2(0, 0), maxc), 0)); + float dn = depth_tex.Load(int3(clamp(dc - ofs, int2(0, 0), maxc), 0)); + float rp = (dp - d0) * inv_d0; + float rn = (dn - d0) * inv_d0; + float wp = (isfinite(dp) && dp > 1e-6 && dp < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rp))) : 0.0; + float wn = (isfinite(dn) && dn > 1e-6 && dn < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rn))) : 0.0; + float conc = max(0.0, rp * wp + rn * wn); + occ += saturate((conc - 0.003) * 4.5); + } + return saturate(1.0 - ao_strength * saturate(occ * 0.25)); +} +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + float3 raw_amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + float3 amb = clamp(raw_amb, 0.0, 0.65); + float ao = 1.0; + if (has_depth != 0 && depth_w > 0 && depth_h > 0) { + int2 dc = int2( + int(min((tid.x * depth_w) / max(width, 1u), depth_w - 1)), + int(min((tid.y * depth_h) / max(height, 1u), depth_h - 1)) + ); + int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); + ao = horizon_crease_ao(tid.xy, dc, maxc); + } + float3 amb_ao = amb * ao; + float3 existing = unpack_r9g9b9e5(out_uav[tid.xy]); + if (!all(isfinite(existing))) existing = float3(0.0, 0.0, 0.0); + if (existing.g < 0.5 * min(existing.r, existing.b) && max(existing.r, existing.b) > 0.02) { + existing = float3(0.0, 0.0, 0.0); + } + float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.02); + float cap_lum = 6.0 * amb_lum; + float cur_lum = dot(existing, float3(0.2126, 0.7152, 0.0722)); + if (cur_lum > cap_lum) { + existing *= (cap_lum / max(cur_lum, 1e-6)); + } + out_uav[tid.xy] = pack_r9g9b9e5(max(existing, amb_ao)); +} +"#; + +/// Write-only fallback for `TemporalResolve` when typed UAV load is unsupported on `out_uav`. +const AMBIENT_FILL_WRITE_HLSL: &str = r#" +Texture2D depth_tex : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint depth_w; + uint depth_h; + uint has_depth; + float ao_strength; + uint sky_ready; + float fallback_level; +}; +float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { + float d0 = depth_tex.Load(int3(dc, 0)); + if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { + return 1.0; + } + float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); + float base_ang = ign * 6.2831853; + float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); + float inv_d0 = 1.0 / max(d0, 1e-5); + float occ = 0.0; + [unroll] + for (uint i = 0; i < 4; ++i) { + float ang = base_ang + float(i) * 0.78539816; + float t = frac(ign * 0.61803399 + (float(i) + 0.5) * 0.25); + float rad = clamp(max_rad * sqrt(t), 1.5, 16.0); + int2 ofs = int2(int(round(cos(ang) * rad)), int(round(sin(ang) * rad))); + float dp = depth_tex.Load(int3(clamp(dc + ofs, int2(0, 0), maxc), 0)); + float dn = depth_tex.Load(int3(clamp(dc - ofs, int2(0, 0), maxc), 0)); + float rp = (dp - d0) * inv_d0; + float rn = (dn - d0) * inv_d0; + float wp = (isfinite(dp) && dp > 1e-6 && dp < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rp))) : 0.0; + float wn = (isfinite(dn) && dn > 1e-6 && dn < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rn))) : 0.0; + float conc = max(0.0, rp * wp + rn * wn); + occ += saturate((conc - 0.003) * 4.5); + } + return saturate(1.0 - ao_strength * saturate(occ * 0.25)); +} +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + float3 amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + float ao = 1.0; + if (has_depth != 0 && depth_w > 0 && depth_h > 0) { + int2 dc = int2( + int(min((tid.x * depth_w) / max(width, 1u), depth_w - 1)), + int(min((tid.y * depth_h) / max(height, 1u), depth_h - 1)) + ); + int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); + ao = horizon_crease_ao(tid.xy, dc, maxc); + } + out_uav[tid.xy] = float4(amb * ao, 1.0); +} +"#; + +const REFLECT_CLAMP_HLSL: &str = r#" +Texture2D _unused : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint _u2; + uint _u3; + uint _u4; + float reflect_scale; + float _p6; + float _p7; +}; +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + float4 cur = out_uav[tid.xy]; + float3 rgb = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + float3 cap = max(sky_level[0].rgb * reflect_scale, float3(0.005, 0.005, 0.005)); + out_uav[tid.xy] = float4(min(rgb, cap), isfinite(cur.a) ? cur.a : 1.0); +} +"#; + +/// Lightweight 3D froxel luminance cap for `CS_AccumulateLocalLightInscatteringVolume`: smoothly +/// compresses over-bright indoor volumetric haze against the settled sky luminance * `air_scale` +/// while preserving sky scatter chromaticity through windows. +const AIR_CAP_HLSL: &str = r#" +Texture2D _unused : register(t0); +RWTexture3D vol_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint depth; + uint _u3; + uint _u4; + float air_scale; + float _p6; + float _p7; +}; +[numthreads(8, 8, 2)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height || tid.z >= depth) return; + float4 cur = vol_uav[tid]; + float3 rgb = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + float sky_lum = max(sky_level[0].w, 0.01); + float cap = max(sky_lum * air_scale, 0.01); + float lum = dot(rgb, float3(0.2126, 0.7152, 0.0722)); + if (lum > cap) { + float excess = lum - cap; + float rolled = cap + excess / (1.0 + excess / max(cap, 1e-4)); + rgb *= (rolled / max(lum, 1e-6)); + } + float ch_cap = cap * 2.0; + rgb = min(rgb, float3(ch_cap, ch_cap, ch_cap)); + vol_uav[tid] = float4(rgb, isfinite(cur.a) ? cur.a : 0.0); +} +"#; + +unsafe fn build_device(dev: &ID3D12Device) -> Option { + let reduce_bc = compile_cs_sm5(SKY_REDUCE_HLSL)?; + let fill_bc = compile_cs_sm5(AMBIENT_FILL_HLSL)?; + let fill_write_bc = compile_cs_sm5(AMBIENT_FILL_WRITE_HLSL)?; + let fill_r9_bc = compile_cs_sm5(AMBIENT_FILL_R9G9B9E5_HLSL)?; + let reflect_bc = compile_cs_sm5(REFLECT_CLAMP_HLSL)?; + let air_bc = compile_cs_sm5(AIR_CAP_HLSL)?; + + // Shared compute RS: [0] 8 root constants (b0), [1] 1 SRV (t0), [2] 2 UAVs (u0..u1) + let srv_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 2, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 8 }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &uav_range }, + }, + }, + ]; + let rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + ..Default::default() + }; + let mut rs_blob = None; + D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut rs_blob, None).ok()?; + let rs_blob = rs_blob?; + + let dev_raw = dev.as_raw(); + type CreateRsFn = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const c_void, *mut *mut c_void) -> i32; + type CreateCsFn = unsafe extern "system" fn(*mut c_void, *const D3D12_COMPUTE_PIPELINE_STATE_DESC, *const c_void, *mut *mut c_void) -> i32; + type CreateHeapFn = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const c_void, *mut *mut c_void) -> i32; + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + type CreateResFn = unsafe extern "system" fn( + *mut c_void, + *const D3D12_HEAP_PROPERTIES, + D3D12_HEAP_FLAGS, + *const D3D12_RESOURCE_DESC, + D3D12_RESOURCE_STATES, + *const D3D12_CLEAR_VALUE, + *const c_void, + *mut *mut c_void, + ) -> i32; + + let create_rs: CreateRsFn = std::mem::transmute(real::orig_fn(dev_raw, 16)); + let create_cs: CreateCsFn = std::mem::transmute(real::orig_fn(dev_raw, 11)); + let create_heap: CreateHeapFn = std::mem::transmute(real::orig_fn(dev_raw, 14)); + let inc_size: IncSizeFn = std::mem::transmute(real::orig_fn(dev_raw, 15)); + let create_res: CreateResFn = std::mem::transmute(real::orig_fn(dev_raw, 27)); + + let mut rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, rs_blob.GetBufferPointer(), rs_blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const c_void, &mut rs_raw) < 0 || rs_raw.is_null() { + return None; + } + let rs = ID3D12RootSignature::from_raw(rs_raw); + + let make_cs = |bc: &[u8], name: &str| -> Option { + let mut d = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bc.as_ptr() as *const c_void, BytecodeLength: bc.len() }, + ..Default::default() + }; + let mut raw = std::ptr::null_mut(); + let hr = create_cs(dev_raw, &d, &ID3D12PipelineState::IID as *const _ as *const c_void, &mut raw); + ManuallyDrop::drop(&mut d.pRootSignature); + (hr >= 0 && !raw.is_null()).then(|| { + let pso = ID3D12PipelineState::from_raw(raw); + let _ = pso.SetName(&windows::core::HSTRING::from(name)); + super::dred::label_text(pso.as_raw() as usize, || name.to_string()); + pso + }) + }; + let reduce_pso = make_cs(&reduce_bc, "xcl ambient sky_reduce")?; + let fill_pso = make_cs(&fill_bc, "xcl ambient fill")?; + let fill_write_pso = make_cs(&fill_write_bc, "xcl ambient fill_write")?; + let fill_r9_pso = make_cs(&fill_r9_bc, "xcl ambient fill_r9")?; + let reflect_pso = make_cs(&reflect_bc, "xcl ambient reflect_clamp")?; + let air_pso = make_cs(&air_bc, "xcl ambient air_cap")?; + + let default_hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let make_res = |rd: &D3D12_RESOURCE_DESC, init: D3D12_RESOURCE_STATES| -> Option { + let mut raw = std::ptr::null_mut(); + let hr = create_res(dev_raw, &default_hp, D3D12_HEAP_FLAG_NONE, rd, init, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const c_void, &mut raw); + (hr >= 0 && !raw.is_null()).then(|| ID3D12Resource::from_raw(raw)) + }; + + let sky_copy = make_res( + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )?; + let sky_level = make_res( + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + 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() + }, + D3D12_RESOURCE_STATE_COMMON, + )?; + let dummy_depth = make_res( + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )?; + + let heap_desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: RING_GROUPS * GROUP_SLOTS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }; + let mut heap_raw = std::ptr::null_mut(); + if create_heap(dev_raw, &heap_desc, &ID3D12DescriptorHeap::IID as *const _ as *const c_void, &mut heap_raw) < 0 || heap_raw.is_null() { + return None; + } + let heap = ID3D12DescriptorHeap::from_raw(heap_raw); + let heap_cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; + let heap_gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr; + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + Some(AmbientDevice { + rs, + reduce_pso, + fill_pso, + fill_write_pso, + fill_r9_pso, + reflect_pso, + air_pso, + sky_copy, + sky_level, + dummy_depth, + heap, + heap_cpu, + heap_gpu, + inc, + next_group: AtomicU32::new(0), + sky_ready: AtomicBool::new(false), + last_sky_us: AtomicU64::new(0), + }) +} + +unsafe fn get_device(dev: &ID3D12Device) -> Option> { + let key = dev.as_raw() as usize; + { + let g = DEVICES.lock().unwrap(); + if let Some(entry) = g.as_ref().and_then(|m| m.get(&key)) { + return entry.clone(); + } + } + let built = build_device(dev).map(std::sync::Arc::new); + DEVICES.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, built.clone()); + built +} + +impl AmbientDevice { + fn alloc_group(&self) -> (u64, u64) { + let g = self.next_group.fetch_add(1, Ordering::Relaxed) % RING_GROUPS; + let off = (g * GROUP_SLOTS) as u64 * self.inc as u64; + (self.heap_cpu + off, self.heap_gpu + off) + } +} + +unsafe fn uav_barrier(list: *mut c_void, res_raw: usize) { + let b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::transmute_copy(&res_raw), + }), + }, + }; + list_x::pc_resource_barriers(list, &[b]); +} + +unsafe fn typed_uav_load_supported(dev: &ID3D12Device, fmt: DXGI_FORMAT) -> bool { + let mut fs = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: fmt, ..Default::default() }; + dev.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &mut fs as *mut _ as *mut c_void, std::mem::size_of_val(&fs) as u32).is_ok() + && (fs.Support2.0 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD.0 != 0) +} + +/// Called right after a translated graphics draw completes: if the PSO is the sky paraboloid +/// reflection shader targeting a `128x128 R16G16B16A16_FLOAT` 2D render target, snapshot it +/// and update the sky-following ambient level buffer on the GPU. +pub(super) unsafe fn after_draw(list: *mut c_void, pso_resolved: usize) { + if !has_sky_psos() || !active() || role_of(pso_resolved) != Some(PassRole::SkyDome) { + return; + } + if list_x::tracked_list_type(list) != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + let Some(rt0) = present::rt0_resource(list as usize) else { return }; + let rt_ptr = rt0 as *mut c_void; + let Some(rt_res) = ID3D12Resource::from_raw_borrowed(&rt_ptr) else { return }; + if !is_sky_dome_target(&rt_res.GetDesc()) { + return; + } + let Some(cl) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) else { return }; + let mut dev: Option = None; + if cl.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Some(ad) = get_device(&dev) else { return }; + + let sky_raw = ad.sky_copy.as_raw() as usize; + list_x::transition(list, rt0, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_x::transition(list, sky_raw, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + list_x::pc_copy_resource(list, sky_raw, rt0); + list_x::transition(list, sky_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list_x::transition(list, rt0, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + + let (cpu0, gpu0) = ad.alloc_group(); + let inc = ad.inc as u64; + let dev_raw = dev.as_raw(); + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + + let sky_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 1, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, ad.sky_copy.as_raw(), &sky_srv, cpu0 as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); + + let cfg = config(); + let now_us = monotonic_us(); + let prev_us = ad.last_sky_us.swap(now_us, Ordering::AcqRel); + let first_sample = prev_us == 0 || !ad.sky_ready.load(Ordering::Acquire); + let dt_s = if first_sample { 0.0 } else { now_us.saturating_sub(prev_us) as f32 * 1e-6 }; + let alpha = settle_alpha(dt_s, cfg.settle_ms, first_sample); + if !first_sample { + uav_barrier(list, ad.sky_level.as_raw() as usize); + } + let consts = [cfg.gain.to_bits(), cfg.power.to_bits(), cfg.least.to_bits(), alpha.to_bits(), 0, 0, 0, 0]; + set_heaps(list, 1, &heap_raw); + set_cs_rs(list, ad.rs.as_raw()); + super::dred::mark_pipeline(list, ad.reduce_pso.as_raw() as usize, ad.reduce_pso.as_raw() as usize); + set_pso(list, ad.reduce_pso.as_raw()); + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + set_cs_table(list, 1, gpu0); + set_cs_table(list, 2, gpu0 + inc); + dispatch(list, 1, 1, 1); + uav_barrier(list, ad.sky_level.as_raw() as usize); + ad.sky_ready.store(true, Ordering::Release); + list_x::restore_after_internal_pass(list, false, true); + + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: ambient: captured 128x128 R16G16B16A16_FLOAT sky dome ({rt0:#x})"); + } +} + +/// Maximum bindless descriptor-heap slot index probed from root constants/CBVs +/// (covers >1.24M-slot console shader-visible view heaps). +const MAX_SLOT_INDEX: u32 = 2_000_000; + +/// Decode a CBV / buffer `V#` descriptor (`gpu::desc::cbv_words` / `buffer_words`) into +/// `(va, byte_len)` if it is a readable buffer descriptor (`w3 >> 28 < 8` and dst_sel `0xFAC`). +fn decode_cbv_vsharp(w: [u32; 4]) -> Option<(usize, usize)> { + if (w[3] >> 28) >= 8 || (w[3] & 0xFFF) != 0xFAC { + return None; + } + let va = (w[0] as u64 | ((w[1] as u64 & 0xFFFF) << 32)) as usize; + if va == 0 { + return None; + } + let stride = ((w[1] >> 16) & 0x3FFF) as usize; + let records = w[2] as usize; + let bytes = if stride == 0 { records } else { records.saturating_mul(stride) }; + (bytes >= 4).then_some((va, bytes.min(2048))) +} + +/// Resolve a GPU VA to a CPU-readable host address when it lives in a `PAGE_NOACCESS` GPU mirror view. +fn resolve_cbv_va(va: usize) -> usize { + if va == 0 { + return 0; + } + if crate::gpu::shader::readable(va, 4) { + return va; + } + match crate::hle::kernelx::mirrors::mapped_source(va) { + Some(Some(backing)) => backing, + Some(None) => 0, + None => crate::hle::kernelx::mirrors::source(va).unwrap_or(va), + } +} + +/// Scan up to `max_bytes` (capped at 2048 B) of readable constant-buffer memory at `va`, +/// resolving each chunk (capped at 256 B and never crossing a 64 KiB mirror page boundary) +/// through `resolve`, and feed candidate bindless descriptor indices `< MAX_SLOT_INDEX` into `push_idx`. +unsafe fn scan_cbv_indices_with( + va: usize, + max_bytes: usize, + mut resolve: impl FnMut(usize) -> usize, + push_idx: &mut impl FnMut(u32), +) { + if va == 0 || max_bytes < 4 { + return; + } + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + let total = max_bytes.min(2048); + let mut off = 0usize; + while off < total { + let Some(cur_va) = va.checked_add(off) else { break }; + let to_page_end = PAGE - (cur_va & (PAGE - 1)); + let chunk = (total - off).min(256).min(to_page_end); + let base = resolve(cur_va); + if base == 0 || !crate::gpu::shader::readable(base, chunk) { + break; + } + let words = chunk / 4; + for k in 0..words { + let v = ((base + 4 * k) as *const u32).read_unaligned(); + if v != 0 { + push_idx(v); + } + } + off += chunk; + } +} + +/// Scan up to `max_bytes` (capped at 2048 B) of readable constant-buffer memory at `va` in +/// page-bounded chunks and feed candidate bindless descriptor indices `< MAX_SLOT_INDEX` into `push_idx`. +unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMut(u32)) { + scan_cbv_indices_with(va, max_bytes, resolve_cbv_va, push_idx); +} + +/// Inspect a compute dispatch's bound descriptor tables, SM 6.6 directly-indexed view heap +/// (`view_heap_base`), and root/table CBVs to locate its output float UAV (2D screen-space or +/// 3D froxel volume when `want_3d` is true) and optional depth SRV for crease AO. +unsafe fn find_dispatch_views( + role: PassRole, + layout: &Layout, + args: &[u8], + groups: [u32; 3], + view_heap_base: u32, + want_3d: bool, +) -> (Option<(usize, i32, u32, u32, u32)>, Option<(usize, i32, u32, u32)>, usize, usize, usize) { + let Some(u) = crate::gpu::uma::get() else { return (None, None, 0, 0, 0) }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + let mut param_tables: Vec = Vec::new(); + let mut tables: Vec = Vec::new(); + let mut indices: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut push_idx = |v: u32| { + if v < MAX_SLOT_INDEX && seen.insert(v) { + indices.push(v); + } + }; + if view_heap_base != 0 { + tables.push(view_heap_base); + } + for p in &layout.params { + match *p { + Param::Constants { at, count } => { + for k in 0..count.min(64) as usize { + if let Some(v) = word(at as usize + 4 * k) { + push_idx(v); + } + } + } + Param::Descriptor { at } => { + let lo = word(at as usize).unwrap_or(0) as u64; + let hi = word(at as usize + 4).unwrap_or(0) as u64; + let va = (lo | (hi << 32)) as usize; + scan_cbv_indices(va, 2048, &mut push_idx); + } + Param::Table { at } => { + if let Some(t) = word(at as usize) { + if t != 0 { + if !param_tables.contains(&t) { + param_tables.push(t); + } + if !tables.contains(&t) { + tables.push(t); + } + } + } + } + } + } + + // Scan direct slots `0..64` of every bound `Param::Table` for BOTH direct image T# descriptors + // and CBV V# descriptors (whose buffer contents often carry bindless indices into `view_heap`). + let mut table_cbvs = 0usize; + let mut direct_addrs: Vec = Vec::new(); + for &t in ¶m_tables { + for k in 0..64usize { + let Some(off) = (t as usize).checked_add(32 * k) else { break }; + let Some(addr) = u.base().checked_add(off) else { break }; + if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { + break; + } + let w = [ + (addr as *const u32).read_unaligned(), + ((addr + 4) as *const u32).read_unaligned(), + ((addr + 8) as *const u32).read_unaligned(), + ((addr + 12) as *const u32).read_unaligned(), + ]; + if (w[3] >> 28) >= 8 { + direct_addrs.push(addr); + } else if let Some((cbv_va, cbv_len)) = decode_cbv_vsharp(w) { + table_cbvs += 1; + scan_cbv_indices(cbv_va, cbv_len, &mut push_idx); + } + } + } + + let mut uav_hit: Option<(u64, usize, i32, u32, u32, u32)> = None; + let mut depth_hit: Option<(usize, i32, u32, u32)> = None; + let slots = VIEW_SLOTS.read().unwrap(); + let Some(vs) = slots.as_ref() else { return (None, None, tables.len(), indices.len(), table_cbvs) }; + + let mut check_slot = |addr: usize| { + if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { + return; + } + let w0 = (addr as *const u32).read_unaligned(); + let w3 = ((addr + 12) as *const u32).read_unaligned(); + // Image T# descriptors have type >= 8 in bits [31:28] of word 3. + if (w3 >> 28) < 8 { + return; + } + let Some(&ve) = vs + .by_addr + .get(&addr) + .or_else(|| (w0 != 0).then(|| vs.by_idx.get(&w0)).flatten()) + else { + return; + }; + let ptr = ve.res as *mut c_void; + let Some(res) = ID3D12Resource::from_raw_borrowed(&ptr) else { return }; + let rd = res.GetDesc(); + if ve.is_uav { + let scored = if want_3d { + score_volume_target(&rd, ve.fmt, groups).map(|s| (s, rd.DepthOrArraySize as u32)) + } else { + score_dispatch_target_for_role(role, &rd, ve.fmt, groups).map(|s| (s, 1u32)) + }; + if let Some((score, depth)) = scored { + if uav_hit.is_none_or(|(best, _, _, _, _, _)| score < best) { + uav_hit = Some((score, ve.res, ve.fmt, rd.Width as u32, rd.Height, depth)); + } + } + } else if !want_3d + && depth_hit.is_none() + && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && rd.DepthOrArraySize == 1 + && rd.SampleDesc.Count == 1 + && rd.Width >= 64 + && rd.Height >= 64 + { + depth_hit = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height)); + } + }; + + for addr in direct_addrs { + check_slot(addr); + } + for &t in &tables { + for &idx in &indices { + let Some(off) = (t as usize).checked_add(32usize.saturating_mul(idx as usize)) else { continue }; + let Some(addr) = u.base().checked_add(off) else { continue }; + check_slot(addr); + } + } + (uav_hit.map(|(_, r, f, w, h, d)| (r, f, w, h, d)), depth_hit, tables.len(), indices.len(), table_cbvs) +} + +/// Called right after a translated compute dispatch completes: when RT is gated off and a sky +/// dome sample has been captured, apply the sky-following screen-space radiance floor + 8-tap +/// horizon crease AO on `CS_ScreenProbes_TemporalResolve`, clamp `CS_UpdateHistory` reflections +/// to `reflect * ambient`, and cap `CS_AccumulateLocalLightInscatteringVolume` 3D froxel haze +/// against settled sky luminance * `air`. +pub(super) unsafe fn after_compute_dispatch( + list: *mut c_void, + pso_resolved: usize, + groups: [u32; 3], + layout: Option<&Layout>, + args: &[u8], + view_heap_base: u32, +) { + if !has_compute_psos() || !active() { + return; + } + let Some(role) = role_of(pso_resolved) else { return }; + if !matches!(role, PassRole::TemporalResolve | PassRole::ReflectionHistory | PassRole::InscatteringVolume) { + return; + } + let cfg = config(); + if role == PassRole::InscatteringVolume && cfg.air <= 0.0 { + return; + } + let ty = list_x::tracked_list_type(list); + if !matches!(ty, Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE)) { + static BAD_TY: AtomicU64 = AtomicU64::new(0); + if BAD_TY.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!("D3D12.X: ambient: {role:?} skipped on unsupported list type {ty:?}"); + } + return; + } + let Some(layout) = layout else { + static NO_LAYOUT: AtomicU64 = AtomicU64::new(0); + if NO_LAYOUT.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!("D3D12.X: ambient: {role:?} skipped (no compute root-signature layout)"); + } + return; + }; + let Some(cl) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) else { return }; + let mut dev: Option = None; + if cl.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Some(ad) = get_device(&dev) else { return }; + let sky_ready = ad.sky_ready.load(Ordering::Acquire); + if !sky_ready { + static NO_SKY: AtomicU64 = AtomicU64::new(0); + if NO_SKY.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!( + "D3D12.X: ambient: {role:?} dispatched ({groups:?}) before sky dome capture ({})", + if role == PassRole::TemporalResolve { "using least fallback" } else { "skipping" } + ); + } + if role != PassRole::TemporalResolve { + return; + } + } + + let want_3d = role == PassRole::InscatteringVolume; + let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(role, layout, args, groups, view_heap_base, want_3d); + let Some((uav_res, uav_fmt, w, h, d)) = uav_opt else { + static MISS: AtomicU64 = AtomicU64::new(0); + if MISS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: {role:?} ({groups:?}) found no matching UAV (tables={n_tables}, view_heap={view_heap_base:#x}, table_cbvs={n_cbvs}, indices={n_indices})" + ); + } + return; + }; + let can_typed_load = typed_uav_load_supported(&dev, DXGI_FORMAT(uav_fmt)); + if matches!(role, PassRole::ReflectionHistory | PassRole::InscatteringVolume) && !can_typed_load { + static NO_LOAD: AtomicU64 = AtomicU64::new(0); + if NO_LOAD.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!("D3D12.X: ambient: {role:?} skipped (typed UAV load unsupported for fmt {uav_fmt})"); + } + return; + } + + let (cpu0, gpu0) = ad.alloc_group(); + let inc = ad.inc as u64; + let dev_raw = dev.as_raw(); + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + + let (depth_raw, depth_fmt, depth_w, depth_h, has_depth) = match (role, depth_opt) { + (PassRole::TemporalResolve, Some((r, f, dw, dh))) => (r as *mut c_void, DXGI_FORMAT(f), dw, dh, 1u32), + _ => (ad.dummy_depth.as_raw(), DXGI_FORMAT_R32_FLOAT, 1, 1, 0u32), + }; + let depth_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: depth_fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let out_uav_desc = if want_3d { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(uav_fmt), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE3D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture3D: D3D12_TEX3D_UAV { MipSlice: 0, FirstWSlice: 0, WSize: d }, + }, + } + } else { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(uav_fmt), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }, + }, + } + }; + let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 1, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, depth_raw, &depth_srv, cpu0 as usize); + create_uav(dev_raw, uav_res as *mut c_void, std::ptr::null_mut(), &out_uav_desc, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + uav_barrier(list, uav_res); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); + + let (pso, consts, disp) = match role { + PassRole::TemporalResolve => ( + if uav_fmt == 42 { + ad.fill_r9_pso.as_raw() + } else if can_typed_load { + ad.fill_pso.as_raw() + } else { + ad.fill_write_pso.as_raw() + }, + [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), sky_ready as u32, cfg.least.to_bits()], + (w.div_ceil(8), h.div_ceil(8), 1), + ), + PassRole::ReflectionHistory => ( + ad.reflect_pso.as_raw(), + [w, h, 0, 0, 0, cfg.reflect.to_bits(), 0, 0], + (w.div_ceil(8), h.div_ceil(8), 1), + ), + PassRole::InscatteringVolume => ( + ad.air_pso.as_raw(), + [w, h, d, 0, 0, cfg.air.to_bits(), 0, 0], + (w.div_ceil(8), h.div_ceil(8), d.div_ceil(2)), + ), + PassRole::SkyDome => return, + }; + set_heaps(list, 1, &heap_raw); + set_cs_rs(list, ad.rs.as_raw()); + super::dred::mark_pipeline(list, pso as usize, pso as usize); + set_pso(list, pso); + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + set_cs_table(list, 1, gpu0); + set_cs_table(list, 2, gpu0 + inc); + dispatch(list, disp.0, disp.1, disp.2); + uav_barrier(list, uav_res); + list_x::restore_after_internal_pass(list, false, true); + + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 6 { + crate::xlog_info!("D3D12.X: ambient: applied {role:?} stand-in on {w}x{h}x{d} fmt {uav_fmt} (depth AO: {has_depth})"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The stand-in is for a picture without bounce light: with traversal held back, and as much + /// with traversal running while every ray misses; not with rays that hit. + #[test] + fn the_stand_in_is_on_whenever_the_rays_find_nothing() { + assert!(rays_find_nothing(false, false), "traversal held back"); + assert!(rays_find_nothing(true, true), "every ray misses"); + assert!(rays_find_nothing(false, true)); + assert!(!rays_find_nothing(true, false), "rays that hit bring the title's own light"); + } + + #[test] + fn mode_and_shader_classification_match_expected_passes() { + assert_eq!(parse_mode(None), Mode::Auto); + assert_eq!(parse_mode(Some("auto")), Mode::Auto); + assert_eq!(parse_mode(Some("sky")), Mode::Sky); + assert_eq!(parse_mode(Some("1")), Mode::Sky); + assert_eq!(parse_mode(Some("0")), Mode::Off); + assert_eq!(parse_mode(Some("off")), Mode::Off); + + assert_eq!(classify_ps(b"\0PRIVps_sky_paraboloid_reflection\0"), Some(PassRole::SkyDome)); + assert_eq!(classify_ps(b"\0PS_Sky_Paraboloid_Reflection_V2\0"), Some(PassRole::SkyDome)); + assert_eq!(classify_ps(b"\0ps_gbuffer_opaque\0"), None); + + assert_eq!(classify_cs(b"ILDN\0CS_ScreenProbes_TemporalResolve\0"), Some(PassRole::TemporalResolve)); + assert_eq!(classify_cs(b"ILDN\0CS_UpdateHistory_16\0"), Some(PassRole::ReflectionHistory)); + assert_eq!(classify_cs(b"ILDN\0CS_CullInstances\0"), None); + } + + #[test] + fn sky_dome_filter_rejects_r11g11b10_and_wrong_sizes() { + let mut rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(is_sky_dome_target(&rd)); + + // Typeless 128x128 RGBA16 render targets are copy-compatible with R16G16B16A16_FLOAT. + rd.Format = DXGI_FORMAT_R16G16B16A16_TYPELESS; + assert!(is_sky_dome_target(&rd)); + + // Must ignore the brighter 128x128 R11G11B10_FLOAT pass to prevent frame flicker. + rd.Format = DXGI_FORMAT_R11G11B10_FLOAT; + assert!(!is_sky_dome_target(&rd)); + + rd.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + rd.Width = 256; + assert!(!is_sky_dome_target(&rd)); + + assert!(is_ambient_compute(b"ILDN\0CS_ScreenProbes_TemporalResolve\0")); + assert!(is_ambient_compute(b"ILDN\0CS_UpdateHistory_16\0")); + assert!(!is_ambient_compute(b"ILDN\0CS_CullInstances\0")); + } + + #[test] + fn dispatch_target_matching_and_sky_transfer_curve() { + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1280, + Height: 720, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + assert!(matches_dispatch_target(&rd, [160, 90, 1])); + assert!(!matches_dispatch_target(&rd, [16, 16, 1])); + + let night = sky_transfer([0.0, 0.0, 0.0], 0.55, 0.65, 0.025); + assert!((night[0] - 0.025).abs() < 1e-6); + let day = sky_transfer([1.0, 0.9, 1.2], 0.55, 0.65, 0.025); + assert!(day[2] > day[0] && day[0] > night[0]); + } + + #[test] + fn sm5_ambient_hlsl_shaders_compile_cleanly() { + assert!(compile_cs_sm5(SKY_REDUCE_HLSL).is_some(), "SKY_REDUCE_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(AMBIENT_FILL_HLSL).is_some(), "AMBIENT_FILL_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(AMBIENT_FILL_WRITE_HLSL).is_some(), "AMBIENT_FILL_WRITE_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(AMBIENT_FILL_R9G9B9E5_HLSL).is_some(), "AMBIENT_FILL_R9G9B9E5_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(REFLECT_CLAMP_HLSL).is_some(), "REFLECT_CLAMP_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(AIR_CAP_HLSL).is_some(), "AIR_CAP_HLSL failed D3DCompile"); + } + + #[test] + fn temporal_resolve_targets_r32_uint_and_never_hdr_scene_color() { + let hdr_scene = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 2560, + Height: 1440, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R11G11B10_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let r9_probe = D3D12_RESOURCE_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ..hdr_scene + }; + assert!(score_dispatch_target_for_role(PassRole::TemporalResolve, &hdr_scene, DXGI_FORMAT_R11G11B10_FLOAT.0, [320, 360, 1]).is_none()); + assert!(score_dispatch_target_for_role(PassRole::TemporalResolve, &hdr_scene, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [320, 360, 1]).is_none()); + assert!(score_dispatch_target_for_role(PassRole::TemporalResolve, &r9_probe, DXGI_FORMAT_R32_UINT.0, [320, 360, 1]).is_some()); + assert!(score_dispatch_target_for_role(PassRole::ReflectionHistory, &r9_probe, DXGI_FORMAT_R32_UINT.0, [320, 360, 1]).is_none()); + assert!(score_dispatch_target_for_role(PassRole::ReflectionHistory, &hdr_scene, DXGI_FORMAT_R11G11B10_FLOAT.0, [320, 360, 1]).is_some()); + } + + #[test] + fn inscattering_volume_classification_volume_scoring_and_time_based_settling() { + assert_eq!( + classify_cs(b"ILDN\0CS_AccumulateLocalLightInscatteringVolume\0"), + Some(PassRole::InscatteringVolume) + ); + assert!(is_ambient_compute(b"ILDN\0CS_AccumulateLocalLightInscatteringVolume_V2\0")); + + let def = Config::default(); + assert!((def.settle_ms - 250.0).abs() < 1e-6); + assert!((def.air - 0.0).abs() < 1e-6); + + // First capture or settle_ms == 0 snaps immediately; subsequent samples follow 1 - exp(-dt/tau). + assert_eq!(settle_alpha(0.016, 250.0, true), 1.0); + assert_eq!(settle_alpha(0.016, 0.0, false), 1.0); + assert_eq!(settle_alpha(0.0, 250.0, false), 0.0); + let a_frame = settle_alpha(1.0 / 60.0, 250.0, false); + let a_tau = settle_alpha(0.25, 250.0, false); + let a_long = settle_alpha(1.0, 250.0, false); + assert!(a_frame > 0.05 && a_frame < 0.08, "16.7 ms EMA step: {a_frame}"); + assert!((a_tau - (1.0 - (-1.0f32).exp())).abs() < 1e-5, "dt == tau: {a_tau}"); + assert!(a_long > a_tau && a_long < 1.0, "1 s EMA step: {a_long}"); + + // 3D froxel volume matching: accepts 3D RGBA16F and R11G11B10F UAVs, rejects 2D and wrong formats. + let vol = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D, + Width: 160, + Height: 90, + DepthOrArraySize: 64, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + assert!(score_volume_target(&vol, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [20, 12, 32]).is_some()); + assert!(score_volume_target(&vol, DXGI_FORMAT_R11G11B10_FLOAT.0, [0, 0, 0]).is_some()); + assert!(score_volume_target(&vol, DXGI_FORMAT_R32G32B32A32_FLOAT.0, [20, 12, 32]).is_none()); + let tex2d = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, ..vol }; + assert!(score_volume_target(&tex2d, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [20, 12, 1]).is_none()); + let tiny = D3D12_RESOURCE_DESC { DepthOrArraySize: 2, ..vol }; + assert!(score_volume_target(&tiny, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [20, 12, 1]).is_none()); + } + + #[test] + fn typeless_uav_indirect_dispatch_and_cpu_heap_slot_copy_resolve_cleanly() { + // Typeless resource with concrete R16G16B16A16_FLOAT UAV view must match (both direct and indirect). + let typeless = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1920, + Height: 1080, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + assert!(score_dispatch_target(&typeless, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [240, 135, 1]).is_some()); + assert!(score_dispatch_target(&typeless, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [0, 0, 0]).is_some()); + // Texture2DArray must be rejected for TEXTURE2D view creation. + let arr = D3D12_RESOURCE_DESC { DepthOrArraySize: 4, ..typeless }; + assert!(score_dispatch_target(&arr, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [240, 135, 1]).is_none()); + + // [320, 360, 1] Wave32 [8, 4, 1] / half-res probe grid matches 2560x1440, 1280x720, and 640x360. + let qhd = D3D12_RESOURCE_DESC { Width: 2560, Height: 1440, ..typeless }; + let half = D3D12_RESOURCE_DESC { Width: 640, Height: 360, ..typeless }; + assert_eq!(score_dispatch_target(&qhd, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [320, 360, 1]), Some(0)); + assert!(score_dispatch_target(&half, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [320, 360, 1]).is_some()); + + // CBV V# in a descriptor table decodes back to its buffer VA and byte size. + let cbv = crate::gpu::desc::cbv_words(0x7_1234_5600, 512); + assert_eq!(decode_cbv_vsharp(cbv), Some((0x7_1234_5600, 512))); + let img = crate::gpu::desc::xcl_image_for_view(42, 0, crate::gpu::desc::ImageType::D2, 64, 64, 1, 1); + assert_eq!(decode_cbv_vsharp([img[0], img[1], img[2], img[3]]), None); + + // Two distinct CPU-only heap slots (`global_index == 0`) at different addresses must not collide + // before being copied to the shader-visible heap. + let cpu_slot_a = 0x7F00_0000_0020usize; + let cpu_slot_b = 0x7F00_0010_0020usize; + let sv_slot_dst = 0x7F00_0020_0040usize; + let res_a = 0x7F00_AAAAusize; + let res_b = 0x7F00_BBBBusize; + note_descriptor(cpu_slot_a, 0, res_a, DXGI_FORMAT_R16G16B16A16_FLOAT.0, DXGI_FORMAT_R16G16B16A16_TYPELESS.0, true); + note_descriptor(cpu_slot_b, 0, res_b, DXGI_FORMAT_R8G8B8A8_UNORM.0, DXGI_FORMAT_R8G8B8A8_UNORM.0, false); + copy_descriptor(cpu_slot_a, 0, sv_slot_dst, 1_100_002); + { + let g = VIEW_SLOTS.read().unwrap(); + let vs = g.as_ref().unwrap(); + assert_eq!(vs.by_addr.get(&sv_slot_dst).map(|v| v.res), Some(res_a)); + assert_eq!(vs.by_idx.get(&1_100_002).map(|v| v.res), Some(res_a)); + } + forget_resource(res_a); + note_descriptor(cpu_slot_b, 0, 0, 0, 0, false); + } + + #[test] + fn scan_cbv_indices_resolves_each_64k_mirror_page_independently() { + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + // Backing page 0 sits right before a readable decoy slice; backing page 1 is separate. + let mut backing0_and_decoy = vec![0u32; 128]; + backing0_and_decoy[0] = 101_001; // sentinel in page 0 (last 256 B of GPU page 0) + backing0_and_decoy[64] = 999_999; // decoy immediately after backing 0 (must NEVER be read) + let mut backing1 = vec![0u32; 64]; + backing1[0] = 202_002; // sentinel in page 1 (first 256 B of GPU page 1) + + let gpu_page0 = 0x5000_0000usize; + let gpu_page1 = gpu_page0 + PAGE; + let cbv_start = gpu_page0 + (PAGE - 256); // 0xff00: spans 256 B on page 0 + 256 B on page 1 + let p0_base = backing0_and_decoy.as_ptr() as usize; + let p1_base = backing1.as_ptr() as usize; + + let mut seen = Vec::new(); + unsafe { + scan_cbv_indices_with( + cbv_start, + 512, + |va| { + if va >= gpu_page0 && va < gpu_page1 { + p0_base + (va - cbv_start) + } else if va >= gpu_page1 && va < gpu_page1 + 256 { + p1_base + (va - gpu_page1) + } else { + 0 + } + }, + &mut |v| seen.push(v), + ); + } + assert!(seen.contains(&101_001), "first 64 KiB page sentinel must be read"); + assert!(seen.contains(&202_002), "second 64 KiB page sentinel must be resolved independently"); + assert!(!seen.contains(&999_999), "readable decoy past backing 0 must never be read across 64 KiB boundary"); + assert_eq!(resolve_cbv_va(0), 0); + assert_eq!(resolve_cbv_va(p1_base), p1_base); + } + + #[test] + fn ambient_sky_reduce_runs_cleanly_on_gpu() { + unsafe { + if std::env::var_os("XCL_D3D12_DEBUG").is_some() { + let mut dbg: Option = None; + if D3D12GetDebugInterface(&mut dbg).is_ok() { + if let Some(d) = dbg { + d.EnableDebugLayer(); + } + } + } + let mut dev: Option = None; + if D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + return; + } + let dev = dev.unwrap(); + let dev_raw = dev.as_raw(); + real::adopt(dev_raw, real::Kind::Device); + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let list_raw = list.as_raw(); + real::adopt(list_raw, real::Kind::CommandList); + list_x::on_create(list_raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + // Create a 128x128 RGBA16F render target (sky dome) in RENDER_TARGET state. + let rt_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut rt: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rt_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut rt).unwrap(); + let rt = rt.unwrap(); + + let ad = build_device(&dev).expect("build_device must succeed"); + let sky_raw = ad.sky_copy.as_raw() as usize; + let rt0 = rt.as_raw() as usize; + list_x::transition(list_raw, rt0, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_x::transition(list_raw, sky_raw, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + list_x::pc_copy_resource(list_raw, sky_raw, rt0); + list_x::transition(list_raw, sky_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list_x::transition(list_raw, rt0, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + + let (cpu0, gpu0) = ad.alloc_group(); + let inc = ad.inc as u64; + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + let sky_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 1, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, ad.sky_copy.as_raw(), &sky_srv, cpu0 as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list_raw, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list_raw, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list_raw, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list_raw, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list_raw, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list_raw, 14)); + let consts = [0.22f32.to_bits(), 0.65f32.to_bits(), 0.02f32.to_bits(), 1.0f32.to_bits(), 0, 0, 0, 0]; + set_heaps(list_raw, 1, &heap_raw); + set_cs_rs(list_raw, ad.rs.as_raw()); + set_pso(list_raw, ad.reduce_pso.as_raw()); + set_cs_consts(list_raw, 0, 8, consts.as_ptr(), 0); + set_cs_table(list_raw, 1, gpu0); + set_cs_table(list_raw, 2, gpu0 + inc); + dispatch(list_raw, 1, 1, 1); + uav_barrier(list_raw, ad.sky_level.as_raw() as usize); + list.Close().unwrap(); + + let cl: ID3D12CommandList = list.cast().unwrap(); + q.ExecuteCommandLists(&[Some(cl)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let ev = windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap(); + q.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, ev).unwrap(); + windows::Win32::System::Threading::WaitForSingleObject(ev, 5000); + let _ = windows::Win32::Foundation::CloseHandle(ev); + assert_eq!(fence.GetCompletedValue(), 1, "ambient sky_reduce GPU dispatch must complete cleanly (device removed: {:?})", dev.GetDeviceRemovedReason()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index f2a771ee06..c084a9f6ef 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -41,6 +41,8 @@ struct State { heap_bound: bool, res_buf: Option, res_retired: Vec, + /// this recording wrote into the device's shared two-pass record buffer (`SHARED_RECORDS`) + shared_records: bool, /// rewritten indirect arguments (`scratch_args`): the block (and its bytes), its bytes in /// use, and the bytes of blocks this recording took scratch: Option<(ID3D12Resource, u64)>, @@ -68,6 +70,7 @@ struct State { /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its /// two-pass ExecuteIndirects are skipped) const SCRATCH_BLOCK: u64 = 1 << 20; +const SCRATCH_FIRST_BLOCK: u64 = 128 << 10; const SCRATCH_CAP: u64 = 16 << 20; /// Most bytes of buffers kept for reuse (`FREE_RES`) const FREE_RES_CAP: u64 = 1 << 30; @@ -214,7 +217,8 @@ fn hold_res_until_reset(allocator: usize, mut bufs: Vec) { return; } if allocator == 0 { - let over = UNKNOWN_RES.lock().unwrap().hold(std::time::Instant::now(), bufs.into_iter().map(|b| (b.bytes, b)).collect()); + let marks = super::alloc_pool::pending_gpu_marks(); + let over = UNKNOWN_RES.lock().unwrap().hold(std::time::Instant::now(), bufs.into_iter().map(|b| (b.bytes, (b, marks.clone()))).collect()); if over > 0 { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -227,14 +231,16 @@ fn hold_res_until_reset(allocator: usize, mut bufs: Vec) { } pub(super) fn release_allocator_res(allocator: usize) { - let aged = UNKNOWN_RES.lock().unwrap().take_older(std::time::Instant::now(), UNKNOWN_RES_AGE); + let aged = UNKNOWN_RES.lock().unwrap().take_ready(std::time::Instant::now(), UNKNOWN_RES_AGE, |(_, marks)| { + marks.iter().all(|(f, v)| unsafe { super::real::fence_completed(f) } >= *v) + }); let bufs = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); // (let go outside the lock) let _gone = { let mut free = FREE_RES.lock().unwrap(); let now = std::time::Instant::now(); let mut gone = free.take_idle(now, FREE_RES_IDLE); - for b in bufs.into_iter().flatten().chain(aged) { + for b in bufs.into_iter().flatten().chain(aged.into_iter().map(|(b, _)| b)) { gone.extend(free.put(now, b.bytes, b.dev, b)); } gone @@ -290,9 +296,15 @@ impl Aging { } /// What has been kept `age` or longer at `now`. + #[cfg(test)] fn take_older(&mut self, now: std::time::Instant, age: std::time::Duration) -> Vec { + self.take_ready(now, age, |_| true) + } + + /// What has been kept `age` or longer at `now` and satisfies `ready` (GPU fences completed). + fn take_ready(&mut self, now: std::time::Instant, age: std::time::Duration, mut ready: impl FnMut(&T) -> bool) -> Vec { let mut out = Vec::new(); - while self.held.front().is_some_and(|&(at, _, _)| now.saturating_duration_since(at) >= age) { + while self.held.front().is_some_and(|(at, _, item)| now.saturating_duration_since(*at) >= age && ready(item)) { let (_, b, t) = self.held.pop_front().unwrap(); self.bytes -= b; out.push(t); @@ -301,8 +313,9 @@ impl Aging { } } -/// the two-pass buffers of recordings with no known allocator (`hold_res_until_reset`) -static UNKNOWN_RES: Mutex> = Mutex::new(Aging::new(UNKNOWN_RES_CAP)); +/// the two-pass buffers of recordings with no known allocator (`hold_res_until_reset`), +/// paired with the GPU fences active when they were held so long stalls never free in-flight buffers. +static UNKNOWN_RES: Mutex)>> = Mutex::new(Aging::new(UNKNOWN_RES_CAP)); /// Buffers the GPU is done with, kept for the recordings that need one next (`FREE_RES`): each /// with when it was handed back, its bytes and its device, oldest first. What it keeps is what @@ -444,7 +457,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.rs_gfx = 0; s.heaps = [0; 2]; // (the scratch blocks are in `res_retired` already) - (s.scratch, s.scratch_used, s.scratch_taken, s.scratch_in_args, s.record_open) = (None, 0, 0, false, None); + (s.scratch, s.scratch_used, s.scratch_taken, s.scratch_in_args, s.record_open, s.shared_records) = (None, 0, 0, false, None, false); let mut res_bufs = std::mem::take(&mut s.res_retired); if let Some(b) = s.res_buf.take() { res_bufs.push(b); @@ -502,7 +515,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.heaps = heaps; // the two-pass record buffers and argument scratch of `to`'s previous recording, as in // `reset`: the GPU may still read them, so the new one takes fresh ones - (s.scratch, s.scratch_used, s.scratch_taken, s.scratch_in_args, s.record_open) = (None, 0, 0, false, None); + (s.scratch, s.scratch_used, s.scratch_taken, s.scratch_in_args, s.record_open, s.shared_records) = (None, 0, 0, false, None, false); let mut res_bufs = std::mem::take(&mut s.res_retired); if let Some(b) = s.res_buf.take() { res_bufs.push(b); @@ -1669,15 +1682,91 @@ fn record_buffer_bytes(need: u64) -> u64 { need.clamp(RECORD_MIN, RECORD_MAX).next_power_of_two() } -/// Record bytes a two-pass ExecuteIndirect asks for: `INDIRECT_RECORDS`, or less when a command's -/// groups (at most 65 535 / `split` in X, `record_groups`) need less – the same groups fit. +/// The record buffers all recordings of a device share (`XCL_TWO_PASS_SHARED=0`: one of each list, +/// kept until its allocator is reset). A retail title's world frame has more than a hundred lists +/// with two-pass draws: at 32 MiB a list the first frames made 68 of them in 4 s. A queue runs +/// its lists in order and every pass over the records ends with a UAV barrier (`emit_uav_barrier`), +/// so the next list's passes see none of it as long as all of them go to one queue +/// (`note_records_queue`). +static SHARED_RECORDS: Mutex> = Mutex::new(Vec::new()); +const SHARED_LEAST: u64 = 32 << 20; + +fn shared_records_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TWO_PASS_SHARED").map_or(true, |v| v.trim() != "0")) +} + +static RECORDS_QUEUE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static RECORDS_QUEUES_DIFFER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// `lists` go to `queue` now (`present::note_execute`): the ones that used the shared record +/// buffer must all go to one queue. +pub(super) fn note_records_queue(queue: usize, lists: &[*mut c_void]) { + if RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed) { + return; + } + let used = lists.iter().any(|&l| STATES.contains(l as usize) && with(l, |s| s.shared_records)); + if used && !same_records_queue(&RECORDS_QUEUE, queue) { + RECORDS_QUEUES_DIFFER.store(true, Ordering::Relaxed); + crate::xlog_warn!("D3D12.X: two-pass draws go to a second queue ({queue:#x}): the record buffers are the lists' own from here"); + } +} + +fn same_records_queue(seen: &std::sync::atomic::AtomicUsize, queue: usize) -> bool { + match seen.compare_exchange(0, queue, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => true, + Err(first) => first == queue, + } +} + +unsafe fn shared_record_buffer(dev: &ID3D12Device, need: u64) -> Result<(ID3D12Resource, u64), String> { + let key = dev.as_raw() as usize; + let mut all = SHARED_RECORDS.lock().unwrap(); + if let Some((buf, cap, _)) = all.iter().find(|(_, cap, d)| *d == key && *cap >= need) { + return Ok((buf.clone(), *cap)); + } + let bytes = need.max(SHARED_LEAST); + let buf = default_uav_buffer(dev, bytes, "shared two-pass record buffer")?; + all.push((buf.clone(), bytes, key)); + Ok((buf, bytes)) +} + +fn two_pass_indirect_bytes() -> u64 { + static MB: std::sync::OnceLock = std::sync::OnceLock::new(); + *MB.get_or_init(|| two_pass_list_mb(std::env::var("XCL_TWO_PASS_LIST_MB").ok().as_deref())) << 20 +} + +fn two_pass_list_mb(v: Option<&str>) -> u64 { + v.and_then(|v| v.trim().parse::().ok()).filter(|&mb| mb > 0).map_or(32, |mb| mb.min(128)) +} + +/// Record bytes a two-pass ExecuteIndirect asks for: `XCL_TWO_PASS_LIST_MB` (default 32 MiB), or +/// less when a command's groups (at most 65 535 / `split` in X, `record_groups`) need less. fn indirect_record_need(record_bytes: u64, split: u32) -> u64 { - INDIRECT_RECORDS.min(record_bytes.saturating_mul(65_535 / split.max(1) as u64)) + two_pass_indirect_bytes().min(record_bytes.saturating_mul(65_535 / split.max(1) as u64)) } /// The record buffer of this list for `need_bytes` (at most `RECORD_MAX`): buffer, address, bytes. unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64, u64), String> { let need = record_buffer_bytes(need_bytes); + { + static SAID: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()]; + let one = !RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed); + let on = shared_records_on(); + SAID[(on && one) as usize].call_once(|| { + crate::xlog_info!("D3D12.X: two-pass records: {} (switch {on}, one queue so far {one})", if on && one { "shared" } else { "a buffer of each list" }); + }); + } + if shared_records_on() && !RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed) { + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let (buf, cap) = shared_record_buffer(&dev, need)?; + let first = with(this, |s| !std::mem::replace(&mut s.shared_records, true)); + if let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this).filter(|_| first) { + emit_uav_barrier(list, None); + } + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va, cap)); + } if let Some((buf, cap)) = with(this, |s| s.res_buf.as_ref().filter(|b| b.bytes >= need).map(|b| (b.res.clone(), b.bytes))) { let va = buf.GetGPUVirtualAddress(); return Ok((buf, va, cap)); @@ -1794,7 +1883,7 @@ unsafe fn prepare_two_pass_stage(this: *mut c_void, real_mesh_pso: usize, tp: &s if pso == 0 { return Err(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" }.into()); } - let w = |k: usize| super::real::uma_window_va(k).unwrap_or(first); + let w = |k: usize| super::real::uma_window_va(k).filter(|&v| v != 0).unwrap_or(first); Ok(StageBind { rs, pso, views: [va(io_at), res_va, w(0), w(1), w(2), w(3)] }) } @@ -1813,7 +1902,10 @@ RWByteAddressBuffer cnt : register(u4); void main(uint tid : SV_DispatchThreadID) { uint count = io.Load(0), stride = io.Load(4), offset = io.Load(8), split = io.Load(12), cap = io.Load(16); if (tid >= count) return; - uint live = io.Load(28) != 0u ? min(count, cnt.Load(io.Load(32))) : count; + uint live = count; + if (io.Load(28) != 0u) { + live = min(count, cnt.Load(io.Load(32))); + } uint s = io.Load(20) + tid * stride, d = io.Load(24) + tid * stride, m = d + count * stride; for (uint i = 0u; i < stride; i += 4u) { uint w = src.Load(s + i); @@ -1832,6 +1924,68 @@ void main(uint tid : SV_DispatchThreadID) { } "#; +const SCALE_ARGS_DRED_LABEL: &str = "xcl make_scaled_args_buffer"; + +/// Align a GPU virtual address down to a 256-byte root UAV base and its 4-byte-aligned shader +/// byte offset (`RWByteAddressBuffer::Load` requires 4-byte alignment, and D3D12 root raw UAVs +/// require >= 16-byte alignment; UMA window buffers are 64 KiB-aligned so `va & !255` stays in +/// the same buffer and sparse tile). +fn align_root_uav(va: u64) -> Result<(u64, u32), String> { + if va % 4 != 0 { + return Err(format!("indirect buffer address {va:#x} is not 4-byte aligned")); + } + Ok((va & !255, (va & 255) as u32)) +} + +/// Validate `SCALE_ARGS_HLSL`'s command-buffer layout and return the source command byte span. +fn validate_scale_args_layout(max: u32, stride: u32, mesh_offset: u32) -> Result { + if max == 0 || stride == 0 || stride % 4 != 0 || mesh_offset % 4 != 0 || mesh_offset.checked_add(12).is_none_or(|end| end > stride) { + return Err(format!("invalid indirect layout (max={max}, stride={stride}, mesh_offset={mesh_offset})")); + } + let commands = (max as u64).checked_mul(stride as u64).ok_or("indirect command span overflow")?; + let total_dst = commands.checked_mul(2).ok_or("scaled indirect buffer size overflow")?; + if total_dst > u32::MAX as u64 { + return Err(format!("scaled indirect buffer ({total_dst:#x} B) exceeds 32-bit shader offsets")); + } + Ok(commands) +} + +/// Minimal compute root signature for `SCALE_ARGS_HLSL`: only the 4 root UAVs (`u0, u2, u3, u4`) +/// and no heap flags, so every root parameter is unconditionally bound before Dispatch. +unsafe fn scale_args_root_signature(dev: &ID3D12Device) -> Result { + let params: Vec = [0u32, 2, 3, 4] + .iter() + .map(|®| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: reg, + RegisterSpace: 0, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }) + .collect(); + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }, + }, + }; + let mut blob: Option = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None).map_err(|e| format!("scale args root signature serialize: {e}"))?; + let blob = blob.ok_or("scale args root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("scale args root signature create: {e}")) +} + unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { static CACHE: Mutex>> = Mutex::new(None); let key = dev.as_raw() as usize; @@ -1839,7 +1993,7 @@ unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSigna return Ok(pair); } let dxil = crate::gpu::recomp::dxc::compile_cached(SCALE_ARGS_HLSL, "main", "cs_6_6")?.0; - let rs = crate::gpu::recomp::pso::abi_root_signature(dev, false)?; + let rs = scale_args_root_signature(dev)?; let mut cdesc = 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() }, @@ -1847,7 +2001,9 @@ unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSigna }; let res_pso: Result = dev.CreateComputePipelineState(&cdesc); std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); - let pso = res_pso.map_err(|e| format!("scale pso create: {e}"))?; + let pso = res_pso.map_err(|e| format!("{SCALE_ARGS_DRED_LABEL} pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(SCALE_ARGS_DRED_LABEL)); + super::dred::label_text(pso.as_raw() as usize, || SCALE_ARGS_DRED_LABEL.to_string()); CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); Ok((rs, pso)) } @@ -1865,7 +2021,8 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res }) { return Ok(r); } - let size = bytes.max(SCRATCH_BLOCK); + let first = with(this, |s| s.scratch.is_none()); + let size = bytes.max(if first { SCRATCH_FIRST_BLOCK } else { SCRATCH_BLOCK }); let remaining = SCRATCH_CAP.saturating_sub(with(this, |s| s.scratch_taken)); if size > remaining { return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); @@ -1897,7 +2054,7 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res /// title's world, three times, each at the first such draw of a list). Without a count buffer /// u4 names the constants, which are always there. fn scale_views(consts: u64, src: u64, dst: u64, count: Option) -> [(u32, u64); 4] { - [(0, consts), (2, src), (3, dst), (4, count.unwrap_or(consts))] + [(0, consts), (1, src), (2, dst), (3, count.unwrap_or(consts))] } /// The arguments of `max` commands at UMA address `src`, rewritten for the two passes @@ -1947,28 +2104,39 @@ struct Rewrite { /// its place in a scratch block, the block and the offset. #[allow(clippy::too_many_arguments)] unsafe fn prepare_scaled_args(this: *mut c_void, src: usize, count: Option, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result<(Rewrite, ID3D12Resource, u64), String> { + if super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) { + return Err("command bundles cannot record indirect argument barriers".into()); + } + let commands = validate_scale_args_layout(max, stride, mesh_offset)?; let dev = super::real::list_device(this).ok_or("no device")?; let (rs, pso) = scale_indirect_pipeline(&dev)?; let u = crate::gpu::uma::get().ok_or("no unified memory")?; - let commands = (max as u64).saturating_mul(stride as u64); // only the GPU reads them: in a GPU view too, once its tiles are asked for want_view(super::view_want::Path::MemoryOp, src as u64, commands); super::real::uma_window_buffer_gpu(src, commands as usize).ok_or("the indirect arguments are not in one memory window")?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; - let count_va = match count { + let (src_base, src_off) = align_root_uav(src_va)?; + if (src_off as u64).checked_add(commands).is_none_or(|end| end > u32::MAX as u64) { + return Err("indirect command range exceeds 32-bit shader offsets".into()); + } + let count_bound = match count { Some(p) => { want_view(super::view_want::Path::MemoryOp, p as u64, 4); super::real::uma_window_buffer_gpu(p, 4).ok_or("the indirect count is not in a memory window")?; - Some(super::real::uma_va_of(p).ok_or("unified memory is not open on the GPU")?) + let va = super::real::uma_va_of(p).ok_or("unified memory is not open on the GPU")?; + Some(align_root_uav(va)?) } None => None, }; let (dst, dst_off) = scratch_args(this, &dev, commands.saturating_mul(2))?; - let consts: Vec = [max, stride, mesh_offset, split, cap, 0, 0, count_va.is_some() as u32, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let consts: Vec = [max, stride, mesh_offset, split, cap, src_off, 0, count_bound.is_some() as u32, count_bound.map_or(0, |(_, off)| off)] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; - let views = scale_views(consts_va, src_va, dst.GetGPUVirtualAddress() + dst_off, count_va); + let views = scale_views(consts_va, src_base, dst.GetGPUVirtualAddress() + dst_off, count_bound.map(|(base, _)| base)); // (the pair is the device's for good: `scale_indirect_pipeline` keeps it) Ok((Rewrite { rs: rs.as_raw() as usize, pso: pso.as_raw() as usize, views, groups: max.div_ceil(64) }, dst, dst_off)) } @@ -2404,6 +2572,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us (None, None) => fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)), } super::gpu_profile::end(this, t); + if compute && super::ambient::has_compute_psos() { + let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, pso, [0, 0, 0], layout.as_deref(), &args, view_heap); + } } Err(e) => { ei_work(this, sig, super::targets::SKIPPED); @@ -2569,12 +2741,17 @@ pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: let _c = capture_work(this, || super::capture::WorkKind::Draw { vertices, instances, first_vertex, first_instance }, true); DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some(list) = graphics_bound(this) { - let t = super::gpu_profile::begin(this, with(this, |s| s.pso), super::gpu_profile::Kind::Draw, [vertices, instances, 0]); + let bound_pso = with(this, |s| s.pso); + let t = super::gpu_profile::begin(this, bound_pso, super::gpu_profile::Kind::Draw, [vertices, instances, 0]); if !draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); list.DrawInstanced(vertices, instances, first_vertex, first_instance); } super::gpu_profile::end(this, t); + if super::ambient::has_sky_psos() { + let pso = super::pso_async::resolve(bound_pso); + super::ambient::after_draw(this, pso); + } } } @@ -2589,6 +2766,10 @@ pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, i if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); + if super::ambient::has_sky_psos() { + let pso = super::pso_async::resolve(with(this, |s| s.pso)); + super::ambient::after_draw(this, pso); + } } } @@ -3094,8 +3275,28 @@ fn note_thread_dimensions(threads: [u32; 3], groups: [u32; 3], shape: [u32; 3]) } } +/// Whether the BVH builder's passes (`DispatchX` with `DISPATCH_THREAD_DIMENSIONS`, the title's +/// `XboxBvhBuilder.dll`) run: off unless `XCL_BVH_BUILDER=1`. While its 52 pipelines compile one +/// by one, partial runs write garbage bounds/pointers into title memory and crash or hang world load. +fn bvh_builder_runs(flags: u32, enabled: bool) -> bool { + flags & DISPATCH_THREAD_DIMENSIONS == 0 || enabled +} + +fn bvh_builder_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_BVH_BUILDER").is_ok_and(|v| v.trim() == "1")) +} + /// `Dispatch` / `DispatchX(x, y, z, flags)`. pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + if !bvh_builder_runs(flags, bvh_builder_enabled()) { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: BVH builder pass left out ({n} so far; XCL_BVH_BUILDER=1 runs them)"); + } + return; + } let pso = with(this, |s| s.pso); let _c = capture_work(this, || captured_dispatch(pso, [x, y, z], flags), false); // (recorded at the submit through this call, with everything below: counted there) @@ -3145,7 +3346,13 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f 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), + Ok(()) => { + count(DISPATCHES); + if super::ambient::has_compute_psos() { + let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, pso, groups, layout.as_deref(), &args, view_heap); + } + } Err(e) => { count(DISPATCHES_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -3488,6 +3695,19 @@ pub(super) fn counts_snapshot() -> [u64; 5] { std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) } +/// Tracked console `(graphics_root_signature, compute_root_signature)` on `list` for restoring +/// PC root signatures after an internal graphics/compute sync pass (invalidating cached view heap +/// binding state since the internal pass clobbered descriptor heaps / root signatures). +pub(super) fn tracked_root_sigs(list: *mut c_void) -> (usize, usize) { + if !STATES.contains(list as usize) { + return (0, 0); + } + with(list, |s| { + s.heap_bound = false; + (s.rs_gfx, 0) + }) +} + #[cfg(test)] pub(super) fn tracked_pso(list: *mut c_void) -> usize { if STATES.contains(list as usize) { with(list, |s| s.pso) } else { 0 } @@ -4120,7 +4340,7 @@ void main(uint t : SV_GroupIndex) { } let buf = TwoPassBuf::make(&dev.unwrap(), 1 << 16, "test").unwrap(); let raw = buf.res.as_raw() as usize; - let kept = |r: usize| UNKNOWN_RES.lock().unwrap().held.iter().any(|h| h.2.res.as_raw() as usize == r); + let kept = |r: usize| UNKNOWN_RES.lock().unwrap().held.iter().any(|h| h.2.0.res.as_raw() as usize == r); hold_res_until_reset(0, vec![buf]); assert!(kept(raw), "a buffer of a recording with no allocator is kept"); } @@ -4757,10 +4977,14 @@ void main(uint t : SV_GroupIndex) { } assert!(!SCALE_ARGS_HLSL.contains("register(u1)") && !SCALE_ARGS_HLSL.contains("register(u5)")); let with_count = scale_views(0x1000, 0x2000, 0x3000, Some(0x4000)); - assert_eq!(with_count, [(0, 0x1000), (2, 0x2000), (3, 0x3000), (4, 0x4000)]); + assert_eq!(with_count, [(0, 0x1000), (1, 0x2000), (2, 0x3000), (3, 0x4000)]); let without = scale_views(0x1000, 0x2000, 0x3000, None); - assert_eq!(without, [(0, 0x1000), (2, 0x2000), (3, 0x3000), (4, 0x1000)]); + assert_eq!(without, [(0, 0x1000), (1, 0x2000), (2, 0x3000), (3, 0x1000)]); assert!(without.iter().all(|&(_, va)| va != 0)); + assert_eq!(align_root_uav(0x1_0000_000c).unwrap(), (0x1_0000_0000, 12)); + assert!(align_root_uav(0x1_0000_0002).is_err()); + assert_eq!(validate_scale_args_layout(4, 16, 4).unwrap(), 64); + assert!(validate_scale_args_layout(1, 16, 8).is_err()); } /// `SCALE_ARGS_HLSL` on `commands` (dwords each, the DispatchMesh argument at dword 1): diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index a7319c1b40..ff6e744836 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -861,6 +861,9 @@ pub fn copy_words(src: &Slot, dst: &Slot) { write(dst, &w[..n]); if !src.sampler { note_resource(dst, resource_at(src.at).unwrap_or(0)); + let src_idx = if src.shared_srv != 0 { src.index } else { 0 }; + let dst_idx = if dst.shared_srv != 0 { dst.index } else { 0 }; + super::ambient::copy_descriptor(src.at, src_idx, dst.at, dst_idx); } } diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index d2a60e5c1b..5f750bf5be 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -26,10 +26,14 @@ use std::collections::HashMap; use std::ffi::c_void; +use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; -use windows::core::Interface; +use windows::core::{Interface, PCSTR}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -93,8 +97,18 @@ struct Inner { made_in: Option, /// [depth, stencil] twins: [Option; 2], + /// cached (DSV heap, shader-visible SRV/UAV heap) per depth resource object for R24G8 fullscreen/CS sync + pass_heaps: HashMap, } +struct PassHeaps { + dsv: ID3D12DescriptorHeap, + srv_uav: ID3D12DescriptorHeap, +} + +unsafe impl Send for PassHeaps {} +unsafe impl Sync for PassHeaps {} + /// A plane's twin: a colour texture of the plane's size with unordered access, resting in /// UNORDERED_ACCESS. struct Twin { @@ -273,7 +287,9 @@ pub(super) fn forget(res: usize) { } let Some(o) = OBJECTS.remove(res) else { return }; REGISTERED.fetch_sub(1, Ordering::Relaxed); + let dropped_heaps = o.cell.inner.lock().unwrap().pass_heaps.remove(&res); let gone = CELLS.lock().unwrap().as_mut().map(|cells| leave(cells, &o.cell)); + drop(dropped_heaps); drop(gone); } @@ -328,8 +344,7 @@ pub(super) unsafe fn resolve_uav(dev: *mut c_void, res: *mut c_void, rd: Option< } } let stencil = stencil_view(view); - // (a D24S8's depth plane: no UAV format holds it as a shader reads it) - if if stencil { !matches!(key.format, 19 | 44) } else { !matches!(key.format, 19 | 39 | 53) } { + if if stencil { !matches!(key.format, 19 | 44) } else { !matches!(key.format, 19 | 39 | 44 | 53) } { return Resolve::Null("its depth plane has no twin yet"); } // (its states stay the title's: the twin would never be copied) @@ -339,7 +354,14 @@ pub(super) unsafe fn resolve_uav(dev: *mut c_void, res: *mut c_void, rd: Option< // (the Cell holds the twin) let Some((twin, _)) = plane_twin(&o, stencil as usize, dev) else { return Resolve::Null("the twin could not be made") }; REDIRECTED.fetch_add(1, Ordering::Relaxed); - Resolve::Twin(twin.as_raw(), if stencil { twin_view(view, key.array) } else { depth_twin_view(view, key.array, key.format == 53) }) + let r16 = is_r16_depth(key.format, o.cell.console_format); + Resolve::Twin(twin.as_raw(), if stencil { twin_view(view, key.array) } else { depth_twin_view(view, key.array, r16) }) +} + +/// True when the depth plane's twin is 16-bit (`R16_TYPELESS`): PC D16 (`53`) or console +/// `D16_UNORM_S8_UINT` (`118..=120`) backed by PC `R24G8_TYPELESS` (`44`). +fn is_r16_depth(format: u32, console_format: u32) -> bool { + format == 53 || (format == 44 && matches!(console_format, 118..=120)) } /// The twin of `plane` (0 depth, 1 stencil) of the buffer `o` is in, and its number: the one it @@ -350,7 +372,7 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D if let Some(t) = &inner.twins[plane] { return Some((t.res.clone(), t.n)); } - let t = make_twin(dev, &key, twin_format(key.format, plane))?; + let t = make_twin(dev, &key, twin_format(key.format, o.cell.console_format, plane))?; TWINS.fetch_add(1, Ordering::Relaxed); let n = MADE.fetch_add(1, Ordering::Relaxed) + 1; inner.twins[plane] = Some(Twin { res: t.clone(), n }); @@ -378,7 +400,7 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D key.format, o.cell.console_format, key.at, - if key.format == 53 { 16 } else { 32 }, + if is_r16_depth(key.format, o.cell.console_format) { 16 } else { 32 }, state ); } @@ -386,12 +408,12 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D Some((t, n)) } -/// The format of the twin of `plane` of a buffer of the PC format `format`: R8 for the stencil -/// plane, R16 for D16's depth, R32 for D32's and D32S8's (the plane copies as R32_TYPELESS). -fn twin_format(format: u32, plane: usize) -> DXGI_FORMAT { +/// The format of the twin of `plane` of a buffer of the PC format `format` (and `console_format`): +/// R8 for stencil, R16 for D16 and console D16S8 (`118..=120`), R32 for D32, D32S8, and D24S8. +fn twin_format(format: u32, console_format: u32, plane: usize) -> DXGI_FORMAT { match (plane, format) { (1, _) => DXGI_FORMAT_R8_TYPELESS, - (_, 53) => DXGI_FORMAT_R16_TYPELESS, + (0, f) if is_r16_depth(f, console_format) => DXGI_FORMAT_R16_TYPELESS, _ => DXGI_FORMAT_R32_TYPELESS, } } @@ -399,9 +421,11 @@ fn twin_format(format: u32, plane: usize) -> DXGI_FORMAT { /// Where a buffer whose depth plane can have a twin rests while the title has it in /// UNORDERED_ACCESS: COPY_SOURCE, the state the plane is copied into the twin from. pub(super) const PARK: u32 = 0x800; -/// D3D12_RESOURCE_STATE_UNORDERED_ACCESS, COPY_DEST +/// D3D12_RESOURCE_STATE_UNORDERED_ACCESS, DEPTH_WRITE, COPY_DEST const UNORDERED_ACCESS: u32 = 0x8; +const DEPTH_WRITE_STATE: u32 = 0x10; const COPY_DEST: u32 = 0x400; +const SRV_ALL: u32 = 0x40 | 0x80; /// The states in which nothing writes a depth plane: DEPTH_READ, NON_PIXEL_SHADER_RESOURCE, /// PIXEL_SHADER_RESOURCE, INDIRECT_ARGUMENT, COPY_SOURCE, RESOLVE_SOURCE (and their sums). const READ_ONLY: u32 = 0x20 | 0x40 | 0x80 | 0x200 | 0x800 | 0x2000; @@ -418,23 +442,30 @@ pub(super) struct PlaneCopy { /// the depth plane's subresources it copies (the twin's have the same numbers) pub subs: Vec, pub twin: ID3D12Resource, + /// Some(steps) for `R24G8_TYPELESS` fullscreen/CS sync (`steps == true` for console D16S8 `118..=120`), + /// None for direct `CopyTextureRegion` (`D32`, `D16`, `D32S8`). + pub r24g8_steps: Option, + pub width: u32, + pub height: u32, + pub array: u16, + pub mips: u16, } /// What goes on the PC list with a title's barriers (`plan_barriers`). #[derive(Default)] pub(super) struct Plan { - /// before them: twins into depth planes (the buffer goes PARK → COPY_DEST, the title's - /// transition takes it on from COPY_DEST; the twin UNORDERED_ACCESS → COPY_SOURCE and back) + /// before them: twins into depth planes (the buffer goes PARK → COPY_DEST / DEPTH_WRITE, the + /// title's transition takes it on from there; the twin UNORDERED_ACCESS → COPY_SOURCE/SRV and back) pub to_plane: Vec, /// after them: depth planes into twins (the buffer rests in PARK; the twin - /// UNORDERED_ACCESS → COPY_DEST and back) + /// UNORDERED_ACCESS → COPY_DEST and back, or CS UAV write for R24G8) pub to_twin: Vec, } -/// Whether the depth plane of `o`'s buffer can have a twin: a D32, D16 or D32S8 buffer, and the -/// object was not made in UNORDERED_ACCESS (that object's states stay the title's). +/// Whether the depth plane of `o`'s buffer can have a twin: a D32, D16, D32S8 or D24S8/D16S8 +/// buffer, and the object was not made in UNORDERED_ACCESS (that object's states stay the title's). fn plane_twinnable(o: &Object) -> bool { - matches!(o.cell.key.format, 19 | 39 | 53) && o.state & UNORDERED_ACCESS == 0 + matches!(o.cell.key.format, 19 | 39 | 44 | 53) && o.state & UNORDERED_ACCESS == 0 } /// The title's barriers `barriers` (PC D3D12_RESOURCE_BARRIERs as words, the console's bits @@ -498,13 +529,15 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, crate::xlog_warn!("D3D12.X: a buffer with a depth UAV twin goes into or out of UNORDERED_ACCESS on a compute or copy list: the twin is not copied there"); } } + let key = o.cell.key; + let r24g8_steps = (key.format == 44).then(|| matches!(o.cell.console_format, 118..=120)); if leaving { before = PARK; // (a twin whose last way in was not copied holds something else than the plane: not // copied back – what the shaders wrote into it is lost, as without a twin) let t = (direct && !subs.is_empty()).then(|| twin_if_made(&o)).flatten(); if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed)) { - before = COPY_DEST; + before = if r24g8_steps.is_some() { DEPTH_WRITE_STATE } else { COPY_DEST }; let c = TO_PLANE.fetch_add(1, Ordering::Relaxed) + 1; if c <= 4 || c.is_power_of_two() { crate::xlog_info!("D3D12.X: depth UAV twin #{k}: the title moves depth buffer {res:#x} out of UNORDERED_ACCESS into state {after:#x}: the twin is copied into its depth plane first ({c} such copies so far)"); @@ -512,7 +545,17 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, if subs.len() as u32 == n && !in_step.contains(&id) { in_step.push(id); } - plan.to_plane.push(PlaneCopy { depth: res, sub, subs: subs.clone(), twin: t }); + plan.to_plane.push(PlaneCopy { + depth: res, + sub, + subs: subs.clone(), + twin: t, + r24g8_steps, + width: key.width, + height: key.height, + array: key.array.max(1), + mips: key.mips.max(1), + }); } if writes(after) { in_step.retain(|&c| c != id); @@ -539,7 +582,17 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, in_step.push(id); } entered.store(true, Ordering::Relaxed); - plan.to_twin.push(PlaneCopy { depth: res, sub, subs, twin: t }); + plan.to_twin.push(PlaneCopy { + depth: res, + sub, + subs, + twin: t, + r24g8_steps, + width: key.width, + height: key.height, + array: key.array.max(1), + mips: key.mips.max(1), + }); } else { entered.store(false, Ordering::Relaxed); } @@ -559,6 +612,403 @@ fn twin_if_made(o: &Object) -> Option<(ID3D12Resource, u64)> { o.cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n)) } +struct SyncPipelines { + gfx_rs: ID3D12RootSignature, + gfx_pso: ID3D12PipelineState, + gfx_pso_steps: ID3D12PipelineState, + cs_rs: ID3D12RootSignature, + cs_pso: ID3D12PipelineState, +} + +unsafe impl Send for SyncPipelines {} +unsafe impl Sync for SyncPipelines {} + +static SYNC_PIPELINES: Mutex>>> = Mutex::new(None); + +fn compile_sm5(src: &str, target: &str) -> Option> { + unsafe { + let mut blob = None; + let t = format!("{target}\0"); + let r = D3DCompile( + src.as_ptr() as *const c_void, + src.len(), + PCSTR::null(), + None, + None, + PCSTR(b"main\0".as_ptr()), + PCSTR(t.as_ptr()), + 0, + 0, + &mut blob, + None, + ); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +unsafe fn build_sync_pipelines(dev: &ID3D12Device) -> Option { + let vs = compile_sm5( + "float4 main(uint id : SV_VertexID) : SV_Position {\n\ + float2 p = float2((id == 2) ? 3.0 : -1.0, (id == 1) ? 3.0 : -1.0);\n\ + return float4(p, 0.0, 1.0);\n\ + }\n", + "vs_5_0", + )?; + let ps = compile_sm5( + "Texture2DArray src : register(t0);\n\ + cbuffer C : register(b0) { uint slice; uint mip; };\n\ + float main(float4 pos : SV_Position) : SV_Depth {\n\ + return src.Load(int4(int2(pos.xy), int(slice), int(mip)));\n\ + }\n", + "ps_5_0", + )?; + // Console D16_UNORM_S8_UINT (118..=120): read R16_TYPELESS twin as R16_UINT and multiply by + // asfloat(0x37800080) so 24-bit depth matches tiled-lighting DepthFunc = EQUAL vertex shaders + // bit-for-bit on AMD RDNA4. + let ps_steps = compile_sm5( + "Texture2DArray src : register(t0);\n\ + cbuffer C : register(b0) { uint slice; uint mip; };\n\ + float main(float4 pos : SV_Position) : SV_Depth {\n\ + return float(src.Load(int4(int2(pos.xy), int(slice), int(mip)))) * asfloat(0x37800080);\n\ + }\n", + "ps_5_0", + )?; + let cs = compile_sm5( + "Texture2DArray src : register(t0);\n\ + RWTexture2DArray dst : register(u0);\n\ + cbuffer C : register(b0) { uint w; uint h; uint slices; uint mip; };\n\ + [numthreads(8, 8, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + if (id.x < w && id.y < h && id.z < slices) {\n\ + dst[id] = src.Load(int4(int3(id), int(mip)));\n\ + }\n\ + }\n", + "cs_5_0", + )?; + + let srv_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let dev_raw = dev.as_raw(); + type CreateRsFn = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_rs: CreateRsFn = std::mem::transmute(super::real::orig_fn(dev_raw, 16)); + + let gfx_params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 2 } }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range } }, + }, + ]; + let mut blob = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC { NumParameters: gfx_params.len() as u32, pParameters: gfx_params.as_ptr(), ..Default::default() }, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).ok()?; + let blob = blob?; + let mut gfx_rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, blob.GetBufferPointer(), blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const _, &mut gfx_rs_raw) < 0 || gfx_rs_raw.is_null() { + return None; + } + let gfx_rs = ID3D12RootSignature::from_raw(gfx_rs_raw); + + let cs_params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 } }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range } }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &uav_range } }, + }, + ]; + let mut cs_blob = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC { NumParameters: cs_params.len() as u32, pParameters: cs_params.as_ptr(), ..Default::default() }, D3D_ROOT_SIGNATURE_VERSION_1, &mut cs_blob, None).ok()?; + let cs_blob = cs_blob?; + let mut cs_rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, cs_blob.GetBufferPointer(), cs_blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const _, &mut cs_rs_raw) < 0 || cs_rs_raw.is_null() { + return None; + } + let cs_rs = ID3D12RootSignature::from_raw(cs_rs_raw); + + let mut gfx_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(gfx_rs.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const c_void, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as *const c_void, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: false.into(), ..Default::default() }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { DepthEnable: true.into(), DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, StencilEnable: false.into(), ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 0, + DSVFormat: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + type CreateGfxPsoFn = unsafe extern "system" fn(*mut c_void, *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_gfx: CreateGfxPsoFn = std::mem::transmute(super::real::orig_fn(dev_raw, 10)); + let mut gfx_pso_raw = std::ptr::null_mut(); + if create_gfx(dev_raw, &gfx_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut gfx_pso_raw) < 0 || gfx_pso_raw.is_null() { + ManuallyDrop::drop(&mut gfx_desc.pRootSignature); + return None; + } + let gfx_pso = ID3D12PipelineState::from_raw(gfx_pso_raw); + let _ = gfx_pso.SetName(&windows::core::HSTRING::from("xcl depth_uav r24g8 sync gfx")); + + gfx_desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps_steps.as_ptr() as *const c_void, BytecodeLength: ps_steps.len() }; + let mut gfx_pso_steps_raw = std::ptr::null_mut(); + let hr_steps = create_gfx(dev_raw, &gfx_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut gfx_pso_steps_raw); + ManuallyDrop::drop(&mut gfx_desc.pRootSignature); + if hr_steps < 0 || gfx_pso_steps_raw.is_null() { + return None; + } + let gfx_pso_steps = ID3D12PipelineState::from_raw(gfx_pso_steps_raw); + let _ = gfx_pso_steps.SetName(&windows::core::HSTRING::from("xcl depth_uav r24g8 sync gfx steps")); + + let mut cs_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(cs_rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + ..Default::default() + }; + type CreateCsPsoFn = unsafe extern "system" fn(*mut c_void, *const D3D12_COMPUTE_PIPELINE_STATE_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_cs: CreateCsPsoFn = std::mem::transmute(super::real::orig_fn(dev_raw, 11)); + let mut cs_pso_raw = std::ptr::null_mut(); + let hr_cs = create_cs(dev_raw, &cs_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut cs_pso_raw); + ManuallyDrop::drop(&mut cs_desc.pRootSignature); + if hr_cs < 0 || cs_pso_raw.is_null() { + return None; + } + let cs_pso = ID3D12PipelineState::from_raw(cs_pso_raw); + let _ = cs_pso.SetName(&windows::core::HSTRING::from("xcl depth_uav r24g8 sync cs")); + + Some(SyncPipelines { gfx_rs, gfx_pso, gfx_pso_steps, cs_rs, cs_pso }) +} + +unsafe fn get_sync_pipelines(dev: &ID3D12Device) -> Option<(ID3D12RootSignature, ID3D12PipelineState, ID3D12PipelineState, ID3D12RootSignature, ID3D12PipelineState)> { + let key = dev.as_raw() as usize; + let mut g = SYNC_PIPELINES.lock().unwrap(); + let p = g.get_or_insert_with(HashMap::new).entry(key).or_insert_with(|| build_sync_pipelines(dev)).as_ref()?; + Some((p.gfx_rs.clone(), p.gfx_pso.clone(), p.gfx_pso_steps.clone(), p.cs_rs.clone(), p.cs_pso.clone())) +} + +unsafe fn ensure_pass_heaps(dev: &ID3D12Device, copy: &PlaneCopy, steps: bool) -> Option<(ID3D12DescriptorHeap, ID3D12DescriptorHeap)> { + let o = OBJECTS.get(copy.depth)?; + { + let inner = o.cell.inner.lock().unwrap(); + if let Some(h) = inner.pass_heaps.get(©.depth) { + return Some((h.dsv.clone(), h.srv_uav.clone())); + } + } + let dev_raw = dev.as_raw(); + type CreateHeapFn = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + type CreateDsvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, usize); + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_heap: CreateHeapFn = std::mem::transmute(super::real::orig_fn(dev_raw, 14)); + let inc_size: IncSizeFn = std::mem::transmute(super::real::orig_fn(dev_raw, 15)); + let create_srv: CreateSrvFn = std::mem::transmute(super::real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(super::real::orig_fn(dev_raw, 19)); + let create_dsv: CreateDsvFn = std::mem::transmute(super::real::orig_fn(dev_raw, 21)); + + let mips = copy.mips.max(1) as u32; + let slices = copy.array.max(1) as u32; + let depth_raw = copy.depth as *mut c_void; + + let dsv_desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, NumDescriptors: mips * slices, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0 }; + let mut dsv_raw = std::ptr::null_mut(); + if create_heap(dev_raw, &dsv_desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut dsv_raw) < 0 || dsv_raw.is_null() { + return None; + } + let dsv_heap = ID3D12DescriptorHeap::from_raw(dsv_raw); + let dsv_inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let dsv_base = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + for m in 0..mips { + for a in 0..slices { + let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D24_UNORM_S8_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Flags: D3D12_DSV_FLAG_NONE, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_DSV { MipSlice: m, FirstArraySlice: a, ArraySize: 1 } }, + }; + create_dsv(dev_raw, depth_raw, &dsv, dsv_base + ((m * slices + a) as usize) * dsv_inc); + } + } + + let srv_desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: 2 + mips, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; + let mut srv_raw = std::ptr::null_mut(); + if create_heap(dev_raw, &srv_desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut srv_raw) < 0 || srv_raw.is_null() { + return None; + } + let srv_heap = ID3D12DescriptorHeap::from_raw(srv_raw); + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let base = srv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let twin_srv_fmt = if steps { DXGI_FORMAT_R16_UINT } else { DXGI_FORMAT_R32_FLOAT }; + let twin_uav_fmt = if steps { DXGI_FORMAT_R16_UNORM } else { DXGI_FORMAT_R32_FLOAT }; + let twin_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: twin_srv_fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: mips, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + }; + create_srv(dev_raw, copy.twin.as_raw(), &twin_srv, base); + let depth_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: mips, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + }; + create_srv(dev_raw, depth_raw, &depth_srv, base + inc); + for m in 0..mips { + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: twin_uav_fmt, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: m, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0 } }, + }; + create_uav(dev_raw, copy.twin.as_raw(), std::ptr::null_mut(), &uav, base + (2 + m as usize) * inc); + } + + let mut inner = o.cell.inner.lock().unwrap(); + let h = inner.pass_heaps.entry(copy.depth).or_insert(PassHeaps { dsv: dsv_heap, srv_uav: srv_heap }); + Some((h.dsv.clone(), h.srv_uav.clone())) +} + +/// Synchronize an `R24G8_TYPELESS` depth plane with its `R16_TYPELESS` (`steps == true`, console +/// D16S8 `118..=120`) or `R32_TYPELESS` twin on a DIRECT list: fullscreen depth write for +/// `Twin -> Depth` (`to_twin == false`) and compute readback for `Depth -> Twin` (`to_twin == true`). +/// Returns `(clobbered_gfx, clobbered_cs)`. +pub(super) unsafe fn execute_r24g8_copy(list: *mut c_void, copy: &PlaneCopy, steps: bool, to_twin: bool) -> (bool, bool) { + let barriers = |b: &[[u32; 8]]| { + let f: unsafe extern "system" fn(*mut c_void, u32, *const [u32; 8]) = std::mem::transmute(super::real::orig_fn(list, 26)); + f(list, b.len() as u32, b.as_ptr()); + }; + let tr = |res: usize, sub: u32, before: u32, after: u32| [0, 0, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0]; + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + + let Some(dev) = super::real::list_device(list) else { + if !to_twin { + barriers(&[tr(copy.depth, copy.sub, PARK, DEPTH_WRITE_STATE)]); + } + return (false, false); + }; + let Some((gfx_rs, gfx_pso, gfx_pso_steps, cs_rs, cs_pso)) = get_sync_pipelines(&dev) else { + if !to_twin { + barriers(&[tr(copy.depth, copy.sub, PARK, DEPTH_WRITE_STATE)]); + } + return (false, false); + }; + let Some((dsv_heap, srv_heap)) = ensure_pass_heaps(&dev, copy, steps) else { + if !to_twin { + barriers(&[tr(copy.depth, copy.sub, PARK, DEPTH_WRITE_STATE)]); + } + return (false, false); + }; + let dev_raw = dev.as_raw(); + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + let inc_size: IncSizeFn = std::mem::transmute(super::real::orig_fn(dev_raw, 15)); + let twin_raw = copy.twin.as_raw() as usize; + let srv_raw = srv_heap.as_raw() as usize; + let mips_u32 = copy.mips.max(1) as u32; + let slices_u32 = copy.array.max(1) as u32; + + if !to_twin { + barriers(&[tr(twin_raw, all, UNORDERED_ACCESS, SRV_ALL), tr(copy.depth, copy.sub, PARK, DEPTH_WRITE_STATE)]); + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(super::real::orig_fn(list, 28)); + let set_gfx_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(super::real::orig_fn(list, 30)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(super::real::orig_fn(list, 25)); + let set_topo: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(super::real::orig_fn(list, 20)); + let set_gfx_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(super::real::orig_fn(list, 32)); + let set_vp: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(super::real::orig_fn(list, 21)); + let set_sc: unsafe extern "system" fn(*mut c_void, u32, *const RECT) = std::mem::transmute(super::real::orig_fn(list, 22)); + let set_rt: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(super::real::orig_fn(list, 46)); + let set_gfx_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(super::real::orig_fn(list, 36)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(super::real::orig_fn(list, 12)); + + set_heaps(list, 1, &srv_raw); + set_gfx_rs(list, gfx_rs.as_raw()); + set_pso(list, if steps { gfx_pso_steps.as_raw() } else { gfx_pso.as_raw() }); + set_topo(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + set_gfx_table(list, 1, srv_heap.GetGPUDescriptorHandleForHeapStart().ptr); + let dsv_base = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let dsv_inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + for &k in ©.subs { + let m = k % mips_u32; + let a = k / mips_u32; + let mw = (copy.width >> m).max(1); + let mh = (copy.height >> m).max(1); + let vp = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: mw as f32, Height: mh as f32, MinDepth: 0.0, MaxDepth: 1.0 }; + let sc = RECT { left: 0, top: 0, right: mw as i32, bottom: mh as i32 }; + set_vp(list, 1, &vp); + set_sc(list, 1, &sc); + let dsv = dsv_base + ((m * slices_u32 + a) as usize) * dsv_inc; + set_rt(list, 0, std::ptr::null(), 0, &dsv); + let c = [a, m]; + set_gfx_consts(list, 0, 2, c.as_ptr(), 0); + draw(list, 3, 1, 0, 0); + } + barriers(&[tr(twin_raw, all, SRV_ALL, UNORDERED_ACCESS)]); + (true, false) + } else { + barriers(&[tr(copy.depth, copy.sub, PARK, SRV_ALL)]); + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(super::real::orig_fn(list, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(super::real::orig_fn(list, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(super::real::orig_fn(list, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(super::real::orig_fn(list, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(super::real::orig_fn(list, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(super::real::orig_fn(list, 14)); + + set_heaps(list, 1, &srv_raw); + set_cs_rs(list, cs_rs.as_raw()); + set_pso(list, cs_pso.as_raw()); + let gpu_base = srv_heap.GetGPUDescriptorHandleForHeapStart().ptr; + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as u64; + set_cs_table(list, 1, gpu_base + inc); + let mut dispatched = vec![false; mips_u32 as usize]; + for &k in ©.subs { + let m = k % mips_u32; + if dispatched[m as usize] { + continue; + } + dispatched[m as usize] = true; + let mw = (copy.width >> m).max(1); + let mh = (copy.height >> m).max(1); + let c = [mw, mh, slices_u32, m]; + set_cs_consts(list, 0, 4, c.as_ptr(), 0); + set_cs_table(list, 2, gpu_base + (2 + m as u64) * inc); + dispatch(list, mw.div_ceil(8), mh.div_ceil(8), slices_u32); + } + let uav_barrier = [2u32, 0, twin_raw as u32, (twin_raw as u64 >> 32) as u32, 0, 0, 0, 0]; + barriers(&[uav_barrier, tr(copy.depth, copy.sub, SRV_ALL, PARK)]); + (false, true) + } +} + /// A UAV of a depth buffer stays a null view (`Resolve::Null`). pub(super) fn null_view(why: &'static str) { #[cfg(test)] @@ -1138,9 +1588,25 @@ mod tests { #[test] fn a_depth_view_is_a_view_of_a_twin_of_the_planes_size() { assert_eq!( - [twin_format(39, 0), twin_format(19, 0), twin_format(53, 0), twin_format(44, 1), twin_format(19, 1)], - [DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_TYPELESS], - "D32, D32S8, D16 depth; stencil" + [ + twin_format(39, 40, 0), + twin_format(19, 20, 0), + twin_format(53, 55, 0), + twin_format(44, 118, 0), + twin_format(44, 45, 0), + twin_format(44, 45, 1), + twin_format(19, 20, 1), + ], + [ + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R16_TYPELESS, + DXGI_FORMAT_R16_TYPELESS, + DXGI_FORMAT_R32_TYPELESS, + DXGI_FORMAT_R8_TYPELESS, + DXGI_FORMAT_R8_TYPELESS, + ], + "D32, D32S8, D16, console D16S8, D24S8 depth; stencil" ); // an R32 twin: the depth as a float unless the title asked for another R32 class for (asked, got) in [ @@ -1188,12 +1654,13 @@ mod tests { ..Default::default() }; let base = 0x7B30_0000_1000usize; - // console D32, D16, D32S8, D24S8; the PC formats of the buffers; the views of their depth + // console D32, D16, D32S8, D24S8, D16S8; the PC formats of the buffers; the views of their depth for (k, (console, pc, view, on)) in [ (40u32, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_R32_FLOAT, "the twin could not be made"), (55, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, "the twin could not be made"), (20, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, "the twin could not be made"), - (45, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, "its depth plane has no twin yet"), + (45, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, "the twin could not be made"), + (118, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_R16_UNORM, "the twin could not be made"), ] .into_iter() .enumerate() @@ -1369,12 +1836,21 @@ mod tests { assert_eq!(plan(tr(res, 1, DEPTH_WRITE, UA)), (vec![tr(res, 1, DEPTH_WRITE, PARK)], vec![(res, 1, vec![1], tw)])); assert_eq!(plan(tr(res, 2, DEPTH_WRITE, UA)), (vec![tr(res, 2, DEPTH_WRITE, PARK)], vec![]), "a stencil subresource: parked, not copied"); - // a D24S8 (its depth plane has no twin), an object made in UNORDERED_ACCESS, one XCL does - // not keep, a UAV barrier: as they came - assert!(register(d24, &desc(3, 64, 64, 45, 1, 6), None, DEPTH_WRITE)); + // a D24S8/D16S8 now parks and syncs via fullscreen/CS pass + assert!(register(d24, &desc(3, 64, 64, 118, 1, 6), None, DEPTH_WRITE)); + let t24 = stand_in(); + plant_depth_twin(d24, &t24); + assert_eq!(plan(tr(d24, ALL, DEPTH_WRITE, UA)), (vec![tr(d24, ALL, DEPTH_WRITE, PARK)], vec![(d24, ALL, vec![0], t24.as_raw() as usize)])); + let mut out_d24 = vec![tr(d24, ALL, UA, DEPTH_READ)]; + let p_out = plan_with(&mut out_d24, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + assert_eq!(out_d24, vec![tr(d24, ALL, DEPTH_WRITE, DEPTH_READ)]); + assert_eq!(p_out.to_plane.len(), 1); + assert_eq!(p_out.to_plane[0].r24g8_steps, Some(true)); + + // an object made in UNORDERED_ACCESS, one XCL does not keep, a UAV barrier: as they came assert!(register(in_ua, &desc(3, 64, 64, 40, 1, 6), None, UA)); let uav_barrier = [2, 0, res as u32, (res as u64 >> 32) as u32, 0, 0, 0, 0]; - for b in [tr(d24, ALL, DEPTH_WRITE, UA), tr(in_ua, ALL, UA, DEPTH_WRITE), tr(unknown, ALL, DEPTH_WRITE, UA), uav_barrier] { + for b in [tr(in_ua, ALL, UA, DEPTH_WRITE), tr(unknown, ALL, DEPTH_WRITE, UA), uav_barrier] { assert_eq!(plan(b), (vec![b], vec![]), "{b:x?}"); } forget(res); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 0a0de0b0c2..c8affa6ee3 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -99,9 +99,10 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { let resolved_pso = super::pso_async::resolve_for_bind(pso); - let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_pso, riid, ppv); + let pc_alloc = super::alloc_pool::current(alloc); + let hr = real::dev_create_command_list(this, node, ty, pc_alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - super::list_x::on_create(*ppv, alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::on_create_with_backing(*ppv, alloc, pc_alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); super::dred::reset(*ppv); if pso != 0 { super::dred::mark_pipeline(*ppv, pso, resolved_pso); @@ -1140,6 +1141,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } real::note_title_address(*ppv as usize, va as usize); super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); + super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); super::lut3d::created("CreatePlacedResourceX (GPU-owned: on the title's pages / an arena)", *ppv, Some(&x), Some(va as usize), false, state); } return hr; @@ -1156,7 +1158,10 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } }; if hr >= 0 && !buffer && !(*ppv).is_null() { + let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); + let aliased_to_gpu = super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); static M: AtomicU64 = AtomicU64::new(0); + if !aliased_to_gpu { match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { Ok(()) => { real::note_title_address(*ppv as usize, va as usize); @@ -1174,6 +1179,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } Err(_) => {} } + } } if hr >= 0 && !(*ppv).is_null() { real::note_title_address(*ppv as usize, va as usize); diff --git a/crates/xcl/src/hle/d3d12x/dred.rs b/crates/xcl/src/hle/d3d12x/dred.rs index 4eef23183e..98561478bd 100644 --- a/crates/xcl/src/hle/d3d12x/dred.rs +++ b/crates/xcl/src/hle/d3d12x/dred.rs @@ -46,6 +46,14 @@ pub fn label(pso: usize, shaders: &[(&str, Option<&[u8]>)]) { LABELS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, text); } +/// Name an internal pipeline (`SCALE_ARGS_HLSL`, `indirect_guard`, etc.) for DRED breadcrumbs. +pub fn label_text(pso: usize, make: impl FnOnce() -> String) { + if !on() || pso == 0 { + return; + } + LABELS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, make()); +} + pub(super) fn label_of(pso: usize) -> Option { LABELS.lock().unwrap().as_ref()?.get(&pso).cloned() } diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs new file mode 100644 index 0000000000..c490d8a3e0 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -0,0 +1,1689 @@ +//! Placed UAV/SRV texture views (`Create{ShaderResource,UnorderedAccess}ViewAtX`) and +//! format-aliased GPU copies across incompatible DXGI format families. +//! +//! Console titles write packed lighting data (sky, light probes, volumetric fog) through a placed +//! UAV texture view in an integer format (such as `R32_UINT`) and sample the same title address +//! through a placed SRV view in an incompatible format of the same texel width (such as +//! `R9G9B9E5_SHAREDEXP`). On PC D3D12: +//! * `CreateUnorderedAccessViewAtX` often passes a resource desc without `ALLOW_UNORDERED_ACCESS` +//! (or with `R9G9B9E5_SHAREDEXP` / `SRGB`), which caused XCL to produce a null UAV view or +//! promote `R9G9B9E5` to `R11G11B10_FLOAT` (breaking `R32_UINT` views and RGB9E5 decoding). +//! * `CreateShaderResourceViewAtX` with `ALLOW_RENDER_TARGET | ALLOW_UNORDERED_ACCESS` bits still +//! set caused `R9G9B9E5_SHAREDEXP` to be promoted to `R11G11B10_FLOAT` and could register a +//! GPU-written texture in `title_textures` (overwriting GPU data with zeros from CPU memory). +//! * Direct `CopyResource` / `CopyTextureRegion` between different DXGI format families is invalid +//! on PC D3D12; texels of equal byte width must be transferred through an intermediate buffer +//! (`CopyTextureRegion` across all mips and array/depth slices). +//! +//! Set `XCL_FORMAT_ALIAS=0` to disable format-alias syncing. + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::list_x; +use super::real; + +const STATE_COMMON: u32 = 0; +const STATE_RENDER_TARGET: u32 = 0x4; +const STATE_UAV: u32 = 0x8; +const STATE_SRV_NON_PIXEL: u32 = 0x40; +const STATE_SRV_ALL: u32 = 0x40 | 0x80; + +const FLAG_RENDER_TARGET: u32 = 0x1; +const FLAG_DEPTH_STENCIL: u32 = 0x2; +const FLAG_UAV: u32 = 0x4; + +/// Geometry & format summary of a texture for alias / buffer-through copy compatibility checks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct TexShape { + pub dimension: i32, + pub width: u64, + pub height: u32, + pub depth_or_array: u16, + pub mip_levels: u16, + pub format: u32, + pub samples: u32, +} + +impl TexShape { + pub(super) fn from_pc_desc(d: &D3D12_RESOURCE_DESC) -> Self { + Self { + dimension: d.Dimension.0, + width: d.Width, + height: d.Height, + depth_or_array: d.DepthOrArraySize.max(1), + mip_levels: d.MipLevels.max(1), + format: d.Format.0 as u32, + samples: d.SampleDesc.Count.max(1), + } + } + + pub(super) fn subresource_count(&self) -> u32 { + let slices = if self.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + 1 + } else { + self.depth_or_array as u32 + }; + (self.mip_levels as u32).saturating_mul(slices).max(1) + } +} + +/// `(bytes_per_element, is_4x4_block_compressed)` for common DXGI formats. +pub(super) fn format_element_bytes(fmt: u32) -> Option<(u32, bool)> { + match fmt { + // 128-bit uncompressed (16 bytes/texel) + 1..=4 => Some((16, false)), + // 96-bit uncompressed (12 bytes/texel) + 5..=8 => Some((12, false)), + // 64-bit uncompressed (8 bytes/texel): R16G16B16A16_*, R32G32_* + 9..=18 => Some((8, false)), + // 32-bit uncompressed (4 bytes/texel): R10G10B10A2_*, R11G11B10_FLOAT, R8G8B8A8_*, R16G16_*, R32_*, R9G9B9E5_SHAREDEXP, B8G8R8A8/X8_* + 23..=43 | 67 | 87..=93 => Some((4, false)), + // 16-bit uncompressed (2 bytes/texel): R8G8_*, R16_*, B5G6R5, B5G5R5A1, B4G4R4A4 + 48..=59 | 85 | 86 | 115 => Some((2, false)), + // 8-bit uncompressed (1 byte/texel): R8_*, A8_UNORM + 60..=65 => Some((1, false)), + // 4x4 block-compressed, 8 bytes/block: BC1, BC4 + 70..=72 | 79..=81 => Some((8, true)), + // 4x4 block-compressed, 16 bytes/block: BC2, BC3, BC5, BC6H, BC7 + 73..=78 | 82..=84 | 94..=99 => Some((16, true)), + _ => None, + } +} + +/// Canonical typeless family representative for a DXGI format. +pub(super) fn typeless_family(fmt: u32) -> u32 { + match fmt { + 1..=4 => 1, // R32G32B32A32_TYPELESS + 5..=8 => 5, // R32G32B32_TYPELESS + 9..=14 => 9, // R16G16B16A16_TYPELESS + 15..=18 => 15, // R32G32_TYPELESS + 19..=22 => 19, // R32G8X24_TYPELESS + 23..=25 => 23, // R10G10B10A2_TYPELESS + 27..=32 => 27, // R8G8B8A8_TYPELESS + 33..=38 => 33, // R16G16_TYPELESS + 39..=43 => 39, // R32_TYPELESS + 44..=47 => 44, // R24G8_TYPELESS + 48..=52 => 48, // R8G8_TYPELESS + 53..=59 => 53, // R16_TYPELESS + 60..=64 => 60, // R8_TYPELESS + 70..=72 => 70, // BC1_TYPELESS + 73..=75 => 73, // BC2_TYPELESS + 76..=78 => 76, // BC3_TYPELESS + 79..=81 => 79, // BC4_TYPELESS + 82..=84 => 82, // BC5_TYPELESS + 87 | 90 | 91 => 90, // B8G8R8A8_TYPELESS + 88 | 92 | 93 => 92, // B8G8R8X8_TYPELESS + 94..=96 => 94, // BC6H_TYPELESS + 97..=99 => 97, // BC7_TYPELESS + other => other, + } +} + +/// Whether `dst_fmt` and `src_fmt` belong to different DXGI typeless families (so direct +/// `CopyResource` is illegal on PC D3D12 and a buffer-through `CopyTextureRegion` is needed). +pub(super) fn needs_buffer_through(dst_fmt: u32, src_fmt: u32) -> bool { + dst_fmt != 0 && src_fmt != 0 && typeless_family(dst_fmt) != typeless_family(src_fmt) +} + +/// Whether two textures can exchange texels via an intermediate buffer (`CopyTextureRegion`). +pub(super) fn can_copy_through_buffer(dst: &TexShape, src: &TexShape) -> bool { + if dst.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 + || src.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 + || dst.dimension != src.dimension + || dst.samples > 1 + || src.samples > 1 + || dst.mip_levels != src.mip_levels + || dst.depth_or_array != src.depth_or_array + { + return false; + } + let (Some((db, dbc)), Some((sb, sbc))) = (format_element_bytes(dst.format), format_element_bytes(src.format)) else { + return false; + }; + if db != sb { + return false; + } + match (dbc, sbc) { + (false, false) | (true, true) => dst.width == src.width && dst.height == src.height, + (true, false) => src.width == dst.width.div_ceil(4) && src.height == dst.height.div_ceil(4), + (false, true) => dst.width == src.width.div_ceil(4) && dst.height == src.height.div_ceil(4), + } +} + +/// Choose a UAV-capable PC resource format that accepts `view_fmt` (or `rdesc_fmt` if `view_fmt == 0`). +pub(super) fn uav_resource_format(rdesc_fmt: u32, view_fmt: u32) -> u32 { + let target = if view_fmt != 0 { view_fmt } else { rdesc_fmt }; + // R9G9B9E5_SHAREDEXP cannot have ALLOW_UNORDERED_ACCESS on PC; use R32_TYPELESS when the + // view wants 32-bit integer/float UAV access, otherwise let device_x handle it. + if rdesc_fmt == 67 && view_fmt != 0 && view_fmt != 67 { + return typeless_family(view_fmt); + } + // sRGB formats cannot have ALLOW_UNORDERED_ACCESS on PC; use their typeless family. + if matches!(target, 29 | 91 | 93) { + return typeless_family(target); + } + // If the view requests a different family than the resource desc (e.g. R32_UINT view over + // an R9G9B9E5 or R11G11B10 resource), make the UAV texture typeless in the view's family. + if view_fmt != 0 && typeless_family(rdesc_fmt) != typeless_family(view_fmt) { + return typeless_family(view_fmt); + } + // Use typeless when available so both typed UAV and SRV views match cleanly. + let fam = typeless_family(target); + match fam { + 1 | 9 | 15 | 23 | 27 | 33 | 39 | 48 | 53 | 60 | 90 => fam, + _ => target, + } +} + +/// Sanitize a console resource desc for `CreateUnorderedAccessViewAtX`: guarantee +/// `ALLOW_UNORDERED_ACCESS` and a UAV-compatible format so PC D3D12 never drops it to a null view. +pub(super) fn prepare_placed_uav_desc(rdesc: &[u8; 0x38], view_fmt: u32) -> [u8; 0x38] { + let mut x = *rdesc; + // the padding between `Dimension` and `Alignment` (the title leaves stack bytes there): one + // key per view, not one per padding value + x[0x04..0x08].fill(0); + x[0x34..].fill(0); + let rdesc_fmt = u32::from_le_bytes(x[0x20..0x24].try_into().unwrap()); + let mut flags = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()); + let is_depth = flags & FLAG_DEPTH_STENCIL != 0 || matches!(rdesc_fmt, 19 | 20 | 40 | 44 | 45 | 55 | 118..=120); + if !is_depth { + // Strip RTV bit on placed UAV textures so integer/typeless UAV formats are never rejected + // by render-target format restrictions. + flags = (flags & !FLAG_RENDER_TARGET) | FLAG_UAV; + let fmt = uav_resource_format(rdesc_fmt, view_fmt); + x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + } else { + flags |= FLAG_UAV; + } + x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + x +} + +/// Sanitize a console resource desc for `CreateShaderResourceViewAtX`: strip `ALLOW_RENDER_TARGET` +/// and `ALLOW_UNORDERED_ACCESS` so `R9G9B9E5_SHAREDEXP` stays format 67 and placed SRVs never +/// retire or overwrite GPU-owned target tracking at `va`. +pub(super) fn prepare_placed_srv_desc(rdesc: &[u8; 0x38], view_fmt: u32) -> [u8; 0x38] { + let mut x = *rdesc; + x[0x04..0x08].fill(0); + x[0x34..].fill(0); + let rdesc_fmt = u32::from_le_bytes(x[0x20..0x24].try_into().unwrap()); + let mut flags = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()); + flags &= !(FLAG_RENDER_TARGET | FLAG_UAV); + x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + if view_fmt != 0 && typeless_family(rdesc_fmt) != typeless_family(view_fmt) && format_element_bytes(view_fmt).is_some() { + // Keep R9G9B9E5_SHAREDEXP (67) and other single-member formats verbatim; use typeless + // only when it belongs to a multi-format typeless family. + let fmt = match typeless_family(view_fmt) { + f if f == view_fmt => view_fmt, + f if matches!(f, 1 | 9 | 15 | 23 | 27 | 33 | 39 | 48 | 53 | 60 | 70 | 73 | 76 | 79 | 82 | 90 | 92 | 94 | 97) => f, + _ => view_fmt, + }; + x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + } + x +} + +/// Ownership of a resource participating in format-alias tracking. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Owner { + /// Internal texture created by `dev_create_uav_at_x` (resting state: `UNORDERED_ACCESS`). + PlacedUav, + /// Internal texture created by `dev_create_srv_at_x` (resting state outside open list: `COMMON`). + PlacedSrv, + /// Title-created texture from `CreatePlacedResourceX` (tracked PC state). + TitlePlaced, +} + +struct TrackedTex { + device: usize, + va: usize, + shape: TexShape, + owner: Owner, + /// Per-subresource PC states (only tracked for `Owner::TitlePlaced`). + pc_states: Vec, + is_writer: bool, + /// Whether this writer may hold GPU writes not yet copied to its format-aliased readers. + /// Starts `true`, clears after all current readers are synced, and re-arms on any write + /// transition/access, discard, copy-dest, or newly linked reader. + dirty: bool, + /// `bind::activity()` (`(draws, dispatches)`) at the writer's last completed sync. + last_sync_activity: Option<(u64, u64)>, +} + +impl TrackedTex { + fn new(device: usize, va: usize, shape: TexShape, owner: Owner, initial_state: u32, is_writer: bool) -> Self { + let n = if owner == Owner::TitlePlaced { shape.subresource_count().max(1) as usize } else { 0 }; + Self { + device, + va, + shape, + owner, + pc_states: vec![initial_state; n], + is_writer, + dirty: is_writer, + last_sync_activity: None, + } + } + + fn uniform_state(&self) -> Option { + let &first = self.pc_states.first()?; + self.pc_states.iter().all(|&s| s == first).then_some(first) + } + + fn update_state(&mut self, subresource: u32, after: u32) { + if subresource == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { + self.pc_states.fill(after); + } else if let Some(slot) = self.pc_states.get_mut(subresource as usize) { + *slot = after; + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +struct AliasPair { + writer: usize, + reader: usize, + device: usize, + buffer_through: bool, + writer_owner: Owner, + reader_owner: Owner, +} + +struct AliasTable { + /// Cached internal placed-UAV textures: `(va, prepared_desc)` -> owned `ID3D12Resource`. + placed_uavs: HashMap<(u64, [u8; 0x38]), ID3D12Resource>, + /// Cached internal placed-SRV textures: `(va, prepared_desc)` -> owned `ID3D12Resource`. + placed_srvs: HashMap<(u64, [u8; 0x38]), ID3D12Resource>, + /// All tracked textures by raw resource pointer. + by_res: HashMap, + /// Title VA -> tracked resource pointers at that exact VA. + by_va: HashMap>, + /// Active `(writer -> reader)` sync pairs. + pairs: Vec, + /// Pairs whose writer is an internal `PlacedUav` (must be synced on UAV barriers). + placed_uav_pairs: usize, +} + +unsafe impl Send for AliasTable {} + +impl AliasTable { + fn new() -> Self { + Self { + placed_uavs: HashMap::new(), + placed_srvs: HashMap::new(), + by_res: HashMap::new(), + by_va: HashMap::new(), + pairs: Vec::new(), + placed_uav_pairs: 0, + } + } + + fn has_writer_at(&self, va: usize, shape: &TexShape) -> bool { + self.by_va.get(&va).is_some_and(|list| { + list.iter().any(|r| { + self.by_res.get(r).is_some_and(|t| t.is_writer && can_copy_through_buffer(shape, &t.shape)) + }) + }) + } + + /// Register `res` at `va` and link any compatible `(writer -> reader)` pairs at the same VA. + /// Returns any existing reader resources that should be marked `gpu_written` in `title_textures`. + fn insert(&mut self, res: usize, tex: TrackedTex) -> Vec { + self.remove(res); + let mut mark_gpu_written = Vec::new(); + let mut new_pairs = Vec::new(); + if let Some(peers) = self.by_va.get(&tex.va) { + for &peer in peers { + let Some(p) = self.by_res.get(&peer) else { + continue; + }; + if p.device != tex.device { + continue; + } + // Link writer -> reader when one is a PlacedUav (always needs sync to its SRV alias) + // OR when their formats are in different typeless families (format-aliased GPU textures). + if tex.is_writer && !p.is_writer && can_copy_through_buffer(&p.shape, &tex.shape) { + let bt = needs_buffer_through(p.shape.format, tex.shape.format); + if tex.owner == Owner::PlacedUav || bt { + new_pairs.push(AliasPair { + writer: res, + reader: peer, + device: tex.device, + buffer_through: bt, + writer_owner: tex.owner, + reader_owner: p.owner, + }); + mark_gpu_written.push(peer); + } + } else if !tex.is_writer && p.is_writer && can_copy_through_buffer(&tex.shape, &p.shape) { + let bt = needs_buffer_through(tex.shape.format, p.shape.format); + if p.owner == Owner::PlacedUav || bt { + new_pairs.push(AliasPair { + writer: peer, + reader: res, + device: tex.device, + buffer_through: bt, + writer_owner: p.owner, + reader_owner: tex.owner, + }); + mark_gpu_written.push(res); + } + } + } + } + for pair in new_pairs { + if let Some(w) = self.by_res.get_mut(&pair.writer) { + w.dirty = true; + w.last_sync_activity = None; + } + self.add_pair(pair); + } + self.by_va.entry(tex.va).or_default().push(res); + if tex.owner == Owner::TitlePlaced { + TRACKED_TITLE_TEX.fetch_add(1, Ordering::Relaxed); + } + self.by_res.insert(res, tex); + mark_gpu_written + } + + /// Evict cached internal `PlacedUav`/`PlacedSrv` resources at `va` whose shape no longer + /// matches `keep_shape` (or all internal resources at `va` when `keep_shape` is `None` and + /// no `TitlePlaced` peers remain at `va`), returning the evicted `ID3D12Resource`s to be + /// deferred-released outside the lock. + fn evict_stale_internal_at(&mut self, va: usize, keep_shape: Option<&TexShape>) -> Vec { + let mut evicted_ptrs = Vec::new(); + if let Some(list) = self.by_va.get(&va) { + let has_title = list.iter().any(|r| self.by_res.get(r).is_some_and(|t| t.owner == Owner::TitlePlaced)); + if keep_shape.is_none() && has_title { + return Vec::new(); + } + for &r in list { + let Some(t) = self.by_res.get(&r) else { continue }; + if t.owner == Owner::TitlePlaced { + continue; + } + let stale = match keep_shape { + Some(s) => !can_copy_through_buffer(s, &t.shape), + None => true, + }; + if stale { + evicted_ptrs.push(r); + } + } + } + let mut dropped = Vec::new(); + for r in evicted_ptrs { + self.remove(r); + let uav_keys: Vec<_> = self.placed_uavs.iter().filter(|(_, v)| v.as_raw() as usize == r).map(|(k, _)| *k).collect(); + for k in uav_keys { + if let Some(res) = self.placed_uavs.remove(&k) { + dropped.push(res); + } + } + let srv_keys: Vec<_> = self.placed_srvs.iter().filter(|(_, v)| v.as_raw() as usize == r).map(|(k, _)| *k).collect(); + for k in srv_keys { + if let Some(res) = self.placed_srvs.remove(&k) { + dropped.push(res); + } + } + } + dropped + } + + fn add_pair(&mut self, pair: AliasPair) { + if self.pairs.iter().any(|p| p.writer == pair.writer && p.reader == pair.reader) { + return; + } + if pair.writer_owner == Owner::PlacedUav { + self.placed_uav_pairs += 1; + ACTIVE_PLACED_UAV_PAIRS.store(self.placed_uav_pairs, Ordering::Relaxed); + } + ACTIVE_PAIRS.store(self.pairs.len() + 1, Ordering::Relaxed); + self.pairs.push(pair); + } + + fn clone_internal(&self, res: usize) -> Option { + self.placed_uavs + .values() + .chain(self.placed_srvs.values()) + .find(|r| r.as_raw() as usize == res) + .cloned() + } + + fn remove(&mut self, res: usize) -> Option { + if let Some(old) = self.by_res.remove(&res) { + if old.owner == Owner::TitlePlaced { + TRACKED_TITLE_TEX.fetch_sub(1, Ordering::Relaxed); + } + if let Some(list) = self.by_va.get_mut(&old.va) { + list.retain(|&r| r != res); + if list.is_empty() { + self.by_va.remove(&old.va); + } + } + let before = self.pairs.len(); + self.pairs.retain(|p| p.writer != res && p.reader != res); + if self.pairs.len() != before { + self.placed_uav_pairs = self.pairs.iter().filter(|p| p.writer_owner == Owner::PlacedUav).count(); + ACTIVE_PLACED_UAV_PAIRS.store(self.placed_uav_pairs, Ordering::Relaxed); + ACTIVE_PAIRS.store(self.pairs.len(), Ordering::Relaxed); + } + return Some(old.va); + } + None + } +} + +static TABLE: Mutex> = Mutex::new(None); +static TRACKED_TITLE_TEX: AtomicUsize = AtomicUsize::new(0); +static ACTIVE_PAIRS: AtomicUsize = AtomicUsize::new(0); +static ACTIVE_PLACED_UAV_PAIRS: AtomicUsize = AtomicUsize::new(0); + +/// Insert `value` at `key` or keep the existing entry, always returning a cloned handle to the +/// winning map entry plus `Some(loser)` if another thread won the race so the caller can drop the +/// loser outside the table lock. +fn cache_insert_or_clone( + map: &mut HashMap, + key: K, + value: V, +) -> (V, Option) { + match map.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => (e.get().clone(), Some(value)), + std::collections::hash_map::Entry::Vacant(e) => (e.insert(value).clone(), None), + } +} + +/// Release internal resources evicted from `placed_uavs` / `placed_srvs` outside `TABLE`. +/// Adopted resources route through `real::res_release`, which cleans up `title_textures` / +/// `vram` / `format_alias` tracking on the final ref and defers the PC `Release` via +/// `late_release::hold` once no in-flight caller still holds a cloned reference. +unsafe fn defer_drop_resources(evicted: Vec) { + for r in evicted { + if super::real::is_adopted(r.as_raw()) || !super::late_release::enabled() { + drop(r); + } else { + super::late_release::hold(r.into_raw() as usize, false); + } + } +} + +/// D3D12 resource states legal in a `ResourceBarrier` on a `COMPUTE` command list for textures +/// (`COMMON`, `UNORDERED_ACCESS`, `NON_PIXEL_SHADER_RESOURCE`, `COPY_DEST`, `COPY_SOURCE`). +const COMPUTE_VALID_STATES: u32 = 0x8 | 0x40 | 0x400 | 0x800; + +fn state_valid_on_list(ty: D3D12_COMMAND_LIST_TYPE, st: u32) -> bool { + ty == D3D12_COMMAND_LIST_TYPE_DIRECT || (st & !COMPUTE_VALID_STATES == 0) +} + +/// Per-open-list state for `PlacedSrv` resources transitioned into read state on that list +/// (returned to `COMMON` before `Close()`), plus last synced `bind::activity()`. +#[derive(Default)] +struct ListSyncState { + /// `PlacedSrv` resource -> current state on this open list (`SRV_ALL` or `SRV_NON_PIXEL`). + srv_states: HashMap, + last_activity: (u64, u64), + list_type: Option, +} + +static LIST_STATES: Mutex>> = Mutex::new(None); + +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_FORMAT_ALIAS").is_ok_and(|v| v.trim() == "0")) +} + +/// `XCL_FORMAT_ALIAS_DEDUP=0`: disable skipping redundant format-alias copies when the source +/// texture was not written since its last sync. +fn dedup_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_FORMAT_ALIAS_DEDUP").is_ok_and(|v| v.trim() == "0")) +} + +fn note_skipped_sync() { + static SKIPPED: AtomicU64 = AtomicU64::new(0); + let n = SKIPPED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || (n.is_power_of_two() && n >= 16) { + crate::xlog_info!("D3D12.X: skipped {n} redundant format-alias texture copies (source unchanged since last sync)"); + } +} + +fn mark_writer_dirty(res: usize) { + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 && ACTIVE_PLACED_UAV_PAIRS.load(Ordering::Relaxed) == 0 { + return; + } + if let Some(tex) = TABLE.lock().unwrap().as_mut().and_then(|t| t.by_res.get_mut(&res)) { + if tex.is_writer { + tex.dirty = true; + tex.last_sync_activity = None; + } + } +} + +unsafe fn create_internal_texture(dev: *mut c_void, pc_desc: &[u8; 0x38], initial_state: u32) -> Option { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = real::dev_create_committed_resource( + dev, + &heap as *const _ as usize, + 0, + pc_desc.as_ptr() as usize, + initial_state as usize, + 0, + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut out, + ); + if hr < 0 || out.is_null() { + return None; + } + Some(ID3D12Resource::from_raw(out)) +} + +/// Obtain or create the host UAV texture backing `CreateUnorderedAccessViewAtX` at `va`, +/// returning an owned reference so concurrent eviction cannot free it mid-call. +pub(super) unsafe fn placed_uav_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> Option { + if rdesc.is_null() || va == 0 || !crate::gpu::shader::readable(rdesc as usize, 0x38) { + return None; + } + let raw_x: [u8; 0x38] = (rdesc as *const [u8; 0x38]).read_unaligned(); + let prepared = prepare_placed_uav_desc(&raw_x, view_fmt); + let key = (va, prepared); + + { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + if let Some(res) = t.placed_uavs.get(&key) { + return Some(res.clone()); + } + } + + let pc = super::device_x::pc_resource_desc(&prepared); + let flags = u32::from_le_bytes(prepared[0x30..0x34].try_into().unwrap()); + let is_depth_uav = flags & (FLAG_DEPTH_STENCIL | FLAG_UAV) == (FLAG_DEPTH_STENCIL | FLAG_UAV); + let init_state = if is_depth_uav { + super::device_x::pc_initial_state(flags, STATE_UAV) + } else { + STATE_UAV + }; + let Some(res) = create_internal_texture(dev, &pc, init_state) else { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: placed UAV texture at {va:#x} (view fmt {view_fmt}) could not be created"); + } + return None; + }; + let raw = res.as_raw(); + if is_depth_uav { + super::depth_uav::note_created(raw, &prepared, Some(va as usize), init_state); + } + let pc_desc = res.GetDesc(); + let shape = TexShape::from_pc_desc(&pc_desc); + let (winner, lost_race, mark) = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let (winner, loser) = cache_insert_or_clone(&mut t.placed_uavs, key, res); + let mark = if loser.is_none() && !is_depth_uav && enabled() { + t.insert( + raw as usize, + TrackedTex::new(dev as usize, va as usize, shape, Owner::PlacedUav, STATE_UAV, true), + ) + } else { + Vec::new() + }; + (winner, loser, mark) + }; + if let Some(loser) = lost_race { + defer_drop_resources(vec![loser]); + } else { + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: placed UAV texture at {va:#x} ({}x{}x{}, {} mips, pc fmt {}, view fmt {view_fmt}) -> {raw:p} ({} created)", + pc_desc.Width, + pc_desc.Height, + pc_desc.DepthOrArraySize, + pc_desc.MipLevels, + pc_desc.Format.0, + n + 1 + ); + } + } + for reader in mark { + super::title_textures::note_gpu_write(0, reader); + } + Some(winner) +} + +/// Obtain or create the host SRV texture backing `CreateShaderResourceViewAtX` at `va`, +/// returning an owned reference so concurrent eviction cannot free it mid-call. +/// If a GPU writer already occupies `va` with a compatible shape, creates a dedicated GPU-synced +/// SRV texture (skipping `title_textures` so CPU zeros never overwrite GPU writes); otherwise +/// delegates to `create_placed_resource_x` and registers it as a reader in case a placed UAV +/// appears at `va` later. +pub(super) unsafe fn placed_srv_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> Option { + if rdesc.is_null() || va == 0 || !crate::gpu::shader::readable(rdesc as usize, 0x38) { + return None; + } + let raw_x: [u8; 0x38] = (rdesc as *const [u8; 0x38]).read_unaligned(); + let prepared = prepare_placed_srv_desc(&raw_x, view_fmt); + let key = (va, prepared); + let pc = super::device_x::pc_resource_desc(&prepared); + let pc_desc = std::ptr::read_unaligned(pc.as_ptr() as *const D3D12_RESOURCE_DESC); + let shape = TexShape::from_pc_desc(&pc_desc); + + let has_writer = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + if let Some(res) = t.placed_srvs.get(&key) { + return Some(res.clone()); + } + enabled() && t.has_writer_at(va as usize, &shape) + }; + + let res = if has_writer { + // Dedicated GPU-synced SRV texture in COMMON state (not registered in title_textures). + create_internal_texture(dev, &pc, STATE_COMMON)? + } else { + let mut r = std::ptr::null_mut(); + let hr = super::device_x::create_placed_resource_x( + dev, + va, + prepared.as_ptr(), + 0, + std::ptr::null(), + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut r, + ); + if hr < 0 || r.is_null() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: placed SRV texture at {va:#x}: resource creation failed ({hr:#x})"); + } + return None; + } + ID3D12Resource::from_raw(r) + }; + + let raw = res.as_raw(); + let owner = if has_writer { Owner::PlacedSrv } else { Owner::TitlePlaced }; + let (winner, lost_race, mark) = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let (winner, loser) = cache_insert_or_clone(&mut t.placed_srvs, key, res); + let mark = if loser.is_none() && enabled() { + t.insert( + raw as usize, + TrackedTex::new(dev as usize, va as usize, shape, owner, STATE_COMMON, false), + ) + } else { + Vec::new() + }; + (winner, loser, mark) + }; + if let Some(loser) = lost_race { + defer_drop_resources(vec![loser]); + } + for reader in mark { + super::title_textures::note_gpu_write(0, reader); + } + Some(winner) +} + +/// Register a title-created placed texture from `device_x::create_placed_resource_x`. +/// Returns `true` if the texture is already aliased to a GPU writer at `va` (so callers should +/// call `title_textures::note_gpu_write` and avoid CPU uploads over GPU-written texels). +pub(super) fn register_title_texture(dev: usize, res: usize, va: usize, pc_desc: &D3D12_RESOURCE_DESC, flags: u32, initial_state: u32) -> bool { + if !enabled() || res == 0 || va == 0 || pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + let shape = TexShape::from_pc_desc(pc_desc); + if format_element_bytes(shape.format).is_none() || shape.samples > 1 { + return false; + } + let is_writer = flags & (FLAG_RENDER_TARGET | FLAG_UAV) != 0; + let (mark, evicted) = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let evicted = t.evict_stale_internal_at(va, Some(&shape)); + let mark = t.insert( + res, + TrackedTex::new(dev, va, shape, Owner::TitlePlaced, initial_state, is_writer), + ); + (mark, evicted) + }; + if !evicted.is_empty() { + unsafe { defer_drop_resources(evicted) }; + } + let mut self_gpu_written = false; + for r in mark { + if r == res { + self_gpu_written = true; + } + super::title_textures::note_gpu_write(0, r); + } + self_gpu_written +} + +/// Remove a released title resource from format-alias tracking, evicting any orphaned internal +/// `PlacedUav`/`PlacedSrv` textures at the same VA via deferred GPU release. +pub(super) fn forget(res: usize) { + let evicted = { + let mut g = TABLE.lock().unwrap(); + if let Some(t) = g.as_mut() { + let mut dropped = Vec::new(); + let va = t.remove(res); + let uav_keys: Vec<_> = t.placed_uavs.iter().filter(|(_, v)| v.as_raw() as usize == res).map(|(k, _)| *k).collect(); + for k in uav_keys { + if let Some(r) = t.placed_uavs.remove(&k) { + dropped.push(r); + } + } + let srv_keys: Vec<_> = t.placed_srvs.iter().filter(|(_, v)| v.as_raw() as usize == res).map(|(k, _)| *k).collect(); + for k in srv_keys { + if let Some(r) = t.placed_srvs.remove(&k) { + dropped.push(r); + } + } + if let Some(va) = va { + dropped.extend(t.evict_stale_internal_at(va, None)); + } + dropped + } else { + Vec::new() + } + }; + if !evicted.is_empty() { + unsafe { defer_drop_resources(evicted) }; + } + if let Some(m) = LIST_STATES.lock().unwrap().as_mut() { + for s in m.values_mut() { + s.srv_states.remove(&res); + } + } +} + +/// Track state transitions of title-owned textures (even before an alias peer is created at the +/// same VA) and collect any writers leaving `UNORDERED_ACCESS` / `RENDER_TARGET` whose +/// format-aliased readers need a copy. Ignores split-barrier `BEGIN_ONLY` flags. +pub(super) fn note_title_transition(res: usize, subresource: u32, before: u32, after: u32, flags: u32, writers_to_sync: &mut Vec<(usize, u32)>) { + const BARRIER_BEGIN_ONLY: u32 = 1; + const STATE_COPY_DEST: u32 = 0x400; + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 || flags == BARRIER_BEGIN_ONLY { + return; + } + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { + return; + }; + let Some(tex) = t.by_res.get_mut(&res) else { + return; + }; + if tex.owner != Owner::TitlePlaced { + return; + } + tex.update_state(subresource, after); + let write_bits = STATE_UAV | STATE_RENDER_TARGET | STATE_COPY_DEST; + if tex.is_writer && ((before & write_bits != 0) || (after & write_bits != 0)) { + tex.dirty = true; + tex.last_sync_activity = None; + } + let uniform = tex.uniform_state(); + let is_writer = tex.is_writer; + let leaving_write = (before & (STATE_UAV | STATE_RENDER_TARGET) != 0) && (after & (STATE_UAV | STATE_RENDER_TARGET) == 0); + if is_writer && leaving_write && ACTIVE_PAIRS.load(Ordering::Relaxed) != 0 && t.pairs.iter().any(|p| p.writer == res) { + if let Some(st) = uniform { + writers_to_sync.push((res, st)); + } + } +} + +/// Inspect enhanced `D3D12_BARRIER_GROUP` texture barriers (`#146`) and collect any tracked +/// `TitlePlaced` writers leaving write access so their format-aliased readers receive a copy. +pub(super) unsafe fn filter_enhanced_barriers(n: u32, groups: *const c_void, writers_to_sync: &mut Vec<(usize, u32)>) { + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 + || ACTIVE_PAIRS.load(Ordering::Relaxed) == 0 + || n == 0 + || groups.is_null() + { + return; + } + let group_count = (n as usize).min(256); + let group_bytes = group_count.saturating_mul(std::mem::size_of::()); + if !crate::gpu::shader::readable(groups as usize, group_bytes) { + return; + } + let write_access = (D3D12_BARRIER_ACCESS_RENDER_TARGET.0 as u32) + | (D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 as u32) + | (D3D12_BARRIER_ACCESS_COPY_DEST.0 as u32); + let read_access = (D3D12_BARRIER_ACCESS_SHADER_RESOURCE.0 as u32) + | (D3D12_BARRIER_ACCESS_COPY_SOURCE.0 as u32); + let is_write_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_RENDER_TARGET + | D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COPY_DEST + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_DEST + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_DEST + ) + }; + let is_common_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_COMMON + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COMMON + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COMMON + ) + }; + let is_read_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_GENERIC_READ + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_GENERIC_READ + | D3D12_BARRIER_LAYOUT_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_SOURCE + ) + }; + let dedup = dedup_enabled(); + let slice = std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, group_count); + for grp in slice { + if grp.Type != D3D12_BARRIER_TYPE_TEXTURE { + continue; + } + let count = (grp.NumBarriers as usize).min(4096); + if count == 0 { + continue; + } + let ptr = grp.Anonymous.pTextureBarriers; + let bytes = count.saturating_mul(std::mem::size_of::()); + if ptr.is_null() || !crate::gpu::shader::readable(ptr as usize, bytes) { + continue; + } + let tbs = std::slice::from_raw_parts(ptr, count); + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { + continue; + }; + for tb in tbs { + let res: usize = std::mem::transmute_copy(&tb.pResource); + if res == 0 { + continue; + } + let has_pair = t.pairs.iter().any(|p| p.writer == res); + let Some(tex) = t.by_res.get_mut(&res) else { + continue; + }; + if tex.owner != Owner::TitlePlaced || !tex.is_writer || !has_pair { + continue; + } + let discard = (tb.Flags.0 as u32) & (D3D12_TEXTURE_BARRIER_FLAG_DISCARD.0 as u32) != 0 + || tb.LayoutBefore == D3D12_BARRIER_LAYOUT_UNDEFINED; + if discard { + tex.dirty = true; + tex.last_sync_activity = None; + continue; + } + let ab = tb.AccessBefore.0 as u32; + let aa = tb.AccessAfter.0 as u32; + let before_write = (ab & write_access != 0) || is_write_layout(tb.LayoutBefore); + let after_write = (aa & write_access != 0) || is_write_layout(tb.LayoutAfter); + if before_write || after_write { + tex.dirty = true; + tex.last_sync_activity = None; + } + let common_to_read = ab == 0 && is_common_layout(tb.LayoutBefore) && ((aa & read_access != 0) || is_read_layout(tb.LayoutAfter)); + if before_write && !after_write { + if let Some(st) = tex.uniform_state() { + writers_to_sync.push((res, st)); + } + } else if common_to_read { + if !dedup || tex.dirty { + if let Some(st) = tex.uniform_state() { + writers_to_sync.push((res, st)); + } + } else { + note_skipped_sync(); + } + } + } + } +} + +/// Copy all subresources of `src` into `dst` through an intermediate buffer (`CopyTextureRegion`), +/// preserving raw texel bits across incompatible DXGI format families (e.g. `R32_UINT` -> +/// `R9G9B9E5_SHAREDEXP` or `BCn` <-> `R32G32B32A32_UINT`). +/// Callers must ensure `src` is in `COPY_SOURCE` and `dst` is in `COPY_DEST`. +pub(super) unsafe fn copy_all_subresources_through_buffer( + list: *mut c_void, + dev: &ID3D12Device, + dst: &ID3D12Resource, + src: &ID3D12Resource, +) -> bool { + let dst_desc = dst.GetDesc(); + let src_desc = src.GetDesc(); + let dst_shape = TexShape::from_pc_desc(&dst_desc); + let src_shape = TexShape::from_pc_desc(&src_desc); + if !can_copy_through_buffer(&dst_shape, &src_shape) { + return false; + } + let count = dst_shape.subresource_count().min(src_shape.subresource_count()); + for sub in 0..count { + if !copy_one_subresource_through_buffer(list, dev, dst, &dst_desc, sub, src, &src_desc, sub) { + return false; + } + } + true +} + +struct OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION); + +impl Drop for OwnedCopyLoc { + fn drop(&mut self) { + unsafe { ManuallyDrop::drop(&mut self.0.pResource) }; + } +} + +/// Verify two single-subresource footprints have identical element byte widths and compatible +/// block/texel dimensions (preventing accidental aliasing of incompatible formats that merely +/// share a 256-byte-aligned `RowPitch`). +fn subresource_footprints_compatible(dst_fmt: u32, dst_fp: &D3D12_SUBRESOURCE_FOOTPRINT, src_fmt: u32, src_fp: &D3D12_SUBRESOURCE_FOOTPRINT) -> bool { + let (Some((db, dbc)), Some((sb, sbc))) = (format_element_bytes(dst_fmt), format_element_bytes(src_fmt)) else { + return false; + }; + if db != sb || dst_fp.Depth != src_fp.Depth { + return false; + } + let eff = |bc: bool, w: u32, h: u32| -> (u32, u32) { + if bc { (w.div_ceil(4), h.div_ceil(4)) } else { (w, h) } + }; + eff(dbc, dst_fp.Width, dst_fp.Height) == eff(sbc, src_fp.Width, src_fp.Height) +} + +unsafe fn copy_one_subresource_through_buffer( + list: *mut c_void, + dev: &ID3D12Device, + dst: &ID3D12Resource, + dst_desc: &D3D12_RESOURCE_DESC, + dst_sub: u32, + src: &ID3D12Resource, + src_desc: &D3D12_RESOURCE_DESC, + src_sub: u32, +) -> bool { + let mut src_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut dst_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut src_rows = 0u32; + let mut dst_rows = 0u32; + let mut src_total = 0u64; + let mut dst_total = 0u64; + dev.GetCopyableFootprints(src_desc, src_sub, 1, 0, Some(&mut src_fp), Some(&mut src_rows), None, Some(&mut src_total)); + dev.GetCopyableFootprints(dst_desc, dst_sub, 1, 0, Some(&mut dst_fp), Some(&mut dst_rows), None, Some(&mut dst_total)); + if src_total == 0 + || src_total == u64::MAX + || dst_total == 0 + || dst_total == u64::MAX + || src_rows != dst_rows + || !subresource_footprints_compatible(dst_desc.Format.0 as u32, &dst_fp.Footprint, src_desc.Format.0 as u32, &src_fp.Footprint) + { + return false; + } + let row_pitch = src_fp.Footprint.RowPitch.max(dst_fp.Footprint.RowPitch); + src_fp.Footprint.RowPitch = row_pitch; + dst_fp.Footprint.RowPitch = row_pitch; + let slices = (src_fp.Footprint.Depth as u64).max(1); + let needed = (row_pitch as u64).saturating_mul(src_rows as u64).saturating_mul(slices).max(src_total).max(dst_total); + let Some(scratch_raw) = list_x::acquire_scratch_for_copy(list, needed) else { + return false; + }; + let scratch_ptr = scratch_raw as *mut c_void; + let Some(scratch) = ID3D12Resource::from_raw_borrowed(&scratch_ptr) else { + return false; + }; + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + { + let src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(src.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: src_sub }, + }); + let buf_dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(scratch.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: src_fp }, + }); + list_x::pc_copy_texture_region(list, &buf_dst_loc.0, 0, 0, 0, &src_loc.0, std::ptr::null()); + } + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + { + let buf_src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(scratch.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: dst_fp }, + }); + let dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(dst.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: dst_sub }, + }); + list_x::pc_copy_texture_region(list, &dst_loc.0, 0, 0, 0, &buf_src_loc.0, std::ptr::null()); + } + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + true +} + +unsafe fn sync_pair(list: *mut c_void, dev: &ID3D12Device, ty: D3D12_COMMAND_LIST_TYPE, pair: AliasPair, writer_state: u32) -> bool { + let w_ptr = pair.writer as *mut c_void; + let r_ptr = pair.reader as *mut c_void; + let (Some(writer_res), Some(reader_res)) = (ID3D12Resource::from_raw_borrowed(&w_ptr), ID3D12Resource::from_raw_borrowed(&r_ptr)) else { + return false; + }; + let target_srv = if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { STATE_SRV_ALL } else { STATE_SRV_NON_PIXEL }; + + // Determine reader's incoming state on this list. + let (reader_before, reader_after) = match pair.reader_owner { + Owner::PlacedSrv => { + let cur = LIST_STATES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .and_then(|s| s.srv_states.get(&pair.reader).copied()) + .unwrap_or(STATE_COMMON); + (cur, target_srv) + } + Owner::TitlePlaced => { + let Some(st) = TABLE + .lock() + .unwrap() + .as_ref() + .and_then(|t| t.by_res.get(&pair.reader)) + .and_then(TrackedTex::uniform_state) + else { + return false; + }; + // On a compute list, never emit transitions referencing DIRECT-only states + // (`RENDER_TARGET`, `INDEX_BUFFER`, `VERTEX_AND_CONSTANT_BUFFER`, `DEPTH_*`, `PIXEL_SHADER_RESOURCE`). + if !state_valid_on_list(ty, st) { + return false; + } + (st, st) + } + Owner::PlacedUav => return false, + }; + + if writer_state != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 { + list_x::transition(list, pair.writer, D3D12_RESOURCE_STATES(writer_state as i32), D3D12_RESOURCE_STATE_COPY_SOURCE); + } + if reader_before != D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 { + list_x::transition(list, pair.reader, D3D12_RESOURCE_STATES(reader_before as i32), D3D12_RESOURCE_STATE_COPY_DEST); + } + + let ok = if pair.buffer_through { + copy_all_subresources_through_buffer(list, dev, reader_res, writer_res) + } else { + list_x::pc_copy_resource(list, pair.reader, pair.writer); + true + }; + + if writer_state != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 { + list_x::transition(list, pair.writer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATES(writer_state as i32)); + } + if reader_after != D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 { + list_x::transition(list, pair.reader, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATES(reader_after as i32)); + } + + if pair.reader_owner == Owner::PlacedSrv { + let mut g = LIST_STATES.lock().unwrap(); + let ls = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + ls.list_type = Some(ty); + ls.srv_states.insert(pair.reader, reader_after); + } + + if ok { + static SYNCED: AtomicU64 = AtomicU64::new(0); + let n = SYNCED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: synced format-aliased texture {:#x} -> {:#x} ({}, {} syncs so far)", + pair.writer, + pair.reader, + if pair.buffer_through { "buffer-through" } else { "direct copy" }, + n + 1 + ); + } + } + ok +} + +/// Sync active placed-UAV -> format-aliased SRV pairs after a UAV barrier on `list`. +/// When `specific_targets` is `Some(targets)`, only sync pairs whose `writer` is in `targets`; +/// when `None` (global UAV barrier), deduplicate against `bind::activity()`. +pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option<&[usize]>) { + if ACTIVE_PLACED_UAV_PAIRS.load(Ordering::Relaxed) == 0 || list.is_null() { + return; + } + let Some(ty) = list_x::tracked_list_type(list) else { + return; + }; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return; + } + let act = super::bind::activity(); + let dedup = dedup_enabled(); + // Skip duplicate back-to-back global UAV barriers when no draw or dispatch executed in between. + if specific_targets.is_none() { + let mut g = LIST_STATES.lock().unwrap(); + let ls = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if ls.last_activity == act && act != (0, 0) { + note_skipped_sync(); + return; + } + ls.last_activity = act; + ls.list_type = Some(ty); + } + let Some(dev) = list_x::device_of_list(list) else { + return; + }; + let dev_raw = dev.as_raw() as usize; + let mut skipped = 0usize; + let pairs: Vec<(AliasPair, Option, Option)> = { + let g = TABLE.lock().unwrap(); + match g.as_ref() { + Some(t) => t + .pairs + .iter() + .copied() + .filter(|p| { + if p.writer_owner != Owner::PlacedUav + || p.device != dev_raw + || !specific_targets.is_none_or(|targets| targets.contains(&p.writer)) + { + return false; + } + if dedup && act != (0, 0) { + if let Some(w) = t.by_res.get(&p.writer) { + if !w.dirty && w.last_sync_activity == Some(act) { + skipped += 1; + return false; + } + } + } + true + }) + .map(|p| (p, t.clone_internal(p.writer), t.clone_internal(p.reader))) + .collect(), + None => return, + } + }; + for _ in 0..skipped { + note_skipped_sync(); + } + let mut writer_ok: HashMap = HashMap::new(); + for (pair, _writer_pin, _reader_pin) in pairs { + let ok = sync_pair(list, &dev, ty, pair, STATE_UAV); + let entry = writer_ok.entry(pair.writer).or_insert(true); + *entry &= ok; + } + if !writer_ok.is_empty() { + let mut g = TABLE.lock().unwrap(); + if let Some(t) = g.as_mut() { + for (writer, all_ok) in writer_ok { + if all_ok { + if let Some(w) = t.by_res.get_mut(&writer) { + w.dirty = false; + w.last_sync_activity = Some(act); + } + } + } + } + } +} + +/// Sync format-aliased readers for title-owned writers that just transitioned out of write state. +pub(super) unsafe fn sync_title_writers(list: *mut c_void, writers: &[(usize, u32)]) { + if writers.is_empty() || ACTIVE_PAIRS.load(Ordering::Relaxed) == 0 || list.is_null() { + return; + } + let Some(ty) = list_x::tracked_list_type(list) else { + return; + }; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return; + } + let Some(dev) = list_x::device_of_list(list) else { + return; + }; + let dev_raw = dev.as_raw() as usize; + let act = super::bind::activity(); + let mut seen = HashSet::new(); + for &(writer, state) in writers { + if !seen.insert(writer) { + continue; + } + let pairs: Vec<(AliasPair, Option, Option)> = { + let g = TABLE.lock().unwrap(); + match g.as_ref() { + Some(t) => t + .pairs + .iter() + .copied() + .filter(|p| p.writer == writer && p.device == dev_raw) + .map(|p| (p, t.clone_internal(p.writer), t.clone_internal(p.reader))) + .collect(), + None => continue, + } + }; + if pairs.is_empty() { + continue; + } + let mut all_ok = true; + for (pair, _writer_pin, _reader_pin) in pairs { + all_ok &= sync_pair(list, &dev, ty, pair, state); + } + if all_ok { + let mut g = TABLE.lock().unwrap(); + if let Some(w) = g.as_mut().and_then(|t| t.by_res.get_mut(&writer)) { + w.dirty = false; + w.last_sync_activity = Some(act); + } + } + } +} + +/// Return any `PlacedSrv` resources transitioned into read state on `list` back to `COMMON` +/// before `Close()`, keeping cross-queue state invariants clean. +pub(super) unsafe fn before_close(list: *mut c_void) { + if list.is_null() { + return; + } + let pending: Vec<(usize, u32)> = { + let mut g = LIST_STATES.lock().unwrap(); + match g.as_mut().and_then(|m| m.get_mut(&(list as usize))) { + Some(ls) if !ls.srv_states.is_empty() => ls.srv_states.drain().collect(), + _ => return, + } + }; + for (res, state) in pending { + if state != STATE_COMMON { + list_x::transition(list, res, D3D12_RESOURCE_STATES(state as i32), D3D12_RESOURCE_STATE_COMMON); + } + } +} + +/// Clear per-list sync state on `Reset` / `Create` / `Release`. +pub(super) fn list_reset(list: usize) { + if let Some(m) = LIST_STATES.lock().unwrap().as_mut() { + m.remove(&list); + } +} + +/// Intercept `CopyResource(dst, src)` between incompatible DXGI format families of equal texel +/// width (e.g. `R32_UINT` <-> `R9G9B9E5_SHAREDEXP`) and run it through an intermediate buffer. +/// Returns `true` if handled. +pub(super) unsafe fn try_copy_resource(list: *mut c_void, dst: usize, src: usize) -> bool { + if !enabled() || dst == 0 || src == 0 || dst == src { + return false; + } + let (dp, sp) = (dst as *mut c_void, src as *mut c_void); + let (Some(d), Some(s)) = (ID3D12Resource::from_raw_borrowed(&dp), ID3D12Resource::from_raw_borrowed(&sp)) else { + return false; + }; + let (dd, sd) = (d.GetDesc(), s.GetDesc()); + if dd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || sd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + if !needs_buffer_through(dd.Format.0 as u32, sd.Format.0 as u32) { + return false; + } + let Some(dev) = list_x::device_of_list(list) else { + return false; + }; + let ok = copy_all_subresources_through_buffer(list, &dev, d, s); + if ok { + mark_writer_dirty(dst); + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k < 8 || k.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: format-aliased CopyResource fmt {} -> fmt {} ({}x{}) copied via intermediate buffer ({} so far)", + sd.Format.0, + dd.Format.0, + dd.Width, + dd.Height, + k + 1 + ); + } + } + ok +} + +/// Intercept full-subresource texture-to-texture `CopyTextureRegion` between incompatible DXGI +/// format families of equal texel width and run it through an intermediate buffer. +/// Returns `true` if handled. +pub(super) unsafe fn try_copy_texture_region( + list: *mut c_void, + dst: &D3D12_TEXTURE_COPY_LOCATION, + x: u32, + y: u32, + z: u32, + src: &D3D12_TEXTURE_COPY_LOCATION, + bx: *const D3D12_BOX, +) -> bool { + if !enabled() + || dst.Type != D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + || src.Type != D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + || x != 0 + || y != 0 + || z != 0 + || !bx.is_null() + { + return false; + } + let (Some(d), Some(s)) = (dst.pResource.as_ref(), src.pResource.as_ref()) else { + return false; + }; + let (dd, sd) = (d.GetDesc(), s.GetDesc()); + if dd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || sd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + if !needs_buffer_through(dd.Format.0 as u32, sd.Format.0 as u32) { + return false; + } + let Some(dev) = list_x::device_of_list(list) else { + return false; + }; + let ok = copy_one_subresource_through_buffer( + list, + &dev, + d, + &dd, + dst.Anonymous.SubresourceIndex, + s, + &sd, + src.Anonymous.SubresourceIndex, + ); + if ok { + mark_writer_dirty(d.as_raw() as usize); + } + ok +} + +#[cfg(test)] +mod tests { + use super::*; + + fn shape(fmt: u32, w: u64, h: u32, d: u16, mips: u16) -> TexShape { + TexShape { + dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, + width: w, + height: h, + depth_or_array: d, + mip_levels: mips, + format: fmt, + samples: 1, + } + } + + #[test] + fn r32_uint_and_r9g9b9e5_alias_needs_buffer_through() { + assert!(needs_buffer_through(67, 42)); // R9G9B9E5_SHAREDEXP vs R32_UINT + assert!(needs_buffer_through(67, 39)); // R9G9B9E5_SHAREDEXP vs R32_TYPELESS + assert!(!needs_buffer_through(42, 39)); // R32_UINT vs R32_TYPELESS (same family) + assert!(!needs_buffer_through(28, 27)); // R8G8B8A8_UNORM vs R8G8B8A8_TYPELESS + + let s_uav = shape(39, 128, 128, 6, 4); + let s_srv = shape(67, 128, 128, 6, 4); + assert!(can_copy_through_buffer(&s_srv, &s_uav)); + + // 3D volumetric fog froxel texture: R32_UINT UAV -> R9G9B9E5_SHAREDEXP SRV + let fog_uav = TexShape { dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D.0, ..shape(42, 160, 90, 64, 1) }; + let fog_srv = TexShape { dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D.0, ..shape(67, 160, 90, 64, 1) }; + assert!(can_copy_through_buffer(&fog_srv, &fog_uav)); + assert_eq!(fog_srv.subresource_count(), 1); + + // BC7 (16 B per 4x4 block) <-> R32G32B32A32_UINT (16 B per texel, 1/4 width & height) + let bc7 = shape(98, 256, 128, 1, 1); + let u32x4 = shape(3, 64, 32, 1, 1); + assert!(can_copy_through_buffer(&bc7, &u32x4)); + assert!(can_copy_through_buffer(&u32x4, &bc7)); + + // Mismatched dimensions or bpp rejected + assert!(!can_copy_through_buffer(&shape(67, 64, 64, 1, 1), &shape(42, 128, 128, 1, 1))); + assert!(!can_copy_through_buffer(&shape(10, 128, 128, 1, 1), &shape(42, 128, 128, 1, 1))); + } + + #[test] + fn placed_uav_and_srv_descs_are_sanitized() { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + x[0x20..0x24].copy_from_slice(&67u32.to_le_bytes()); // R9G9B9E5_SHAREDEXP + x[0x30..0x34].copy_from_slice(&0x30_0005u32.to_le_bytes()); // RTV | UAV + console bits + + // Placed UAV with R32_UINT view over R9G9B9E5 desc -> R32_TYPELESS + ALLOW_UNORDERED_ACCESS (no RTV) + let uav = prepare_placed_uav_desc(&x, 42); + let uav_fmt = u32::from_le_bytes(uav[0x20..0x24].try_into().unwrap()); + let uav_flags = u32::from_le_bytes(uav[0x30..0x34].try_into().unwrap()); + assert_eq!(uav_fmt, 39, "R32_UINT UAV over R9G9B9E5 must become R32_TYPELESS, not R11G11B10_FLOAT"); + assert!(uav_flags & FLAG_UAV != 0 && uav_flags & FLAG_RENDER_TARGET == 0); + + // Placed SRV with R9G9B9E5 view -> strips RTV|UAV so pc_resource_desc keeps format 67! + let srv = prepare_placed_srv_desc(&x, 67); + let srv_pc = super::super::device_x::pc_resource_desc(&srv); + let srv_fmt = u32::from_le_bytes(srv_pc[0x20..0x24].try_into().unwrap()); + let srv_flags = u32::from_le_bytes(srv_pc[0x30..0x34].try_into().unwrap()); + assert_eq!(srv_fmt, 67, "placed SRV must stay R9G9B9E5_SHAREDEXP"); + assert_eq!(srv_flags & (FLAG_RENDER_TARGET | FLAG_UAV), 0); + } + + #[test] + fn placed_descs_ignore_the_padding_after_dimension() { + // bytes 0x04..0x08 are the padding between `Dimension` and `Alignment`; the title leaves + // stack bytes there, and a different value must not make a second key for the same view + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + x[0x10..0x18].copy_from_slice(&256u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&256u32.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); // R8G8B8A8_UNORM + let mut garbage = x; + garbage[0x04..0x08].copy_from_slice(&[0xd8, 0x7e, 0x3f, 0x01]); + assert_eq!(prepare_placed_srv_desc(&garbage, 28), prepare_placed_srv_desc(&x, 28)); + assert_eq!(prepare_placed_uav_desc(&garbage, 28), prepare_placed_uav_desc(&x, 28)); + assert_eq!(prepare_placed_srv_desc(&garbage, 28)[0x04..0x08], [0u8; 4]); + } + + #[test] + fn alias_table_links_in_both_creation_orders() { + let mut t = AliasTable::new(); + let va = 0x2_0000_0000usize; + let uav_shape = shape(39, 64, 64, 1, 1); + let srv_shape = shape(67, 64, 64, 1, 1); + + // Order 1: SRV created first, placed UAV created second -> links and marks SRV gpu_written + let m1 = t.insert(0x100, TrackedTex::new(1, va, srv_shape, Owner::TitlePlaced, 0, false)); + assert!(m1.is_empty()); + assert!(t.pairs.is_empty()); + + let m2 = t.insert(0x200, TrackedTex::new(1, va, uav_shape, Owner::PlacedUav, STATE_UAV, true)); + assert_eq!(m2, vec![0x100]); + assert_eq!(t.pairs.len(), 1); + assert!(t.pairs[0].buffer_through); + assert_eq!(t.placed_uav_pairs, 1); + + // Order 2: second SRV created after UAV -> links immediately and marks itself gpu_written + let m3 = t.insert(0x300, TrackedTex::new(1, va, srv_shape, Owner::PlacedSrv, 0, false)); + assert_eq!(m3, vec![0x300]); + assert_eq!(t.pairs.len(), 2); + + // Removing the reader cleans up its pair + t.remove(0x100); + assert_eq!(t.pairs.len(), 1); + assert_eq!(t.pairs[0].reader, 0x300); + + // Removing the writer cleans up remaining pairs + t.remove(0x200); + assert!(t.pairs.is_empty()); + assert_eq!(t.placed_uav_pairs, 0); + + // Compute-list state validation rejects RENDER_TARGET (0x4), INDEX_BUFFER (0x2), VCB (0x1), + // DEPTH_WRITE (0x10), PIXEL_SHADER_RESOURCE (0x80), while allowing COMMON/UAV/NON_PIXEL_SRV/COPY. + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_COMMON)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_UAV)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_SRV_NON_PIXEL)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_RENDER_TARGET)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, 0x1)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, 0x2)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_SRV_ALL)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_DIRECT, STATE_RENDER_TARGET)); + + // Subresource footprint compatibility rejects mismatched element byte widths even with equal RowPitch + let fp = |w, h, d| D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(0), + Width: w, + Height: h, + Depth: d, + RowPitch: 256, + }; + assert!(subresource_footprints_compatible(67, &fp(32, 32, 1), 42, &fp(32, 32, 1))); + assert!(!subresource_footprints_compatible(10, &fp(32, 32, 1), 42, &fp(32, 32, 1)), "8 Bpp vs 4 Bpp must be rejected"); + assert!(subresource_footprints_compatible(98, &fp(64, 64, 1), 3, &fp(16, 16, 1)), "BC7 64x64 == R32G32B32A32 16x16"); + } + + #[test] + fn enhanced_common_to_read_skips_unchanged_writer_and_rearms_on_write() { + let dev = 0x7A00_0001usize; + let va = 0x7A00_0000_0000usize; + let writer = 0x7A00_1001usize; + let reader = 0x7A00_1002usize; + let reader2 = 0x7A00_1003usize; + let uav_shape = shape(42, 64, 64, 1, 1); // R32_UINT + let srv_shape = shape(67, 64, 64, 1, 1); // R9G9B9E5_SHAREDEXP + + { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + t.insert(writer, TrackedTex::new(dev, va, uav_shape, Owner::TitlePlaced, STATE_COMMON, true)); + t.insert(reader, TrackedTex::new(dev, va, srv_shape, Owner::TitlePlaced, STATE_COMMON, false)); + } + + let mk_group = |tb: &D3D12_TEXTURE_BARRIER| D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_TEXTURE, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: tb as *const _ }, + }; + let mk_tb = |ab: D3D12_BARRIER_ACCESS, aa: D3D12_BARRIER_ACCESS, lb: D3D12_BARRIER_LAYOUT, la: D3D12_BARRIER_LAYOUT, flags: D3D12_TEXTURE_BARRIER_FLAGS| -> D3D12_TEXTURE_BARRIER { + D3D12_TEXTURE_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_ALL, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: ab, + AccessAfter: aa, + LayoutBefore: lb, + LayoutAfter: la, + pResource: unsafe { std::mem::transmute_copy(&writer) }, + Subresources: D3D12_BARRIER_SUBRESOURCE_RANGE::default(), + Flags: flags, + } + }; + + // 1. Fresh writer starts dirty: COMMON -> SRV triggers initial sync. + let tb_c2r = mk_tb( + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_SHADER_RESOURCE, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + ); + let grp = mk_group(&tb_c2r); + let mut out = Vec::new(); + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert_eq!(out, vec![(writer, STATE_COMMON)]); + + // Simulate completed sync clearing dirty flag. + TABLE.lock().unwrap().as_mut().unwrap().by_res.get_mut(&writer).unwrap().dirty = false; + + // 2. Second COMMON -> SRV with no intervening write must be skipped. + out.clear(); + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert!(out.is_empty(), "unchanged writer must skip redundant COMMON -> SRV copy"); + + // 3. Entering UAV layout (`COMMON -> UAV`) re-arms dirty without syncing yet. + let tb_c2u = mk_tb( + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + ); + let grp_u = mk_group(&tb_c2u); + unsafe { filter_enhanced_barriers(1, &grp_u as *const _ as *const c_void, &mut out) }; + assert!(out.is_empty()); + assert!(TABLE.lock().unwrap().as_ref().unwrap().by_res.get(&writer).unwrap().dirty); + + // 4. Subsequent COMMON -> SRV now syncs again. + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert_eq!(out, vec![(writer, STATE_COMMON)]); + + // 5. Linking a new format-aliased reader re-arms dirty on the writer. + TABLE.lock().unwrap().as_mut().unwrap().by_res.get_mut(&writer).unwrap().dirty = false; + TABLE.lock().unwrap().as_mut().unwrap().insert(reader2, TrackedTex::new(dev, va, srv_shape, Owner::TitlePlaced, STATE_COMMON, false)); + assert!(TABLE.lock().unwrap().as_ref().unwrap().by_res.get(&writer).unwrap().dirty); + + // Prevent ManuallyDrop::drop on synthetic pointer in tb_c2r / tb_c2u (already ManuallyDrop) + // and clean up test entries from global TABLE. + forget(reader2); + forget(reader); + forget(writer); + } + + #[test] + fn cache_insert_or_clone_returns_winner_and_keeps_handle_alive_across_eviction() { + use std::sync::Arc; + + let mut cache: HashMap> = HashMap::new(); + let first = Arc::new(111u32); + let second = Arc::new(222u32); + + // Initial insert: map and caller both hold a reference to `first`. + let (h1, loser1) = cache_insert_or_clone(&mut cache, 0x1000, Arc::clone(&first)); + assert!(loser1.is_none()); + assert_eq!(*h1, 111); + assert_eq!(Arc::strong_count(&first), 3); // local `first` + cache + `h1` + + // Concurrent miss race: returns a handle to the winning `first` and hands `second` + // back to the caller so it can be dropped outside the lock without UAF or deadlock. + let (h2, loser2) = cache_insert_or_clone(&mut cache, 0x1000, Arc::clone(&second)); + assert_eq!(*h2, 111, "concurrent race must return the cached winner, not the loser"); + assert!(Arc::ptr_eq(&h2, &first)); + let loser = loser2.expect("duplicate loser must be returned for outside-lock drop"); + assert!(Arc::ptr_eq(&loser, &second)); + assert_eq!(Arc::strong_count(&second), 2); + drop(loser); + assert_eq!(Arc::strong_count(&second), 1); + + // Concurrent eviction while `h1` / `h2` are in use keeps the resource alive until dropped. + drop(first); + let evicted = cache.remove(&0x1000).unwrap(); + drop(evicted); + assert_eq!(*h1, 111); + assert_eq!(*h2, 111); + assert_eq!(Arc::strong_count(&h1), 2); + drop(h1); + assert_eq!(Arc::strong_count(&h2), 1); + drop(h2); + } +} diff --git a/crates/xcl/src/hle/d3d12x/gpu_awake.rs b/crates/xcl/src/hle/d3d12x/gpu_awake.rs new file mode 100644 index 0000000000..ecca7a012f --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gpu_awake.rs @@ -0,0 +1,412 @@ +//! AMD GPU keep-awake compute heartbeat (`XCL_GPU_AWAKE`). +//! +//! On AMD RDNA2/RDNA3 GPUs, the SMU can drop shader clocks during 1.2–2.4 ms CPU gaps between +//! title command-list submissions, inflating GPU frame time by 20–30%. While the title is actively +//! submitting GPU work (within the last 250 ms), a single lightweight background thread keeps at +//! most two tiny async-compute dispatches in flight on a dedicated `D3D12_COMMAND_LIST_TYPE_COMPUTE` +//! queue so the GPU never falls into deep idle between submits, and sleeps immediately whenever +//! title submission pauses (menus, shader compile stalls, idle). +//! +//! Controlled by `XCL_GPU_AWAKE`: +//! - `0` / `off` / `false`: disabled +//! - `1` / `on` / `true`: forced on +//! - unset / `auto` / other: enabled automatically on AMD adapters (`vendor_id == 0x1002`) + +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use windows::core::{Interface, PCSTR}; +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + +/// PCI vendor ID for AMD GPUs. +const AMD_VENDOR_ID: u32 = 0x1002; +/// How long after the most recent title GPU submit we keep submitting heartbeats. +const ACTIVE_WINDOW_MS: u64 = 250; +/// Sleep interval while the title is idle (no submit within `ACTIVE_WINDOW_MS`). +const IDLE_SLEEP_MS: u64 = 4; +/// Fence wait slice so `stop()` or device removal is noticed promptly. +const WAIT_SLICE_MS: u32 = 100; +/// Bounded drain timeout on clean shutdown before dropping D3D12 objects. +const SHUTDOWN_DRAIN_MS: u32 = 500; + +/// Minimal SM 5.0 compute shader: 64 threads running a 400,000-step LCG and writing 1 uint each +/// (256 bytes total) to a root UAV at `u0` (no descriptor heap required). +const HEARTBEAT_HLSL: &str = r#" +RWByteAddressBuffer dst : register(u0); + +[numthreads(64, 1, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + uint x = tid.x ^ 0x9e3779b9u; + [loop] + for (uint i = 0u; i < 400000u; ++i) { + x = x * 1664525u + 1013904223u; + } + dst.Store(tid.x * 4u, x); +} +"#; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + Off, + On, + Auto, +} + +fn parse_mode(val: Option<&str>) -> Mode { + let Some(raw) = val.map(str::trim).filter(|s| !s.is_empty()) else { + return Mode::Auto; + }; + if raw.eq_ignore_ascii_case("0") || raw.eq_ignore_ascii_case("off") || raw.eq_ignore_ascii_case("false") { + Mode::Off + } else if raw.eq_ignore_ascii_case("1") || raw.eq_ignore_ascii_case("on") || raw.eq_ignore_ascii_case("true") { + Mode::On + } else { + Mode::Auto + } +} + +fn should_enable(mode: Mode, vendor_id: u32) -> bool { + match mode { + Mode::Off => false, + Mode::On => true, + Mode::Auto => vendor_id == AMD_VENDOR_ID, + } +} + +fn configured_mode() -> Mode { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| parse_mode(std::env::var("XCL_GPU_AWAKE").ok().as_deref())) +} + +static STARTED: OnceLock<()> = OnceLock::new(); +static STOP: AtomicBool = AtomicBool::new(false); +static LAST_SUBMIT_MS: AtomicU64 = AtomicU64::new(0); + +fn epoch_ms() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + // +1 so 0 unambiguously means "no title submit observed yet". + EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 + 1 +} + +/// Record that the title just submitted GPU work so the heartbeat thread stays active for the next +/// `ACTIVE_WINDOW_MS` (250 ms). Lock-free single atomic store on the hot submit path. +pub(super) fn note_activity() { + LAST_SUBMIT_MS.store(epoch_ms(), Ordering::Relaxed); +} + +/// Signal the background heartbeat thread to stop cleanly. +pub(super) fn stop() { + STOP.store(true, Ordering::Release); +} + +/// Start the GPU keep-awake heartbeat thread if enabled by `XCL_GPU_AWAKE` (auto-enabled on AMD +/// `vendor_id == 0x1002`). Idempotent via `OnceLock`. +/// +/// # Safety +/// `device` must be a valid live `ID3D12Device`. +pub(super) unsafe fn start(device: &ID3D12Device, vendor_id: u32) { + let mode = configured_mode(); + if !should_enable(mode, vendor_id) { + return; + } + let dev_clone = device.clone(); + STARTED.get_or_init(|| { + STOP.store(false, Ordering::Release); + struct SendDevice(ID3D12Device); + // COM ID3D12Device methods used here are free-threaded per D3D12 spec. + unsafe impl Send for SendDevice {} + let send_dev = SendDevice(dev_clone); + let spawned = std::thread::Builder::new().name("xcl-gpu-awake".into()).spawn(move || { + let dev = send_dev; + run_worker(dev.0, vendor_id); + }); + if let Err(e) = spawned { + crate::xlog_warn!("D3D12.X: failed to spawn xcl-gpu-awake thread: {e}"); + } + }); +} + +fn compile_heartbeat_cs() -> Option> { + unsafe { + let mut blob = None; + let r = D3DCompile( + HEARTBEAT_HLSL.as_ptr() as *const c_void, + HEARTBEAT_HLSL.len(), + PCSTR::null(), + None, + None, + PCSTR(b"main\0".as_ptr()), + PCSTR(b"cs_5_0\0".as_ptr()), + 0, + 0, + &mut blob, + None, + ); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +struct EventGuard(windows_sys::Win32::Foundation::HANDLE); + +impl EventGuard { + fn new() -> Result { + let h = unsafe { windows_sys::Win32::System::Threading::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; + if h.is_null() { + Err("CreateEventW failed".into()) + } else { + Ok(Self(h)) + } + } + + fn as_win_handle(&self) -> HANDLE { + HANDLE(self.0) + } + + fn wait(&self, timeout_ms: u32) { + unsafe { + windows_sys::Win32::System::Threading::WaitForSingleObject(self.0, timeout_ms); + } + } +} + +impl Drop for EventGuard { + fn drop(&mut self) { + if !self.0.is_null() { + unsafe { + windows_sys::Win32::Foundation::CloseHandle(self.0); + } + } + } +} + +struct RecordedSlot { + _alloc: ID3D12CommandAllocator, + _list: ID3D12GraphicsCommandList, + cmd_list: ID3D12CommandList, +} + +struct HeartbeatState { + queue: ID3D12CommandQueue, + _uav_buf: ID3D12Resource, + _root_sig: ID3D12RootSignature, + _pso: ID3D12PipelineState, + slots: [RecordedSlot; 2], + fence: ID3D12Fence, + event: EventGuard, +} + +unsafe fn init_state(device: &ID3D12Device) -> Result { + let bytecode = compile_heartbeat_cs().ok_or_else(|| "D3DCompile failed for heartbeat compute shader".to_string())?; + + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, + Priority: D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0, + Flags: D3D12_COMMAND_QUEUE_FLAG_NONE, + NodeMask: 0, + }) + .map_err(|e| format!("CreateCommandQueue(COMPUTE) failed: {e}"))?; + + let mut uav_opt: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + &mut uav_opt, + ) + .map_err(|e| format!("CreateCommittedResource(UAV) failed: {e}"))?; + let uav_buf = uav_opt.ok_or_else(|| "CreateCommittedResource(UAV) returned null".to_string())?; + let uav_va = uav_buf.GetGPUVirtualAddress(); + + let param = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: 1, + pParameters: ¶m, + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }; + let mut rs_blob = None; + D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut rs_blob, None) + .map_err(|e| format!("D3D12SerializeRootSignature failed: {e}"))?; + let rs_blob = rs_blob.ok_or_else(|| "D3D12SerializeRootSignature returned null blob".to_string())?; + let rs_bytes = std::slice::from_raw_parts(rs_blob.GetBufferPointer() as *const u8, rs_blob.GetBufferSize()); + let root_sig: ID3D12RootSignature = device + .CreateRootSignature(0, rs_bytes) + .map_err(|e| format!("CreateRootSignature failed: {e}"))?; + + let mut pso_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(root_sig.clone())), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytecode.as_ptr() as *const c_void, + BytecodeLength: bytecode.len(), + }, + ..Default::default() + }; + let pso_res: windows::core::Result = device.CreateComputePipelineState(&pso_desc); + ManuallyDrop::drop(&mut pso_desc.pRootSignature); + let pso = pso_res.map_err(|e| format!("CreateComputePipelineState failed: {e}"))?; + + let make_slot = || -> Result { + let alloc: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE) + .map_err(|e| format!("CreateCommandAllocator(COMPUTE) failed: {e}"))?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, Some(&pso)) + .map_err(|e| format!("CreateCommandList(COMPUTE) failed: {e}"))?; + list.SetComputeRootSignature(&root_sig); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, uav_va); + list.Dispatch(1, 1, 1); + list.Close().map_err(|e| format!("CommandList::Close failed: {e}"))?; + let cmd_list: ID3D12CommandList = list.cast().map_err(|e| format!("cast to ID3D12CommandList failed: {e}"))?; + Ok(RecordedSlot { _alloc: alloc, _list: list, cmd_list }) + }; + let slots = [make_slot()?, make_slot()?]; + + let fence: ID3D12Fence = device + .CreateFence(0, D3D12_FENCE_FLAG_NONE) + .map_err(|e| format!("CreateFence failed: {e}"))?; + let event = EventGuard::new()?; + + Ok(HeartbeatState { + queue, + _uav_buf: uav_buf, + _root_sig: root_sig, + _pso: pso, + slots, + fence, + event, + }) +} + +fn run_worker(device: ID3D12Device, vendor_id: u32) { + let state = match super::title_textures::own_work(|| unsafe { init_state(&device) }) { + Ok(s) => s, + Err(e) => { + crate::xlog_warn!("D3D12.X: GPU keep-awake heartbeat disabled ({e})"); + return; + } + }; + crate::xlog_info!("D3D12.X: GPU keep-awake async-compute heartbeat active (vendor {vendor_id:#06x}, XCL_GPU_AWAKE=0 to disable)"); + + let mut fence_val: u64 = 0; + while !STOP.load(Ordering::Acquire) { + if unsafe { device.GetDeviceRemovedReason() }.is_err() { + break; + } + let last = LAST_SUBMIT_MS.load(Ordering::Relaxed); + let now = epoch_ms(); + if last == 0 || now.saturating_sub(last) > ACTIVE_WINDOW_MS { + std::thread::sleep(Duration::from_millis(IDLE_SLEEP_MS)); + continue; + } + + // Keep at most 2 dispatches in flight: wait until the slot we are about to reuse has + // finished executing on the GPU (`fence >= fence_val - 1`). + let wait_target = fence_val.saturating_sub(1); + if wait_target > 0 { + loop { + let completed = unsafe { state.fence.GetCompletedValue() }; + if completed == u64::MAX || unsafe { device.GetDeviceRemovedReason() }.is_err() { + return; + } + if completed >= wait_target || STOP.load(Ordering::Acquire) { + break; + } + if unsafe { state.fence.SetEventOnCompletion(wait_target, state.event.as_win_handle()) }.is_err() { + return; + } + state.event.wait(WAIT_SLICE_MS); + } + if STOP.load(Ordering::Acquire) { + break; + } + } + + let slot_idx = (fence_val as usize) & 1; + let next_val = fence_val + 1; + let submitted = super::title_textures::own_work(|| unsafe { + state.queue.ExecuteCommandLists(&[Some(state.slots[slot_idx].cmd_list.clone())]); + state.queue.Signal(&state.fence, next_val).is_ok() + }); + if !submitted { + break; + } + fence_val = next_val; + } + + // Drain in-flight heartbeats briefly on clean stop so GPU finishes before COM objects drop. + if fence_val > 0 && unsafe { device.GetDeviceRemovedReason() }.is_ok() { + let completed = unsafe { state.fence.GetCompletedValue() }; + if completed < fence_val && completed != u64::MAX { + if unsafe { state.fence.SetEventOnCompletion(fence_val, state.event.as_win_handle()) }.is_ok() { + state.event.wait(SHUTDOWN_DRAIN_MS); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn env_mode_parsing_and_amd_auto_enable() { + assert_eq!(parse_mode(None), Mode::Auto); + assert_eq!(parse_mode(Some("")), Mode::Auto); + assert_eq!(parse_mode(Some("auto")), Mode::Auto); + assert_eq!(parse_mode(Some("unknown")), Mode::Auto); + + for off in ["0", "off", "OFF", "false", "False", " 0 "] { + assert_eq!(parse_mode(Some(off)), Mode::Off, "expected Off for {off:?}"); + } + for on in ["1", "on", "ON", "true", "True", " 1 "] { + assert_eq!(parse_mode(Some(on)), Mode::On, "expected On for {on:?}"); + } + + // Auto enables only for AMD (0x1002); On/Off override regardless of vendor. + assert!(should_enable(Mode::Auto, AMD_VENDOR_ID)); + assert!(!should_enable(Mode::Auto, 0x10DE)); // NVIDIA + assert!(!should_enable(Mode::Auto, 0x8086)); // Intel + assert!(!should_enable(Mode::Off, AMD_VENDOR_ID)); + assert!(should_enable(Mode::On, 0x10DE)); + assert!(should_enable(Mode::On, 0x8086)); + } + + #[test] + fn heartbeat_hlsl_compiles_with_d3dcompile() { + let bc = compile_heartbeat_cs().expect("HEARTBEAT_HLSL failed D3DCompile(cs_5_0)"); + assert!(bc.len() >= 32, "expected valid DXBC container, got {} bytes", bc.len()); + assert_eq!(&bc[..4], b"DXBC", "expected DXBC magic header"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/indirect_guard.rs b/crates/xcl/src/hle/d3d12x/indirect_guard.rs index e34169cfc4..1921a0946f 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_guard.rs +++ b/crates/xcl/src/hle/d3d12x/indirect_guard.rs @@ -240,6 +240,8 @@ unsafe fn make(dev: &ID3D12Device) -> Result { let pso: ID3D12PipelineState = dev .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }) .map_err(|e| format!("CreateComputePipelineState: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from("xcl indirect_guard")); + super::dred::label_text(pso.as_raw() as usize, || "xcl indirect_guard".to_string()); let buffer = |heap: D3D12_HEAP_PROPERTIES, width: u64| -> Result { let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 3973ef4f23..3323175647 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -229,6 +229,7 @@ pub unsafe fn drain_known(seal_now: bool) { } } queues.extend(super::sparse::queue()); + queues.extend(super::vram::queues()); queues.extend(super::title_textures::upload_queues()); let gone = match HELD.lock().unwrap().as_mut() { Some(h) => h.drain(&queues, seal_now), diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 19eccb57af..7dc8182acc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -132,6 +132,95 @@ pub(super) unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RES pc::(list, PC_RESOURCE_BARRIER)(list, 1, &b); } +pub(super) unsafe fn pc_resource_barriers(list: *mut c_void, barriers: &[D3D12_RESOURCE_BARRIER]) { + if !barriers.is_empty() { + pc::(list, PC_RESOURCE_BARRIER)(list, barriers.len() as u32, barriers.as_ptr()); + } +} + +pub(super) unsafe fn pc_copy_resource(list: *mut c_void, dst: usize, src: usize) { + pc::(list, PC_COPY_RESOURCE)(list, dst, src); +} + +pub(super) unsafe fn pc_copy_texture_region( + list: *mut c_void, + dst: *const D3D12_TEXTURE_COPY_LOCATION, + x: u32, + y: u32, + z: u32, + src: *const D3D12_TEXTURE_COPY_LOCATION, + bx: *const D3D12_BOX, +) { + pc::(list, PC_COPY_TEXTURE_REGION)( + list, dst, x, y, z, src, bx, + ); +} + +pub(super) unsafe fn device_of_list(list: *mut c_void) -> Option { + let l = ID3D12GraphicsCommandList::from_raw_borrowed(&list)?; + let mut dev: Option = None; + l.GetDevice(&mut dev).ok()?; + dev +} + +pub(super) unsafe fn acquire_scratch_for_copy(list: *mut c_void, n: u64) -> Option { + if n == 0 || n > MAX_COPY_SCRATCH || list_type(list) == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return None; + } + let bytes = n.next_power_of_two().max(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64).min(MAX_COPY_SCRATCH); + let (raw, cap) = COPY_SCRATCH.lock().unwrap().acquire(list, bytes)?; + (cap >= n).then_some(raw) +} + +/// Restore title bindings, PC root signatures, and bound PSO after an internal compute pass. +pub(super) unsafe fn restore_after_internal_pass(list: *mut c_void, clobbered_gfx: bool, clobbered_cs: bool) { + let (bindings, bound_pso, ty, depth_bias, native_bias, had_fallback) = { + let mut g = recording(list as usize).lock().unwrap(); + match g.as_mut().and_then(|m| m.get_mut(&(list as usize))) { + Some(s) => { + let had_fallback = s.using_fallback_pso; + if had_fallback { + s.using_fallback_pso = false; + s.pso_dirty = true; + } + ( + s.bindings.clone(), + s.bound_pso, + s.list_type.unwrap_or(D3D12_COMMAND_LIST_TYPE_DIRECT), + s.depth_bias, + s.native_bias, + had_fallback, + ) + } + None => return, + } + }; + restore_bindings(list, &bindings, ty); + let (rs_gfx, rs_cs) = super::bind::tracked_root_sigs(list); + if clobbered_gfx && rs_gfx != 0 { + pc::(list, 30)(list, rs_gfx); + } + if clobbered_cs && rs_cs != 0 { + pc::(list, 29)(list, rs_cs); + } + if bound_pso != 0 { + let resolved = super::pso_async::resolve_for_bind(bound_pso); + pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); + if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE { + if let Some((true, static_bias)) = device_x::base_depth_bias_info(bound_pso) { + let target = depth_bias.unwrap_or(static_bias); + if target != DepthBias::ZERO || native_bias != DepthBias::ZERO { + let _ = try_native_depth_bias(list, target); + } + } else if depth_bias.is_some() && !had_fallback { + if let Some(s) = recording(list as usize).lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.pso_dirty = true; + } + } + } + } +} + /// `op` with the window buffer `res` as a copy destination (back to COMMON after it) unsafe fn as_copy_dest(list: *mut c_void, res: usize, op: impl FnOnce()) { transition(list, res, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); @@ -932,6 +1021,16 @@ unsafe fn try_native_depth_bias(list: *mut c_void, bias: DepthBias) -> bool { /// # Safety /// `list` must be null or a valid `ID3D12GraphicsCommandList` COM pointer. pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { + on_create_with_backing(list, alloc, alloc, pso, ty); +} + +pub unsafe fn on_create_with_backing( + list: *mut c_void, + title_alloc: usize, + pc_alloc: usize, + pso: usize, + ty: D3D12_COMMAND_LIST_TYPE, +) { if list.is_null() { return; } @@ -953,12 +1052,13 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); } } - super::alloc_pool::created_on(key, alloc, ty.0); - m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); + super::alloc_pool::created_on(key, pc_alloc, ty.0); + m.insert(key, ListState { allocator: title_alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); old }; drop(old); super::title_textures::list_reset(key); + super::format_alias::list_reset(key); // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE && pso != 0 { @@ -977,6 +1077,7 @@ pub(super) fn on_release(list: usize) { super::alloc_pool::forget_list(list); release_copy_scratch(list); super::title_textures::list_reset(list); + super::format_alias::list_reset(list); let old = recording(list).lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { if !old.pending_waits.is_empty() { @@ -1004,6 +1105,7 @@ pub(super) fn on_release(list: usize) { pub(super) fn clear_segment_state(list: usize) { super::alloc_pool::unpin_list(list); super::title_textures::list_reset(list); + super::format_alias::list_reset(list); if let Some(s) = recording(list).lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { s.occlusion = Occlusion::default(); s.written_ranges.clear(); @@ -3564,7 +3666,7 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 /// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH /// build passes): emits a global UAV barrier so UMA writes become visible to the next pass -pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _barriers: *const c_void) { +pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, barriers: *const c_void) { let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -3573,6 +3675,12 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _ }, }; pc::(this, PC_RESOURCE_BARRIER)(this, 1, &b); + let mut alias_writers: Vec<(usize, u32)> = Vec::new(); + super::format_alias::filter_enhanced_barriers(n, barriers, &mut alias_writers); + if !alias_writers.is_empty() { + super::format_alias::sync_title_writers(this, &alias_writers); + } + super::format_alias::on_uav_barrier(this, None); } /// A UAV barrier for all resources on `list`, where a list takes one (a copy list and a bundle @@ -3655,6 +3763,7 @@ unsafe fn predication_buffer(list: *mut c_void) -> Option { /// Before `Close()` on a command list: return `pred_buf` to `COMMON` if it is currently in /// `D3D12_RESOURCE_STATE_PREDICATION`. pub(super) unsafe fn before_close(list: *mut c_void) { + super::format_alias::before_close(list); if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { return; } @@ -3678,6 +3787,7 @@ pub(super) unsafe fn before_close(list: *mut c_void) { /// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); + super::format_alias::list_reset(list as usize); if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { return; } @@ -3886,6 +3996,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { // what ran is in the textures' states; the list records anew after its Reset below super::title_textures::submitted(&one); super::title_textures::list_reset(this as usize); + super::format_alias::list_reset(this as usize); if !sparse_writes.0.is_empty() || !sparse_writes.1.is_empty() { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { super::sparse::readback_after_execute(q, &sparse_writes.0, &sparse_writes.1); @@ -4690,6 +4801,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; super::title_textures::list_reset(this as usize); + super::format_alias::list_reset(this as usize); // (what the new recording puts in unified memory belongs to the PC allocator it is on) super::bind::reset(this, on, pso); if !is_bundle && pso != 0 { @@ -4719,6 +4831,9 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 let mut out: Vec<[u32; 8]> = Vec::with_capacity(n as usize + 1); // a UAV barrier for all resources is in `out` / a transition from or to UNORDERED_ACCESS let (mut any_uav, mut uav_transition) = (false, false); + let mut alias_writers: Vec<(usize, u32)> = Vec::new(); + let mut uav_targets: Vec = Vec::new(); + let mut uav_global = false; for k in 0..n as usize { let mut b = barriers.add(k).read_unaligned(); let (ty, flags) = (b[0], b[1]); @@ -4752,6 +4867,12 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 // window buffers – other resources over the same memory – which a UAV barrier for // the title's resource alone does not order (AMD drivers wait and flush for any UAV // barrier, NVIDIA's need not): a UAV barrier for all resources, once per batch + let uav_res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + if uav_res == 0 { + uav_global = true; + } else { + uav_targets.push(uav_res); + } b[2..4].fill(0); if any_uav { continue; @@ -4778,6 +4899,8 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } // UAV writes before (or after) the transition: the same holds for the window buffers uav_transition |= (b[5] | b[6]) & UNORDERED_ACCESS != 0; + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + super::format_alias::note_title_transition(res, b[4], b[5], b[6], flags, &mut alias_writers); } out.push(b); } @@ -4820,6 +4943,13 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if let Some(p) = &plane_copies { plane_copies_on(this, &p.to_twin, true); } + if !alias_writers.is_empty() { + super::format_alias::sync_title_writers(this, &alias_writers); + } + if any_uav || uav_transition { + let targets = if uav_global || uav_targets.is_empty() { None } else { Some(uav_targets.as_slice()) }; + super::format_alias::on_uav_barrier(this, targets); + } } /// The copies between depth planes and their twins around a title's barriers @@ -4835,7 +4965,14 @@ unsafe fn plane_copies_on(list: *mut c_void, copies: &[super::depth_uav::PlaneCo let at = |res: usize, k: u32| D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k } }; let copy = pc::(list, PC_COPY_TEXTURE_REGION); let (copy_src, copy_dst) = (D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + let (mut clobbered_gfx, mut clobbered_cs) = (false, false); for c in copies { + if let Some(steps) = c.r24g8_steps { + let (cg, cc) = super::depth_uav::execute_r24g8_copy(list, c, steps, to_twin); + clobbered_gfx |= cg; + clobbered_cs |= cc; + continue; + } let twin = c.twin.as_raw() as usize; let twin_in = if to_twin { copy_dst } else { copy_src }; if to_twin { @@ -4849,6 +4986,9 @@ unsafe fn plane_copies_on(list: *mut c_void, copies: &[super::depth_uav::PlaneCo } barriers(&[tr(twin, all, twin_in, UNORDERED_ACCESS)]); } + if clobbered_gfx || clobbered_cs { + restore_after_internal_pass(list, clobbered_gfx, clobbered_cs); + } } /// D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER | INDEX_BUFFER: valid for buffers only @@ -5041,7 +5181,9 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds note_copy_into(this as usize, transmute_copy::<_, usize>(&l.pResource), f.Offset, n); } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; - pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); + if !super::format_alias::try_copy_texture_region(this, &d, x, y, z, &s, bx) { + pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); + } std::mem::forget((d, s)); // borrowed resource pointers } @@ -5131,6 +5273,13 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi return refused(); } }; + if real::is_unaligned_delta_uav(cpu as usize) { + static N: AtomicU64 = AtomicU64::new(0); + if once(&N, 4) { + crate::xlog_warn!("D3D12.X: ClearUnorderedAccessView skipped for unaligned delta buffer UAV (cpu {cpu:#x}, res {res:#x})"); + } + return refused(); + } let Some(res) = uav_clear_resource(res, gpu_slot) else { return refused() }; pc::(this, slot)(this, gpu, cpu, res, values, n, rects) } @@ -5173,6 +5322,7 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: /// command list #19 ResolveSubresource(dst, dst sub, src, src sub, format) (PC #19) pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { + let format = super::device_x::pc_target_format(format as u32) as i32; let _c = super::capture::op(this, || { use super::capture as c; Some(c::Op::Resolve { dst: c::describe(dst), dst_sub, src: c::describe(src), src_sub, format, region: None }) @@ -5187,6 +5337,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds /// mode) (PC #64) #[allow(clippy::too_many_arguments)] pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_void, dst: usize, dst_sub: u32, x: u32, y: u32, src: usize, src_sub: u32, rect: *const windows::Win32::Foundation::RECT, format: i32, mode: i32) { + let format = super::device_x::pc_target_format(format as u32) as i32; let _c = super::capture::op(this, || { use super::capture as c; let r = rect.as_ref().map(|r| [r.left, r.top, r.right, r.bottom]); @@ -5218,7 +5369,10 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { note_copy_into(this as usize, dst, 0, u64::MAX); - return pc::(this, PC_COPY_RESOURCE)(this, dst, src); + if !super::format_alias::try_copy_resource(this, dst, src) { + pc::(this, PC_COPY_RESOURCE)(this, dst, src); + } + return; } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); copy_buffer_region_x(this, dst, 0, src, 0, n); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 1b4c01d236..4bfe7c7437 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -16,7 +16,9 @@ mod capture; pub mod console_heap; pub mod console_list; pub mod clamp; +mod ambient; mod depth_uav; +mod format_alias; pub mod device_x; pub mod dxgi_device; mod cpu_writes; @@ -25,6 +27,7 @@ mod fence_x; pub mod file_reads; pub mod frame; pub(crate) mod gfx_records; +mod gpu_awake; mod gpu_profile; mod gpu_times; pub mod guard; @@ -53,6 +56,7 @@ pub mod title_textures; mod uma_driver; pub mod view_want; pub mod vram; +mod vram_small; mod worker_pool; use std::ffi::c_void; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d6daec1221..4941f9329d 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -127,8 +127,10 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u if let Some(t) = LAST.lock().unwrap().replace(now) { crate::xlog_info!("D3D12.X: {frames} frames presented, {:.1} fps over the last 300", 300.0 / (now - t).as_secs_f64()); } + crate::gpu::rt_leave_out::check_structures(); } super::real::stop_if_device_removed(); + super::alloc_pool::release_finished(); if !PRESENTX.swap(true, Ordering::Relaxed) { crate::xlog_info!("D3D12.X: PresentX – the title presents its own frames ({plane_count} plane(s))"); } @@ -328,6 +330,7 @@ pub fn activity() -> (u64, u64) { pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { EXECUTES.fetch_add(1, Ordering::Relaxed); + super::bind::note_records_queue(queue as usize, lists); { let mut q = QUEUES.lock().unwrap(); if !q.contains(&(queue as usize)) { @@ -1335,15 +1338,36 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, } /// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder (`XCL_FRAME_DUMP=n`, -/// n > 1: every n-th; a title loading at a few frames a second shows few) +/// n > 1: every n-th; a title loading at a few frames a second shows few). +/// `XCL_FRAME_DUMP_FROM=k`: suppress dumps before frame `k`; when set alongside `XCL_FRAME_DUMP=1`, +/// dumps every frame from `k` onward so world frames can be inspected without dumping loading screens. /// (`frame_.bmp`, a quarter of each side; `XCL_FRAME_DUMP_FULL=1`: full size) – what the title presented, before the window. fn frame_dump_due() -> bool { + static FROM: std::sync::OnceLock = std::sync::OnceLock::new(); + let from = *FROM.get_or_init(|| std::env::var("XCL_FRAME_DUMP_FROM").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); let every = *EVERY.get_or_init(|| match std::env::var("XCL_FRAME_DUMP") { - Ok(v) => v.parse().ok().filter(|&n| n > 1).unwrap_or(120), + Ok(v) => { + let n = v.trim().parse::().ok(); + if from > 0 && n == Some(1) { + 1 + } else { + n.filter(|&n| n > 1).unwrap_or(120) + } + } Err(_) => 0, }); - every > 0 && PRESENTS.load(Ordering::Relaxed) % every == 20.min(every - 1) + if every == 0 { + return false; + } + let cur = PRESENTS.load(Ordering::Relaxed); + if cur < from { + return false; + } + if every == 1 { + return true; + } + cur % every == 20.min(every - 1) } /// Frames shown so far. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5925dc0da4..fcb693eeca 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -462,11 +462,13 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { } } let w0_va = bufs.first().map_or(0, |b| b.1); + let win_vas: Vec = bufs.iter().enumerate().filter(|(_, b)| b.1 != 0).map(|(k, b)| format!("w{k}={:#x}", b.1)).collect(); crate::xlog_info!( - "D3D12.X: UMA opened ({} sparse VRAM window(s), {} MB coherent window), window 0 buffer at VA {:#x}", + "D3D12.X: UMA opened ({} sparse VRAM window(s), {} MB coherent window), window 0 buffer at VA {:#x} [{}]", sparse.len(), u.size() >> 20, - w0_va + w0_va, + win_vas.join(", ") ); *UMA_HEAPS.lock().unwrap() = heaps; for (k, buf) in &shadows { @@ -665,6 +667,7 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result> 20); break; @@ -1429,7 +1432,7 @@ fn view_shape_desc( ) -> Option<(u32, crate::gpu::desc::ImageType, u32, u32, u32, u32, u32, u32)> { use crate::gpu::desc::ImageType as T; let f = if format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN { r.Format } else { format }; - let fmt = crate::gpu::desc::gfx10_format(f).unwrap_or(0); + let fmt = view_tsharp_format(f); let (w, h, d) = (r.Width as u32, r.Height, r.DepthOrArraySize as u32); let ty = view_dim_to_image_type(dim)?; let depth = match ty { @@ -1455,6 +1458,16 @@ fn view_shape_desc( Some((fmt, ty, w, h, depth, base_level, last_level, max_mip)) } +/// The GFX10 format in the T# of a view in PC format `f` (0, a float image, when the table has +/// none). The PC's stencil views (X32_TYPELESS_G8X24_UINT, X24_TYPELESS_G8_UINT) are not in the +/// table but are UINT views: they get 8_UINT, so that translated shaders load them as integers +/// (`img_cls`); a float load of a UINT view is undefined in D3D12. +fn view_tsharp_format(f: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> u32 { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UINT, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT}; + let f = if f == DXGI_FORMAT_X24_TYPELESS_G8_UINT || f == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT { DXGI_FORMAT_R8_UINT } else { f }; + crate::gpu::desc::gfx10_format(f).unwrap_or(0) +} + /// Build the XCL shader-ABI T# for an SRV, populating GFX10 `BASE_LEVEL` (`t[3][15:12]`), /// `LAST_LEVEL` (`t[3][19:16]`, or `log2(SampleDesc.Count)` for MSAA), and `MAX_MIP` (`t[5][7:4]`). fn srv_tsharp_from_desc(slot_index: u32, r: &D3D12_RESOURCE_DESC, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option<[u32; 8]> { @@ -2009,6 +2022,8 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::placements::gone(this as usize); } super::depth_uav::forget(this as usize); + super::format_alias::forget(this as usize); + super::ambient::forget_resource(this as usize); super::title_textures::forget(this as usize); super::lut3d::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); @@ -2482,12 +2497,7 @@ unsafe extern "system" fn dev_create_uav_checked_x( rd.Format.0 ); } - let null_dim = desc.as_ref().map_or_else(|| default_uav_dimension(&rd), |d| d.ViewDimension); - let null_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, - ViewDimension: null_dim, - ..Default::default() - }; + let null_desc = null_uav_desc(desc.as_ref(), Some(&rd)); return dev_create_uav_x(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_desc, cpu); } if let Some(ref c) = patched { @@ -2669,6 +2679,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, // and what rays read past it: the rest of the top level, its bottom levels, the // parent pointers (`bvh_want`; `XCL_BVH_WALK=0`: the 64 KiB above only) super::bvh_want::view_made(va); + crate::gpu::rt_leave_out::note_structure(va); let w = crate::gpu::desc::bvh_words(va, true); return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); } @@ -2726,6 +2737,8 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, // A null image SRV was already created and published at `slot.index`. Writing `[0; 8]` // would point shaders at `ResourceDescriptorHeap[0]` (memory window 0 / uninitialized), // so write a valid T# referencing `slot.index` with the view's format class and type. + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, false); if let Some(v) = desc.as_ref() { if let Some(ty) = view_dim_to_image_type(v.ViewDimension.0) { let fmt = crate::gpu::desc::gfx10_format(v.Format).unwrap_or(0); @@ -2735,12 +2748,16 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } return super::console_heap::write(&slot, &[0; 8]); }; + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); } let rdesc = r.GetDesc(); + let amb_fmt = desc.as_ref().map(|v| v.Format.0).filter(|&f| f != 0).unwrap_or(rdesc.Format.0); + super::ambient::note_descriptor(slot.at, amb_idx, res as usize, amb_fmt, rdesc.Format.0, false); super::lut3d::viewed(res as usize, &rdesc, desc.as_ref(), slot.index, cpu); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => super::console_heap::write(&slot, &t), @@ -2775,6 +2792,19 @@ fn cube_as_cube_array(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> Option bool { + static ALLOWED: OnceLock = OnceLock::new(); + *ALLOWED.get_or_init(|| { + match std::env::var("XCL_RT_GATE").ok().map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("miss" | "hold" | "1" | "on" | "true") => false, + _ => true, + } + }) +} + +#[allow(dead_code)] unsafe fn resource_at(this: *mut c_void, desc: *const u8, va: u64) -> *mut c_void { type Key = (u64, [u8; 0x38]); static MADE: Mutex>> = Mutex::new(None); @@ -2817,7 +2847,10 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u super::view_want::want(super::view_want::Path::ViewAt, at, len); return super::console_heap::write(&slot, &words); } - dev_create_srv_x(this, resource_at(this, rdesc, va), &v, cpu); + let placed = super::format_alias::placed_srv_resource(this, rdesc, va, v.Format.0 as u32); + let res = placed.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw); + dev_create_srv_x(this, res, &v, cpu); + drop(placed); } /// device #71: the same for an unordered access view ({ the PC's UAV desc; GPU address @0x28; @@ -2830,13 +2863,17 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let v = (view as *const D3D12_UNORDERED_ACCESS_VIEW_DESC).read_unaligned(); if v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER { let Some(slot) = super::console_heap::slot(cpu) else { return }; + note_unaligned_delta_uav(slot.pc_uav as usize, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); super::view_want::want(super::view_want::Path::ViewAt, at, len); return super::console_heap::write(&slot, &words); } - dev_create_uav_x(this, resource_at(this, rdesc, va), std::ptr::null_mut(), &v, cpu); + let placed = super::format_alias::placed_uav_resource(this, rdesc, va, v.Format.0 as u32); + let res = placed.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw); + dev_create_uav_x(this, res, std::ptr::null_mut(), &v, cpu); + drop(placed); } /// V# of `n` elements from element `first` of the buffer at `va`, and the bytes it covers @@ -2874,6 +2911,7 @@ fn null_uav_desc( use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT; let dim = desc .map(|v| v.ViewDimension.0) + .filter(|&d| d != 0) .or_else(|| rd.map(resource_dim_to_view)) .unwrap_or(D3D12_UAV_DIMENSION_TEXTURE2D.0); match dim { @@ -2889,7 +2927,7 @@ fn null_uav_desc( Texture1DArray: D3D12_TEX1D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 0, ArraySize: 1 }, }, }, - 5 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + 5 | 7 => D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_FLOAT, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { @@ -2911,6 +2949,37 @@ fn null_uav_desc( } } +/// Map a typeless or depth DXGI format to a concrete same-family SRV format so +/// `CreateShaderResourceView` never receives a `*_TYPELESS` or depth-only format. +fn concrete_srv_format(fmt: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT { + use windows::Win32::Graphics::Dxgi::Common::*; + match fmt { + DXGI_FORMAT_R32G32B32A32_TYPELESS => DXGI_FORMAT_R32G32B32A32_FLOAT, + DXGI_FORMAT_R32G32B32_TYPELESS => DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R16G16B16A16_TYPELESS => DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R32G32_TYPELESS => DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R32G8X24_TYPELESS | DXGI_FORMAT_D32_FLOAT_S8X24_UINT => DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, + DXGI_FORMAT_R10G10B10A2_TYPELESS => DXGI_FORMAT_R10G10B10A2_UNORM, + DXGI_FORMAT_R8G8B8A8_TYPELESS => DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16_TYPELESS => DXGI_FORMAT_R16G16_FLOAT, + DXGI_FORMAT_R32_TYPELESS | DXGI_FORMAT_D32_FLOAT => DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R24G8_TYPELESS | DXGI_FORMAT_D24_UNORM_S8_UINT => DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + DXGI_FORMAT_R8G8_TYPELESS => DXGI_FORMAT_R8G8_UNORM, + DXGI_FORMAT_R16_TYPELESS | DXGI_FORMAT_D16_UNORM => DXGI_FORMAT_R16_UNORM, + DXGI_FORMAT_R8_TYPELESS => DXGI_FORMAT_R8_UNORM, + DXGI_FORMAT_BC1_TYPELESS => DXGI_FORMAT_BC1_UNORM, + DXGI_FORMAT_BC2_TYPELESS => DXGI_FORMAT_BC2_UNORM, + DXGI_FORMAT_BC3_TYPELESS => DXGI_FORMAT_BC3_UNORM, + DXGI_FORMAT_BC4_TYPELESS => DXGI_FORMAT_BC4_UNORM, + DXGI_FORMAT_BC5_TYPELESS => DXGI_FORMAT_BC5_UNORM, + DXGI_FORMAT_B8G8R8A8_TYPELESS => DXGI_FORMAT_B8G8R8A8_UNORM, + DXGI_FORMAT_B8G8R8X8_TYPELESS => DXGI_FORMAT_B8G8R8X8_UNORM, + DXGI_FORMAT_BC6H_TYPELESS => DXGI_FORMAT_BC6H_UF16, + DXGI_FORMAT_BC7_TYPELESS => DXGI_FORMAT_BC7_UNORM, + f => f, + } +} + /// Companion SRV for an image UAV slot so translated shaders can read from the UAV's T# /// (`ResourceDescriptorHeap[slot.index]`). Returns `None` for buffer or unsupported dimensions. /// When `null_resource` is true (either `pResource == NULL` or `DENY_SHADER_RESOURCE`), @@ -2950,7 +3019,7 @@ fn uav_companion_srv( None => { let r = rd?; let dim = resource_dim_to_view(r); - if !matches!(dim, 2 | 3 | 4 | 5 | 8) { + if !matches!(dim, 2 | 3 | 4 | 5 | 6 | 7 | 8) { return None; } (dim, r.Format, 0, 0, r.DepthOrArraySize as u32, 0) @@ -2977,6 +3046,7 @@ fn uav_companion_srv( (mip, first_slice, array, plane) }; + let msaa = !null_resource && rd.is_some_and(|r| r.SampleDesc.Count > 1); let mut srv = match dim { 2 => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: fmt, @@ -3000,7 +3070,7 @@ fn uav_companion_srv( }, }, }, - 4 => D3D12_SHADER_RESOURCE_VIEW_DESC { + 4 if !msaa => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: fmt, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, @@ -3008,7 +3078,13 @@ fn uav_companion_srv( Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: mip, MipLevels: 1, PlaneSlice: plane, ResourceMinLODClamp: 0.0 }, }, }, - 5 => D3D12_SHADER_RESOURCE_VIEW_DESC { + 4 | 6 => D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DMS, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2DMS: D3D12_TEX2DMS_SRV::default() }, + }, + 5 if !msaa => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: fmt, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, @@ -3023,6 +3099,14 @@ fn uav_companion_srv( }, }, }, + 5 | 7 => D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DMSArray: D3D12_TEX2DMS_ARRAY_SRV { FirstArraySlice: first_slice, ArraySize: array_size }, + }, + }, 8 => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: fmt, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE3D, @@ -3039,9 +3123,238 @@ fn uav_companion_srv( srv = v; } } + srv.Format = concrete_srv_format(srv.Format); Some(srv) } +/// PC UAV CPU descriptor handles that were replaced by a null buffer UAV because the placed +/// buffer's `buffer_delta` was not element-aligned (or its counter offset was not 4096-aligned). +/// `ClearUnorderedAccessView*` checks this before calling PC clear with a non-null resource. +static UNALIGNED_DELTA_UAVS: std::sync::RwLock>> = std::sync::RwLock::new(None); +static UNALIGNED_DELTA_UAV_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub(super) fn is_unaligned_delta_uav(pc_uav: usize) -> bool { + if UNALIGNED_DELTA_UAV_COUNT.load(Ordering::Relaxed) == 0 || pc_uav == 0 { + return false; + } + UNALIGNED_DELTA_UAVS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pc_uav)) +} + +fn note_unaligned_delta_uav(pc_uav: usize, unaligned: bool) { + if pc_uav == 0 { + return; + } + if unaligned { + let mut g = UNALIGNED_DELTA_UAVS.write().unwrap(); + if g.get_or_insert_with(HashSet::new).insert(pc_uav) { + UNALIGNED_DELTA_UAV_COUNT.fetch_add(1, Ordering::Relaxed); + } + } else if UNALIGNED_DELTA_UAV_COUNT.load(Ordering::Relaxed) != 0 { + if let Some(s) = UNALIGNED_DELTA_UAVS.write().unwrap().as_mut() { + if s.remove(&pc_uav) { + UNALIGNED_DELTA_UAV_COUNT.fetch_sub(1, Ordering::Relaxed); + } + } + } +} + +/// Element byte size for standard DXGI typed buffer formats (`None` for unknown/block-compressed). +fn dxgi_buffer_format_bytes(fmt: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> Option { + use windows::Win32::Graphics::Dxgi::Common::*; + match fmt { + DXGI_FORMAT_R32G32B32A32_TYPELESS + | DXGI_FORMAT_R32G32B32A32_FLOAT + | DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32A32_SINT => Some(16), + DXGI_FORMAT_R32G32B32_TYPELESS + | DXGI_FORMAT_R32G32B32_FLOAT + | DXGI_FORMAT_R32G32B32_UINT + | DXGI_FORMAT_R32G32B32_SINT => Some(12), + DXGI_FORMAT_R16G16B16A16_TYPELESS + | DXGI_FORMAT_R16G16B16A16_FLOAT + | DXGI_FORMAT_R16G16B16A16_UNORM + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R16G16B16A16_SNORM + | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R32G32_TYPELESS + | DXGI_FORMAT_R32G32_FLOAT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT => Some(8), + DXGI_FORMAT_R10G10B10A2_TYPELESS + | DXGI_FORMAT_R10G10B10A2_UNORM + | DXGI_FORMAT_R10G10B10A2_UINT + | DXGI_FORMAT_R11G11B10_FLOAT + | DXGI_FORMAT_R8G8B8A8_TYPELESS + | DXGI_FORMAT_R8G8B8A8_UNORM + | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB + | DXGI_FORMAT_R8G8B8A8_UINT + | DXGI_FORMAT_R8G8B8A8_SNORM + | DXGI_FORMAT_R8G8B8A8_SINT + | DXGI_FORMAT_B8G8R8A8_TYPELESS + | DXGI_FORMAT_B8G8R8A8_UNORM + | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB + | DXGI_FORMAT_B8G8R8X8_TYPELESS + | DXGI_FORMAT_B8G8R8X8_UNORM + | DXGI_FORMAT_B8G8R8X8_UNORM_SRGB + | DXGI_FORMAT_R16G16_TYPELESS + | DXGI_FORMAT_R16G16_FLOAT + | DXGI_FORMAT_R16G16_UNORM + | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R16G16_SNORM + | DXGI_FORMAT_R16G16_SINT + | DXGI_FORMAT_R32_TYPELESS + | DXGI_FORMAT_R32_FLOAT + | DXGI_FORMAT_R32_UINT + | DXGI_FORMAT_R32_SINT => Some(4), + DXGI_FORMAT_R8G8_TYPELESS + | DXGI_FORMAT_R8G8_UNORM + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R8G8_SNORM + | DXGI_FORMAT_R8G8_SINT + | DXGI_FORMAT_R16_TYPELESS + | DXGI_FORMAT_R16_FLOAT + | DXGI_FORMAT_R16_UNORM + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R16_SNORM + | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_B5G6R5_UNORM + | DXGI_FORMAT_B5G5R5A1_UNORM + | DXGI_FORMAT_B4G4R4A4_UNORM => Some(2), + DXGI_FORMAT_R8_TYPELESS + | DXGI_FORMAT_R8_UNORM + | DXGI_FORMAT_R8_UINT + | DXGI_FORMAT_R8_SNORM + | DXGI_FORMAT_R8_SINT + | DXGI_FORMAT_A8_UNORM => Some(1), + _ => None, + } +} + +fn buffer_uav_element_bytes(desc: &D3D12_UNORDERED_ACCESS_VIEW_DESC) -> Option { + if desc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER { + return None; + } + let b = unsafe { desc.Anonymous.Buffer }; + if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + Some(4) + } else if b.StructureByteStride != 0 { + Some(b.StructureByteStride as u64) + } else { + dxgi_buffer_format_bytes(desc.Format) + } +} + +/// Adjust a PC buffer UAV description by `res_delta` (and `ctr_delta` when `has_counter`). +fn patch_buffer_uav_delta( + desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, + is_buffer_res: bool, + res_delta: u64, + has_counter: bool, + ctr_delta: u64, +) -> Result, ()> { + if res_delta == 0 && (!has_counter || ctr_delta == 0) { + return Ok(None); + } + let is_buf_view = desc.is_some_and(|d| d.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) || is_buffer_res; + if !is_buf_view { + return Ok(None); + } + let Some(d) = desc else { + return Err(()); + }; + if d.ViewDimension != D3D12_UAV_DIMENSION_BUFFER { + return Err(()); + } + let elem = buffer_uav_element_bytes(d).filter(|&e| e > 0).ok_or(())?; + if res_delta % elem != 0 { + return Err(()); + } + let mut patched = *d; + unsafe { + let b = &mut patched.Anonymous.Buffer; + if has_counter && ctr_delta != 0 { + let new_ctr = b.CounterOffsetInBytes.checked_add(ctr_delta).ok_or(())?; + if new_ctr % 4096 != 0 { + return Err(()); + } + b.CounterOffsetInBytes = new_ctr; + } + b.FirstElement = b.FirstElement.checked_add(res_delta / elem).ok_or(())?; + } + Ok(Some(patched)) +} + +#[cfg(test)] +mod uav_buffer_delta_tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + fn buf_uav(fmt: DXGI_FORMAT, first: u64, num: u32, stride: u32, ctr_off: u64, raw: bool) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: fmt, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: first, + NumElements: num, + StructureByteStride: stride, + CounterOffsetInBytes: ctr_off, + Flags: if raw { D3D12_BUFFER_UAV_FLAG_RAW } else { D3D12_BUFFER_UAV_FLAG_NONE }, + }, + }, + } + } + + #[test] + fn patch_buffer_uav_delta_shifts_raw_structured_and_typed_views() { + let raw = buf_uav(DXGI_FORMAT_R32_TYPELESS, 10, 64, 0, 0, true); + assert!(patch_buffer_uav_delta(Some(&raw), true, 0, false, 0).unwrap().is_none()); + let p = patch_buffer_uav_delta(Some(&raw), true, 0x200, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 10 + 128); + + let structured = buf_uav(DXGI_FORMAT_UNKNOWN, 5, 100, 24, 0, false); + let p = patch_buffer_uav_delta(Some(&structured), true, 0x300, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 5 + 32); + assert!(patch_buffer_uav_delta(Some(&structured), true, 0x100, false, 0).is_err()); + + for (fmt, elem) in [ + (DXGI_FORMAT_R8_UINT, 1u64), + (DXGI_FORMAT_R16_UNORM, 2), + (DXGI_FORMAT_R32_UINT, 4), + (DXGI_FORMAT_R11G11B10_FLOAT, 4), + (DXGI_FORMAT_R10G10B10A2_UNORM, 4), + (DXGI_FORMAT_R32G32_FLOAT, 8), + (DXGI_FORMAT_R32G32B32A32_FLOAT, 16), + ] { + let typed = buf_uav(fmt, 3, 16, 0, 0, false); + let p = patch_buffer_uav_delta(Some(&typed), true, elem * 7, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 10); + if elem > 1 { + assert!(patch_buffer_uav_delta(Some(&typed), true, elem - 1, false, 0).is_err()); + } + } + + let with_ctr = buf_uav(DXGI_FORMAT_UNKNOWN, 0, 16, 16, 4096, false); + let p = patch_buffer_uav_delta(Some(&with_ctr), true, 64, true, 8192).unwrap().unwrap(); + assert_eq!(unsafe { (p.Anonymous.Buffer.FirstElement, p.Anonymous.Buffer.CounterOffsetInBytes) }, (4, 12288)); + assert!(patch_buffer_uav_delta(Some(&with_ctr), true, 64, true, 128).is_err()); + + assert!(patch_buffer_uav_delta(None, true, 0x100, false, 0).is_err()); + let unknown = buf_uav(DXGI_FORMAT_UNKNOWN, 0, 16, 0, 0, false); + assert!(patch_buffer_uav_delta(Some(&unknown), true, 0x100, false, 0).is_err()); + } + + #[test] + fn unaligned_delta_uav_tracking_sets_and_clears() { + let handle = 0xDEAD_BEEF_1234usize; + assert!(!is_unaligned_delta_uav(handle)); + note_unaligned_delta_uav(handle, true); + assert!(is_unaligned_delta_uav(handle)); + note_unaligned_delta_uav(handle, false); + assert!(!is_unaligned_delta_uav(handle)); + } +} + unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { let rd_opt = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); // a UAV of the stencil plane of a depth buffer with unordered access: a view of its twin @@ -3083,8 +3396,30 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, // refuses the pair, `device_x::pc_resource_desc`): a null view – a UAV of it is an invalid // call, and the device is removed (0x887A0001) let no_uav = rd_opt.is_some_and(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0); + // Placed buffers with `buffer_delta != 0` start below the title's VA (`va & !0xFFFF`). Shift + // the PC UAV's `FirstElement` (and `CounterOffsetInBytes`) by the delta so PC UAV clears and + // pipelines hit the title's true buffer instead of `[va & !0xFFFF, va)` in live CPU RAM; if + // the delta is unaligned, bind a null PC UAV and skip PC clears on it. + let res_delta = buffer_delta(res as usize); + let ctr_delta = if counter.is_null() { 0 } else { buffer_delta(counter as usize) }; + let is_buf_res = rd_opt.is_some_and(|d| d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER); + let (pc_uav_desc_patched, unaligned_delta) = if !no_uav { + match patch_buffer_uav_delta(desc.as_ref(), is_buf_res, res_delta, !counter.is_null(), ctr_delta) { + Ok(patched) => (patched, false), + Err(()) => (None, true), + } + } else { + (None, false) + }; + let pc_uav_desc = pc_uav_desc_patched.as_ref().map_or(desc, |d| d as *const _); let null_desc = null_uav_desc(desc.as_ref(), rd_opt.as_ref()); + let null_buf_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + }; let pc_uav = |at: u64| { + note_unaligned_delta_uav(at as usize, unaligned_delta); if no_uav { static N: AtomicU64 = AtomicU64::new(0); if let Some(why) = null_why { @@ -3093,16 +3428,26 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (a depth buffer) – a null view"); } f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_desc, at) + } else if unaligned_delta { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!( + "D3D12.X: buffer UAV on placed resource {res:p} has unaligned delta (res_delta={res_delta:#x}, ctr_delta={ctr_delta:#x}) – binding null PC UAV" + ); + } + f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_buf_desc, at) } else { - f(this, res, counter, desc, at) + f(this, res, counter, pc_uav_desc, at) } }; let Some(slot) = super::console_heap::slot(cpu) else { return pc_uav(cpu) }; pc_uav(slot.pc_uav); super::lut3d::slot_reused(slot.index, cpu, res as usize, || format!("an unordered access view of {res:p} (its companion view)")); - super::console_heap::publish(&slot, true, if no_uav { 0 } else { res as usize }); + super::console_heap::publish(&slot, true, if no_uav || unaligned_delta { 0 } else { res as usize }); super::console_heap::note_resource(&slot, res as usize); + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, true); // A null image UAV was already created and published at `slot.index + 1`. Create a // matching null companion SRV at `slot.index` and write a valid T# referencing // `slot.index` so shaders never fall back to `ResourceDescriptorHeap[0]` / `[1]`. @@ -3121,6 +3466,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, }; let rd = rd_opt.unwrap(); if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, true); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); @@ -3141,6 +3487,8 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } None => (rd.Format, resource_dim_to_view(&rd), rd.DepthOrArraySize as u32, 0), }; + let amb_fmt = if format.0 != 0 { format.0 } else { rd.Format.0 }; + super::ambient::note_descriptor(slot.at, amb_idx, res as usize, amb_fmt, rd.Format.0, true); super::lut3d::wrote(res as usize, false, || { let first = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE3D).map_or(0, |v| v.Anonymous.Texture3D.FirstWSlice); format!("an unordered access view made in console slot {cpu:#x} (T# index {}, the UAV at + 1): format {}, mip {mip}, depth slices {first} (+{})", slot.index, format.0, array as i32) @@ -4525,18 +4873,37 @@ struct Slots { wanted_most: usize, /// compiles that are not built ahead of their first use waiting for a slot (`big_compile_turn`) urgent: AtomicUsize, + /// compiles a live title thread is currently blocked waiting on (`big_compile_turn`): while + /// non-zero, non-wanted builds (ahead or late) do not take a freed slot ahead of them + wanted_waiters: AtomicUsize, /// a build ahead of its pipeline's first use may take a slot (`big_compile_turn`) ahead: bool, } impl Slots { const fn new(most: usize, wanted_most: usize) -> Slots { - Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), ahead: true } + Slots { + n: Mutex::new(0), + cv: std::sync::Condvar::new(), + most, + wanted_most, + urgent: AtomicUsize::new(0), + wanted_waiters: AtomicUsize::new(0), + ahead: true, + } } /// `new` for a lane whose slots no build ahead of its pipeline's first use takes. const fn closed_to_ahead(most: usize, wanted_most: usize) -> Slots { - Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most, wanted_most, urgent: AtomicUsize::new(0), ahead: false } + Slots { + n: Mutex::new(0), + cv: std::sync::Condvar::new(), + most, + wanted_most, + urgent: AtomicUsize::new(0), + wanted_waiters: AtomicUsize::new(0), + ahead: false, + } } fn most(&self) -> usize { @@ -4665,14 +5032,21 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool, ahead: impl Fn() -> bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); let mut n = slots.n.lock().unwrap(); - // (counted in `urgent` while it waits) + // (counted in `urgent` / `wanted_waiters` while it waits) let mut queued = false; + let mut queued_wanted = false; let guard = loop { let is_wanted = wanted(); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; let ahead = !is_wanted && ahead(); let open = slots.ahead || !ahead; - if open && *n < cap && (is_wanted || commit_free()) && !(ahead && slots.urgent.load(Ordering::Acquire) > 0) { + let yielded_to_wanted = !is_wanted && slots.wanted_waiters.load(Ordering::Acquire) > 0; + if open + && *n < cap + && (is_wanted || commit_free()) + && !yielded_to_wanted + && !(ahead && slots.urgent.load(Ordering::Acquire) > 0) + { *n += 1; break SlotGuard(slots); } @@ -4680,11 +5054,21 @@ fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wante queued = true; slots.urgent.fetch_add(1, Ordering::AcqRel); } + if is_wanted && !queued_wanted { + queued_wanted = true; + slots.wanted_waiters.fetch_add(1, Ordering::AcqRel); + } else if !is_wanted && queued_wanted { + queued_wanted = false; + slots.wanted_waiters.fetch_sub(1, Ordering::AcqRel); + } n = slots.cv.wait_timeout(n, LOOK).unwrap().0; }; if queued { slots.urgent.fetch_sub(1, Ordering::AcqRel); } + if queued_wanted { + slots.wanted_waiters.fetch_sub(1, Ordering::AcqRel); + } guard } @@ -5045,6 +5429,7 @@ 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))]); + super::ambient::note_compute_pso(*ppv as usize, cs); if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { PSO_USER_SGPRS.insert(*ppv as usize, (i.user_sgprs, i.threads)); } @@ -5086,6 +5471,7 @@ 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))]); + super::ambient::note_compute_pso(*ppv as usize, cs); if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { PSO_USER_SGPRS.insert(*ppv as usize, (i.user_sgprs, i.threads)); } @@ -6409,6 +6795,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); TRANSLATED_GRAPHICS.insert(*ppv as usize, ()); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); if (super::gpu_profile::on() || super::gpu_times::enabled()) && !super::present::trace_frame() { @@ -6972,11 +7359,28 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const hr } +/// Whether `desc`'s console compute program is one `XCL_RT_LEAVE_OUT` leaves out. +unsafe fn rt_left_out(desc: *const c_void) -> bool { + if !crate::gpu::rt_leave_out::enabled() || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return false; + } + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + shader_bytes(&d.CS).is_some_and(|cs| crate::gpu::recomp::pso::is_console(cs) && crate::gpu::rt_leave_out::left_out(cs)) +} + unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let _cost = crate::hle::api_cost::time(crate::hle::api_cost::Call::Pipeline); super::null::capture_compute_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); - let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; + // `XCL_RT_LEAVE_OUT`: not translated or built; the dummy program below, its dispatches skipped + let left_out = rt_left_out(desc); + let (mut console, missed) = if left_out { + (Some(Err(())), false) + } else if super::pso_async::enabled() { + attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) + } else { + (translated_compute_pso(this, f, desc, riid, ppv), false) + }; if missed { if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, compute_key, build_compute)) { // a console program the worker is translating (its root signature comes with it); @@ -7006,7 +7410,9 @@ unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, copy.CS = bytecode(&dummy().cs); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let hr2 = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); - note_fallback("compute PSO", hr, hr2 >= 0); + if !left_out || hr2 < 0 { + note_fallback("compute PSO", hr, hr2 >= 0); + } if console.is_some() { note_console_compute(hr2, ppv); } @@ -7084,7 +7490,7 @@ pub(super) fn register_two_pass_for_test(pso: usize, kind: &'static str) { compute: 0, compute_rs: 0, mesh_rs: 0, - record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 64, max_vertices: 64, max_primitives: 64 }, + record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 64, max_vertices: 64, max_primitives: 64, params: None }, mesh_groups_per_record: 1, kind, }), @@ -7771,6 +8177,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri } let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, "MS", riid, ppv); if hr >= 0 { + super::ambient::note_graphics_pso(*ppv as usize, console_ps); super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); if super::gpu_times::enabled() { PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(ms), console_ps.map_or(0, crate::gpu::shader::fnv64))); @@ -7849,6 +8256,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE } let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, "GS", riid, ppv); if hr >= 0 { + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); if super::gpu_times::enabled() { PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(gs), shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64))); @@ -8257,6 +8665,86 @@ mod pso_blend_and_tsharp_tests { let img_arr = crate::gpu::desc::image(&srv_tsharp_from_desc(11, &msaa_arr, Some(&msaa_arr_srv)).unwrap()).unwrap(); assert_eq!((img_arr.ty, img_arr.depth, img_arr.base_level, img_arr.last_level), (crate::gpu::desc::ImageType::D2MsaaArray, 4, 0, 2)); } + + /// A stencil view is a UINT view: its T# has a uint format, so translated shaders load it as + /// integers (`img_cls`: the buffer-format table's numeric type 4); the depth view stays float. + #[test] + fn srv_tsharp_of_a_stencil_view_has_a_uint_format() { + let class = |fmt: u32| (crate::gpu::recomp::emit::buf_format_info(fmt as usize) >> 3) & 7; + for (resource, stencil, depth) in [ + (DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS), + (DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS), + ] { + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 2560, + Height: 1440, + DepthOrArraySize: 1, + MipLevels: 1, + Format: resource, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let view = |format, plane| D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: plane, ResourceMinLODClamp: 0.0 }, + }, + }; + let s = crate::gpu::desc::image(&srv_tsharp_from_desc(5, &rd, Some(&view(stencil, 1))).unwrap()).unwrap(); + assert_eq!((s.format, class(s.format)), (5, 4), "stencil view {stencil:?}: T# format 8_UINT, uint class"); + assert_eq!((s.width, s.height), (2560, 1440)); + let d = crate::gpu::desc::image(&srv_tsharp_from_desc(6, &rd, Some(&view(depth, 0))).unwrap()).unwrap(); + assert_ne!(class(d.format), 4, "depth view {depth:?} stays a float image"); + } + } + + /// A translated `image_load` of a stencil view (the T# `srv_tsharp_from_desc` writes for it) + /// gives the stencil values: in the second component, as the PC view has them. + #[test] + fn gpu_image_load_of_a_stencil_view_gives_the_stencil() { + use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; + use crate::gpu::rdna2::encode; + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R24G8_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_X24_TYPELESS_G8_UINT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 1, ResourceMinLODClamp: 0.0 } }, + }; + // the runner's SRV of texture 0 is at heap index 0 + let t = srv_tsharp_from_desc(0, &rd, Some(&view)).unwrap(); + let mut code = encode("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x2), ("DIM", 1), ("UNORM", 1)], None).unwrap(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&t); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = (l % 8) as u32; + r[1] = (l / 8) as u32; + } + let stencil: Vec = (0..64).map(|k| 0x40 + k as u8).collect(); + let tex = [TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_X24_TYPELESS_G8_UINT, width: 8, height: 8, depth: 1, texel_bytes: 1, data: stencil, uav: false }]; + let r = runner::run_code_with(&code, &st, &[], &tex, &[]).unwrap(); + let bad: Vec = (0..64).filter(|&l| r.vgpr[l][10] != 0x40 + l as u32).map(|l| format!("lane {l}: {:#x}", r.vgpr[l][10])).collect(); + assert!(bad.is_empty(), "image_load of a stencil view (want 0x40 + lane):\n{}", bad.join("\n")); + } } enum StreamPipeline { @@ -8731,17 +9219,57 @@ unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { let n = f(this); if n == 0 { super::list_x::on_queue_release(this as usize); + super::title_textures::on_queue_release(this as usize); } n } unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + if add_ref(this) == 2 { + let a = this as usize; + let deferred = super::alloc_pool::release_when_done( + a, + Box::new(move || { + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(a as *mut c_void); + super::list_x::on_allocator_release(a); + // Drop the final PC ID3D12CommandAllocator reference only after all GPU + // fences on its backing complete so the D3D12 command pool is never freed + // while still in flight on the GPU. + rel(a as *mut c_void); + }), + ); + if deferred { + // Drop our temporary probe ref, keeping 1 ref alive for the deferred cleanup above, + // and report 0 to the title since its ownership of the allocator has ended. + rel(this); + return 0; + } + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(this); + super::list_x::on_allocator_release(a); + rel(this); + return rel(this); + } + rel(this); + let n = rel(this); if n == 0 { - dispatch_chain::allocator_reset(this as usize); - super::alloc_pool::forget(this as usize); - super::list_x::on_allocator_release(this as usize); + let a = this as usize; + // Rare race: two threads reached final release concurrently; object is already freed. + if !super::alloc_pool::release_when_done( + a, + Box::new(move || { + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(a as *mut c_void); + super::list_x::on_allocator_release(a); + }), + ) { + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(this); + super::list_x::on_allocator_release(a); + } } n } @@ -9129,6 +9657,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); return; } + super::gpu_awake::note_activity(); super::capture::submit(this, std::slice::from_raw_parts(lists, n as usize)); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's // own work in the submission. Where that takes long, it is not the title's time @@ -9159,6 +9688,15 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis mapped.push(l); } } + // Flush and wait for any tile mappings / recycled-tile zero-fills queued concurrently while + // `record_deferred` built/waited on PSOs so the title's submit never races `UpdateTileMappings`. + // Skip for XCL's own internal submits (`own_work`) which may already hold `PAGES` or `STATE`. + if !super::title_textures::is_own_work() { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&this) { + super::sparse::wait_pending_mappings(q); + super::vram::wait_pending_mappings(q); + } + } super::list_x::note_queue_for_lists(this as usize, &mapped); super::gpu_profile::note_queue(this); let t_exec = std::time::Instant::now(); @@ -9461,7 +9999,7 @@ pub fn log_device_removed() { v.join(", ") }; let va = pf.PageFaultVA; - let window = uma_window_vas().iter().position(|&w| va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); + let window = uma_window_vas().iter().position(|&w| w != 0 && va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); } let breadcrumbs = dred.GetAutoBreadcrumbsOutput(); @@ -10839,7 +11377,7 @@ mod mesh_stream_tests { let make_tp = || crate::gpu::recomp::pso::TwoPass { cs: vec![0; 16], ms: vec![0; 16], - record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1 }, + record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1, params: None }, mesh_groups_per_record: 1, samplers: vec![sampler], }; diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b52ee4ce25..fbbe766bfd 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -32,8 +32,9 @@ use windows_sys::Win32::System::Memory::{ }; const TILE: usize = 0x1_0000; -/// tiles of a video-memory pool heap (64 MiB) -const POOL_TILES: u32 = 1024; +/// tiles of a video-memory pool heap (4 MiB). Smaller pools let more video memory return when a +/// title frees runs of tiles spread across heaps while keeping tiles between them (#2630). +const POOL_TILES: u32 = 64; /// tiles decommitted while no title work was submitted that stay mapped (`State::parked`) before /// they are unmapped together: 256 MB of video memory const PARKED_MAX: usize = 4096; @@ -513,9 +514,9 @@ struct State { /// filled for another address on the sparse queue while title work submitted before the /// unmap could still read it. cooling: VecDeque<((u32, u32), std::time::Instant)>, - /// pools all of whose tiles came free: released once the GPU is past `value` and a moment - /// went by (titles' queues may still read what was mapped there) - retired: Vec<(ID3D12Heap, u64, std::time::Instant)>, + /// pools all of whose tiles came free: released once the GPU is past `(value, rbq_value)` and + /// a moment went by (titles' queues and `rbq` may still read what was mapped there) + retired: Vec<(ID3D12Heap, u64, u64, std::time::Instant)>, /// when `retire_free_pools` last ran (`retire_due`) retire_tried: std::time::Instant, /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes @@ -569,6 +570,10 @@ struct State { rb_last_fence: u64, /// the fence value each title queue last waited for waited: FxHashMap, + /// tile mappings were queued since the last `signal` (`map_tiles` / `unmap_tiles`) + mapping_queued: std::sync::atomic::AtomicBool, + /// the fence value of the last `signal` that came after tile mappings + mapped_value: u64, /// `mapped` as runs of neighbouring tiles (start -> end), kept with it: sorted out of all of /// them again (a retail title has 150,000) for each look behind a commit runs: BTreeMap, @@ -1093,6 +1098,8 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -1236,7 +1243,7 @@ impl State { // 64 MB heap is made: freeing and allocating a tile in turn made a new pool each time, // up to 18 GB of retired heaps in 2 s (#913). Its tiles are reused as freed tiles are // (zeroed), and they all cooled before it was retired. - if let Some((heap, _, _)) = self.retired.pop() { + if let Some((heap, _, _, _)) = self.retired.pop() { let h = self.add_pool(heap); return Some(((h, 0), true)); } @@ -1284,16 +1291,29 @@ impl State { let now = std::time::Instant::now(); self.retire_tried = now; let done = unsafe { super::real::fence_completed(&self.fence) }; - self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); - let gone: Vec = free_heaps(&self.free, &self.cooling, self.pools.len(), now).into_iter().filter(|&h| self.pools[h].is_some()).collect(); - if gone.is_empty() { + let rb_done = self.rbq.as_ref().map_or(u64::MAX, |(_, f)| unsafe { super::real::fence_completed(f) }); + self.retired.retain(|(_, v, rb_v, at)| !(done >= *v && rb_done >= *rb_v && now.duration_since(*at).as_secs() >= 2)); + let gone_list = free_heaps(&self.free, &self.cooling, self.pools.len(), now); + if gone_list.is_empty() { return; } - self.free.retain(|&(h, _)| !gone.contains(&(h as usize))); - self.cooling.retain(|&((h, _), _)| !gone.contains(&(h as usize))); - for h in gone { + let mut gone = vec![false; self.pools.len()]; + let mut any = false; + for h in gone_list { + if self.pools[h].is_some() { + gone[h] = true; + any = true; + } + } + if !any { + return; + } + self.free.retain(|&(h, _)| !gone[h as usize]); + self.cooling.retain(|&((h, _), _)| !gone[h as usize]); + for h in (0..gone.len()).filter(|&h| gone[h]) { if let Some(heap) = self.pools[h].take() { - self.retired.push((heap, self.value, now)); + let rb_v = if self.rbq.is_some() { self.rbq_value } else { 0 }; + self.retired.push((heap, self.value, rb_v, now)); } } } @@ -1304,6 +1324,7 @@ impl State { if tiles.is_empty() { return; } + self.mapping_queued.store(true, Ordering::Relaxed); let mut by_heap: FxHashMap> = FxHashMap::default(); debug_assert!(tiles.iter().all(|t| t.1 != LAZY), "a tile with no video memory is mapped nowhere"); for &(a, (h, t)) in tiles { @@ -1355,6 +1376,7 @@ impl State { if tiles.is_empty() { return; } + self.mapping_queued.store(true, Ordering::Relaxed); let mut xs: Vec = tiles.iter().map(|&a| ((a - res_base) / TILE) as u32).collect(); xs.sort_unstable(); let mut coords: Vec = Vec::with_capacity(xs.len()); @@ -1626,6 +1648,9 @@ impl State { unsafe fn signal(&mut self) { self.value += 1; let _ = self.queue.Signal(&self.fence, self.value); + if self.mapping_queued.swap(false, Ordering::Relaxed) { + self.mapped_value = self.value; + } } #[inline] @@ -3022,8 +3047,13 @@ impl State { return; } let mut ok = self.sync_known_queues(); - let mut marks = Vec::with_capacity(1 + self.queue_fences.len()); + let mut marks = Vec::with_capacity(2 + self.queue_fences.len()); marks.push((self.fence.clone(), self.value)); + if let Some((_, ref rbq_fence)) = self.rbq { + if self.rbq_value > 0 { + marks.push((rbq_fence.clone(), self.rbq_value)); + } + } if ok { for (q, fence, val) in self.queue_fences.values_mut() { let next = *val + 1; @@ -4161,7 +4191,94 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: LOCK_SPLIT.add(LS_ALL, waited); HELD.add(HOLDERS + behind, (t_got - t0).as_micros() as u64); } - s.before_execute_on(queue, dirty, page); + let wait = s.before_execute_on(queue, dirty, page); + drop(_held); + drop(g); + if let Some((fence, value, mappings)) = wait { + let q = queue.as_raw() as usize; + if !(mappings && cpu_waited_for_mappings(&fence, value, "sparse uploads and tile mappings")) { + let _ = queue.Wait(&fence, value); + super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); + } + } +} + +/// Fast-path wait for any sparse-window tile mappings or uploads queued after +/// `title_textures::refresh` (for example while `record_deferred` waited on PSO builds). +pub(super) unsafe fn wait_pending_mappings(queue: &ID3D12CommandQueue) { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return }; + if s.mapping_queued.load(Ordering::Relaxed) { + s.signal(); + } + let q = queue.as_raw() as usize; + if s.queue.as_raw() as usize == q { + return; + } + let waited_before = s.waited.get(&q).copied().unwrap_or(0); + if s.value > 0 && waited_before < s.value { + let (fence, value) = (s.fence.clone(), s.value); + let mappings = s.mapped_value > waited_before; + s.waited.insert(q, value); + drop(g); + if !(mappings && cpu_waited_for_mappings(&fence, value, "sparse uploads and tile mappings")) { + let _ = queue.Wait(&fence, value); + super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); + } + } +} + +/// `XCL_SPARSE_CPU_WAIT_MS` (1 000 by default, 0: off): how long a title submit waits on the +/// CPU for a mapping queue's tile mappings (the sparse windows', the video memory pages') before +/// its lists go, instead of the title's queue waiting for them on the GPU. +/// +/// With the GPU wait every queue of a retail title held its queued work behind the sparse +/// queue's tile mappings. On an AMD RX 9070 (16 GB, at its memory budget) the sparse queue's +/// fence then stopped short of the value they waited for, for 15 s – while AMD's crash analysis +/// found no command buffer in flight – and the device was removed (five runs in a row, 63–140 s +/// into the world). A tile mapping is the video memory manager's work: it can have to evict, and +/// it cannot take memory from queues whose work is already queued behind that very mapping. With +/// the wait on the CPU no queue holds work behind a mapping; past the limit the GPU wait is used +/// as before (logged). +fn sparse_cpu_wait() -> std::time::Duration { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + std::time::Duration::from_millis(*MS.get_or_init(|| { + std::env::var("XCL_SPARSE_CPU_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1000) + })) +} + +/// Whether `fence` (of the mapping queue `what`) reached `value` within `sparse_cpu_wait`. +pub(super) unsafe fn cpu_waited_for_mappings(fence: &ID3D12Fence, value: u64, what: &str) -> bool { + let most = sparse_cpu_wait(); + if most.is_zero() { + return false; + } + if super::real::fence_completed(fence) >= value { + return true; + } + thread_local! { + static EVENT: HANDLE = unsafe { windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap_or_default() }; + } + let t = std::time::Instant::now(); + let reached = EVENT.with(|&ev| { + if ev.is_invalid() || fence.SetEventOnCompletion(value, ev).is_err() { + return false; + } + windows::Win32::System::Threading::WaitForSingleObject(ev, most.as_millis() as u32); + super::real::fence_completed(fence) >= value + }); + let waited = t.elapsed(); + static SLOW: AtomicU64 = AtomicU64::new(0); + if !reached { + crate::xlog_warn!( + "D3D12.X: {what} did not reach {value} in {} ms (at {}): the title's queue waits for it on the GPU", + waited.as_millis(), + super::real::fence_completed(fence) + ); + } else if waited >= std::time::Duration::from_millis(200) && SLOW.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: {what} waited {} ms on the CPU for fence {value}", waited.as_millis()); + } + reached } /// What the title's lists being recorded will write on the GPU in the sparse windows (address, @@ -4311,8 +4428,9 @@ fn lock_split_line(x: &[u64; 11]) -> String { } impl State { - /// `before_execute` with the state locked - unsafe fn before_execute_on(&mut self, queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { + /// `before_execute` with the state locked; returns `(fence, value, has_new_mappings)` to wait + /// for after releasing the lock. + unsafe fn before_execute_on(&mut self, queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) -> Option<(ID3D12Fence, u64, bool)> { let t0 = std::time::Instant::now(); let s = self; // (`XCL_LOOK_STATS=2`: the time after each step, and the work counted so far) @@ -4525,11 +4643,18 @@ impl State { } dirty_runs.clear(); s.scratch_runs = dirty_runs; + // the tile mappings of buffers placed since the last signal (`place_buffer`) + if s.mapping_queued.load(Ordering::Relaxed) { + s.signal(); + } let q = queue.as_raw() as usize; - if s.value > 0 && s.waited.get(&q).copied().unwrap_or(0) < s.value { - let _ = queue.Wait(&s.fence, s.value); - super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &s.fence, s.value); + let waited_before = s.waited.get(&q).copied().unwrap_or(0); + if s.value > 0 && waited_before < s.value { + let mappings = s.mapped_value > waited_before; s.waited.insert(q, s.value); + Some((s.fence.clone(), s.value, mappings)) + } else { + None } } } @@ -5013,6 +5138,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -5344,6 +5471,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -5581,6 +5710,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -5707,6 +5838,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: std::sync::atomic::AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 7c2d65f88c..665264cb8d 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2105,6 +2105,15 @@ unsafe fn reclaim(q: &mut QueueUploads, cap: u64, wait_ms: u64) { } } +/// Drop tracked upload state for a released command queue so its fence and staging buffers do not +/// leak and a later queue at the same address cannot reuse a stale fence. +pub(super) fn on_queue_release(queue_key: usize) { + if queue_key == 0 { + return; + } + ON_QUEUE.lock().unwrap().remove(&queue_key); +} + /// The queue a submit's uploads go to, by device, and the one it waits for first. struct Target { /// the title's queue, when they go to it diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 065467f1ee..60c8ff49e0 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -133,7 +133,9 @@ pub(super) fn is_placed_texture(resource: usize) -> bool { pub(super) fn forget(resource: usize) { let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); if placed { - forget_pages(resource); + if !super::vram_small::forget(resource) { + forget_pages(resource); + } if let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { ARENAS.lock().unwrap().release(id, std::time::Instant::now()); } @@ -230,10 +232,14 @@ struct Target { console_bytes: Option, total: u32, mapped: bool, + /// incremented on every `unmap_placed` / `remap_if_unmapped` to cancel stale deferred unmaps + mapping_gen: u64, used: Vec, used_extra: Vec<(usize, usize)>, /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: Option, + /// placed as GPU-owned: its pages are keyed by the physical page under them (`page_key`) + gpu_owned: bool, } /// The tiles of a texture whose levels get video memory when an upload first has texels for @@ -349,6 +355,10 @@ struct TilePool { free_by_heap: Vec>, /// Whether `free_by_heap[h]` must be sorted descending before popping. dirty_sort: Vec, + /// Per-heap bitmap of recycled tiles (`1` = previously allocated & returned, holds stale VRAM + /// contents that must be zeroed before handing to a new texture under `XCL_ZERO_TARGET_PAGES`). + /// Freshly created heaps start all `0` (already zeroed by D3D12). + dirty_bits: Vec<[u64; (POOL_PAGES as usize).div_ceil(64)]>, /// Total free tiles currently available across all heaps. free_total: usize, /// Tiles given back, reusable after `COOL`. @@ -363,22 +373,49 @@ impl TilePool { TilePool { free_by_heap: Vec::new(), dirty_sort: Vec::new(), + dirty_bits: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::new(), live: Vec::new(), } } + #[inline] + fn mark_dirty(&mut self, h: usize, t: u32) { + let word = (t as usize) >> 6; + if let Some(bits) = self.dirty_bits.get_mut(h) { + if let Some(w) = bits.get_mut(word) { + *w |= 1u64 << (t & 63); + } + } + } + + #[inline] + fn take_dirty(&mut self, h: usize, t: u32) -> bool { + let word = (t as usize) >> 6; + if let Some(bits) = self.dirty_bits.get_mut(h) { + if let Some(w) = bits.get_mut(word) { + let mask = 1u64 << (t & 63); + let was = (*w & mask) != 0; + *w &= !mask; + return was; + } + } + false + } + fn add_heap_at(&mut self, slot: u32, pool_pages: u32) { let idx = slot as usize; if idx >= self.free_by_heap.len() { self.free_by_heap.resize_with(idx + 1, Vec::new); self.dirty_sort.resize(idx + 1, false); + self.dirty_bits.resize(idx + 1, [0u64; (POOL_PAGES as usize).div_ceil(64)]); self.live.resize(idx + 1, false); } debug_assert!(self.free_by_heap[idx].is_empty()); self.free_by_heap[idx] = (0..pool_pages).rev().collect(); self.dirty_sort[idx] = false; + self.dirty_bits[idx] = [0u64; (POOL_PAGES as usize).div_ceil(64)]; self.live[idx] = true; self.free_total += pool_pages as usize; } @@ -404,6 +441,7 @@ impl TilePool { self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; + self.dirty_bits[h] = [0u64; (POOL_PAGES as usize).div_ceil(64)]; self.live[h] = false; self.free_total -= full; reclaimed.push(h as u32); @@ -415,31 +453,55 @@ impl TilePool { self.cooling.push_back((tile, now)); } - /// Move every cooled tile (`>= COOL`) into its pool heap's free list so best-fit allocation + /// Move every cooled tile (`>= COOL` and, when `safe_before` is set, queued no later than the + /// latest GPU-verified fence barrier) into its pool heap's free list so best-fit allocation /// sees all ready tiles at once. - fn drain_cooling(&mut self, now: std::time::Instant) { - while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + fn drain_cooling_before(&mut self, now: std::time::Instant, safe_before: Option) { + while self.cooling.front().is_some_and(|&(_, at)| { + now.duration_since(at) >= COOL && safe_before.is_none_or(|safe| at <= safe) + }) { let Some(((h, t), _)) = self.cooling.pop_front() else { break }; let idx = h as usize; if idx < self.free_by_heap.len() && self.live[idx] { self.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); self.free_total += 1; } } } + #[cfg(test)] + fn drain_cooling(&mut self, now: std::time::Instant) { + self.drain_cooling_before(now, None); + } + fn return_tiles(&mut self, tiles: &[Tile]) { for &(h, t) in tiles { let idx = h as usize; if idx < self.free_by_heap.len() && self.live[idx] { self.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); self.free_total += 1; } } } + fn return_rollback_tiles(&mut self, tiles: &[Tile], dirty: &[Tile]) { + for &(h, t) in tiles { + let idx = h as usize; + if idx < self.free_by_heap.len() && self.live[idx] { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.free_total += 1; + } + } + for &(h, t) in dirty { + self.mark_dirty(h as usize, t); + } + } + /// Pick the pool heap to take up to `rem` tiles from: /// 1. `preferred` if it fits all `rem` tiles (keeps partial-overlap placements on 1 heap), /// 2. otherwise best-fit heap with `len >= rem` (fits the whole texture in 1 heap without @@ -475,26 +537,43 @@ impl TilePool { /// Allocate `count` tiles, preferring a single heap and ascending contiguous offsets. /// `make_heap` allocates a new backing pool heap of `pool_pages` tiles when `free_total == 0`. /// On failure, any tiles already taken are returned untouched. + #[cfg(test)] fn take_batch( &mut self, count: usize, preferred: Option, now: std::time::Instant, pool_pages: u32, + make_heap: impl FnMut() -> Option, + ) -> Option> { + let mut ignored = Vec::new(); + self.take_batch_recycled(count, preferred, now, None, pool_pages, &mut ignored, make_heap) + } + + fn take_batch_recycled( + &mut self, + count: usize, + preferred: Option, + now: std::time::Instant, + safe_before: Option, + pool_pages: u32, + recycled_out: &mut Vec, mut make_heap: impl FnMut() -> Option, ) -> Option> { if count == 0 { return Some(Vec::new()); } - self.drain_cooling(now); + self.drain_cooling_before(now, safe_before); let mut out = Vec::with_capacity(count); + let recycled_start = recycled_out.len(); while out.len() < count { let rem = count - out.len(); let h = match self.pick_heap(rem, preferred) { Some(h) => h, None => { let Some(new_h) = make_heap() else { - self.return_tiles(&out); + let rolled_dirty = recycled_out.split_off(recycled_start); + self.return_rollback_tiles(&out, &rolled_dirty); return None; }; self.add_heap_at(new_h, pool_pages); @@ -505,10 +584,12 @@ impl TilePool { self.free_by_heap[h].sort_unstable_by(|a, b| b.cmp(a)); self.dirty_sort[h] = false; } - let free = &mut self.free_by_heap[h]; - let take = rem.min(free.len()); + let take = rem.min(self.free_by_heap[h].len()); for _ in 0..take { - let t = free.pop().unwrap(); + let t = self.free_by_heap[h].pop().unwrap(); + if self.take_dirty(h, t) { + recycled_out.push((h as u32, t)); + } out.push((h as u32, t)); } self.free_total -= take; @@ -517,6 +598,32 @@ impl TilePool { } } +/// Coalesce recycled `(heap, tile_idx)` pairs into sorted, deduplicated `(heap, start_tile, count)` +/// runs so GPU zero-fills issue one `CopyBufferRegion` per contiguous tile span. +fn coalesce_tile_runs(tiles: &mut Vec) -> Vec<(u32, u32, u32)> { + if tiles.is_empty() { + return Vec::new(); + } + tiles.sort_unstable(); + tiles.dedup(); + let mut runs: Vec<(u32, u32, u32)> = Vec::new(); + for &(h, t) in tiles.iter() { + match runs.last_mut() { + Some(last) if last.0 == h && last.1 + last.2 == t => last.2 += 1, + _ => runs.push((h, t, 1)), + } + } + runs +} + +/// Zero recycled page-pool tiles on the mapping queue before handing them to newly mapped +/// textures so stale render-target/depth/UAV bytes never bleed into new targets (`#505`/`#1833`). +/// Enabled by default (`XCL_ZERO_TARGET_PAGES=0` disables). +fn zero_target_pages() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").map_or(true, |v| v.trim() != "0")) +} + /// Allocate one 64 MiB default heap for `Pages`. unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { let desc = D3D12_HEAP_DESC { @@ -538,13 +645,16 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { /// are reclaimed back to local VRAM. `len()` reports the count of live heaps. struct PoolHeaps { slots: Vec>, + /// Aliased 64 MiB `BUFFER` placed at offset 0 of each pool heap for GPU zero-fills of recycled + /// tiles (0 bytes of extra VRAM; lazily created on first recycled tile in that heap). + zero_bufs: Vec>, free_slots: Vec, live: usize, } impl PoolHeaps { fn new() -> Self { - Self { slots: Vec::new(), free_slots: Vec::new(), live: 0 } + Self { slots: Vec::new(), zero_bufs: Vec::new(), free_slots: Vec::new(), live: 0 } } fn len(&self) -> usize { @@ -556,19 +666,53 @@ impl PoolHeaps { if let Some(idx) = self.free_slots.pop() { debug_assert!(self.slots[idx as usize].is_none()); self.slots[idx as usize] = Some(heap); + self.zero_bufs[idx as usize] = None; idx } else { let idx = self.slots.len() as u32; self.slots.push(Some(heap)); + self.zero_bufs.push(None); idx } } - fn take_heap(&mut self, idx: u32) -> Option { + fn take_heap(&mut self, idx: u32) -> Option<(ID3D12Heap, Option)> { + let zero_buf = self.zero_bufs.get_mut(idx as usize).and_then(|b| b.take()); let h = self.slots.get_mut(idx as usize)?.take()?; self.live -= 1; self.free_slots.push(idx); - Some(h) + Some((h, zero_buf)) + } + + unsafe fn zero_buffer(&mut self, dev: &ID3D12Device, idx: usize) -> Option { + if let Some(b) = self.zero_bufs.get(idx)?.as_ref() { + return Some(b.clone()); + } + let heap = self.slots.get(idx)?.as_ref()?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: POOL_PAGES as u64 * PAGE as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let mut res: Option = None; + let ok = super::title_textures::own_work(|| { + dev.CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res) + }) + .is_ok(); + if !ok { + return None; + } + let buf = res?; + let _ = buf.SetName(windows::core::w!("xcl vram zero_alias")); + self.zero_bufs[idx] = Some(buf.clone()); + Some(buf) } /// The live heap at `idx` (None: reclaimed or never made). @@ -577,6 +721,63 @@ impl PoolHeaps { } } +/// Reusable 4-slot command ring + 1 MiB pre-zeroed upload buffer for asynchronous GPU zero-fills +/// of recycled VRAM pool tiles on `Pages::queue`. +const ZERO_BUF_BYTES: u64 = 1 << 20; +const ZERO_SLOTS: usize = 4; + +struct ZeroSlot { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence_val: u64, + kept_bufs: Vec, +} + +struct ZeroRing { + zero_src: ID3D12Resource, + slots: Vec, +} + +impl ZeroRing { + unsafe fn new(dev: &ID3D12Device) -> Option { + let mut src: Option = None; + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: ZERO_BUF_BYTES, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + super::title_textures::own_work(|| { + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut src) + }) + .ok()?; + let zero_src = src?; + let mut mapped = std::ptr::null_mut(); + zero_src.Map(0, None, Some(&mut mapped)).ok()?; + std::ptr::write_bytes(mapped as *mut u8, 0, ZERO_BUF_BYTES as usize); + zero_src.Unmap(0, None); + let mut slots = Vec::with_capacity(ZERO_SLOTS); + for _ in 0..ZERO_SLOTS { + let (alloc, list) = super::title_textures::own_work(|| -> windows::core::Result<_> { + let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None)?; + l.Close()?; + Ok((a, l)) + }) + .ok()?; + slots.push(ZeroSlot { alloc, list, fence_val: 0, kept_bufs: Vec::new() }); + } + Some(ZeroRing { zero_src, slots }) + } +} + impl std::ops::Index for PoolHeaps { type Output = ID3D12Heap; fn index(&self, idx: usize) -> &Self::Output { @@ -594,6 +795,54 @@ fn keep_spare_pools() -> usize { }) } +/// Deferred `UpdateTileMappings(NULL)` operation awaiting completion of all in-flight device queues. +enum PendingUnmapOp { + /// Whole-resource unmap from `unmap_placed` (skipped if `Target::mapping_gen` advanced). + Whole { res: ID3D12Resource, key: usize, gen: u64, total: u32, tiles: Vec }, +} + +/// Sealed batch of deferred unmaps waiting on live device queues (`F` = fence; pure-CPU types in tests). +struct PendingUnmapBatch { + ops: Vec, + /// `None` if signaling any live queue failed (held to avoid premature unmapping). + marks: Option>, +} + +/// Seal a pre-signal snapshot of unsealed unmaps with `marks` into `pending`, leaving any ops +/// pushed concurrently after the snapshot untouched in `unsealed` for a future fresh signal. +fn seal_snapshot_ops( + ops: Vec, + marks: Option>, + pending: &mut std::collections::VecDeque>, +) { + if !ops.is_empty() { + pending.push_back(PendingUnmapBatch { ops, marks }); + } +} + +/// Pop every front batch in `queue` whose fence marks have all completed. +fn drain_ready_unmap_batches( + queue: &mut std::collections::VecDeque>, + mut completed: impl FnMut(&F) -> u64, +) -> Vec { + let mut ready = Vec::new(); + while queue.front().is_some_and(|b| b.marks.as_ref().is_some_and(|m| m.iter().all(|(f, v)| completed(f) >= *v))) { + if let Some(batch) = queue.pop_front() { + ready.extend(batch.ops); + } + } + ready +} + +/// Tile-mapping queues across devices, kept outside `PAGES` so `late_release` (called from inside +/// COM `Release`) can fence them without acquiring `PAGES.lock()`. +static VRAM_QUEUES: Mutex> = Mutex::new(Vec::new()); + +/// Live `vram` tile-mapping queues (lock-free with respect to `PAGES`). +pub fn queues() -> Vec { + VRAM_QUEUES.lock().unwrap().clone() +} + /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, @@ -602,6 +851,20 @@ struct Pages { value: u64, /// per-device timestamp of the last periodic reclaim check last_reclaim: std::time::Instant, + /// creation time (lower bound for `safe_cool_before` once live queues are observed) + created_at: std::time::Instant, + /// true once `before_execute` has run on a live queue for this device + has_live_queues: bool, + /// unmaps queued inside `PAGES.lock()` awaiting live-queue fence marks (`seal_and_drain_unmaps`) + unsealed_unmaps: Vec, + /// sealed unmaps awaiting all live device queues before `UpdateTileMappings(NULL)` executes + pending_unmaps: std::collections::VecDeque>, + /// unshared tiles already unmapped on `self.queue`, awaiting `self.fence >= val` before returning to `pool` + fenced_tiles: std::collections::VecDeque<(u64, Vec)>, + /// periodic multi-queue fence probe bounding `TilePool::cooling` against >2s GPU/PSO stalls + cool_probe: Option<(std::time::Instant, Vec<(ID3D12Fence, u64)>)>, + /// latest timestamp proven free of in-flight work across all live device queues + safe_cool_before: Option, /// pool heaps by `Tile` index (a reclaimed one's slot is empty, as `TilePool::live` has it) pools: PoolHeaps, pool: TilePool, @@ -623,6 +886,12 @@ struct Pages { scratch_flags: Vec, scratch_offsets: Vec, scratch_counts: Vec, + /// recycled tiles awaiting batched GPU zero-fill on `self.queue` before next `before_execute` + pending_zero_tiles: Vec, + /// lazily initialized command ring + 1 MiB zero source for `flush_zero_tiles` + zero_ring: Option, + /// true once `ZeroRing::new` failed so we don't retry every submit + zero_ring_failed: bool, } // D3D12 objects are free-threaded @@ -643,12 +912,21 @@ impl Pages { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; let _ = queue.SetName(windows::core::w!("xcl vram tile-mapping queue")); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + VRAM_QUEUES.lock().unwrap().push(queue.clone()); crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); + let now = std::time::Instant::now(); Some(Pages { queue, fence, value: 0, - last_reclaim: std::time::Instant::now(), + last_reclaim: now, + created_at: now, + has_live_queues: false, + unsealed_unmaps: Vec::new(), + pending_unmaps: std::collections::VecDeque::new(), + fenced_tiles: std::collections::VecDeque::new(), + cool_probe: None, + safe_cool_before: None, pools: PoolHeaps::new(), pool: TilePool::new(), pages: std::collections::HashMap::new(), @@ -661,7 +939,136 @@ impl Pages { scratch_flags: Vec::new(), scratch_offsets: Vec::new(), scratch_counts: Vec::new(), + pending_zero_tiles: Vec::new(), + zero_ring: None, + zero_ring_failed: false, + }) + } + + /// Latest timestamp proven free of in-flight GPU work when live queues are tracked. + #[inline] + fn cool_bound(&self) -> Option { + self.has_live_queues.then(|| self.safe_cool_before.unwrap_or(self.created_at)) + } + + /// Return any unshared tiles whose deferred `UpdateTileMappings(NULL)` fence on `self.queue` + /// has completed back into `self.pool` immediately. + unsafe fn drain_fenced_tiles(&mut self) { + if self.fenced_tiles.is_empty() { + return; + } + let done = super::real::fence_completed(&self.fence); + while self.fenced_tiles.front().is_some_and(|&(fv, _)| done >= fv) { + if let Some((_, tiles)) = self.fenced_tiles.pop_front() { + self.pool.return_tiles(&tiles); + } + } + } + + /// Asynchronously zero all queued recycled pool tiles on `self.queue` in one batched command + /// list, then emit an aliasing barrier + `self.fence` signal so any title queue waiting in + /// `before_execute` sees zeroed tiles before reading or writing newly mapped textures. + unsafe fn flush_zero_tiles(&mut self, dev: &ID3D12Device) { + if self.pending_zero_tiles.is_empty() { + return; + } + if !zero_target_pages() || self.zero_ring_failed { + self.pending_zero_tiles.clear(); + return; + } + let runs = coalesce_tile_runs(&mut self.pending_zero_tiles); + self.pending_zero_tiles.clear(); + if runs.is_empty() { + return; + } + if self.zero_ring.is_none() { + match ZeroRing::new(dev) { + Some(r) => self.zero_ring = Some(r), + None => { + self.zero_ring_failed = true; + return; + } + } + } + let mut heap_bufs: std::collections::HashMap = std::collections::HashMap::new(); + for &(h, _, _) in &runs { + if !heap_bufs.contains_key(&h) { + if let Some(buf) = self.pools.zero_buffer(dev, h as usize) { + heap_bufs.insert(h, buf); + } + } + } + if heap_bufs.is_empty() { + return; + } + let done = self.fence.GetCompletedValue(); + let ring = self.zero_ring.as_mut().unwrap(); + let slot_idx = match ring.slots.iter().position(|s| s.fence_val <= done) { + Some(i) => i, + None => { + let (oldest_idx, oldest_val) = ring + .slots + .iter() + .enumerate() + .min_by_key(|(_, s)| s.fence_val) + .map(|(i, s)| (i, s.fence_val)) + .unwrap(); + let _ = crate::gpu::fence::wait(&self.fence, oldest_val, dev, None, 5_000); + oldest_idx + } + }; + let zero_src = ring.zero_src.clone(); + let slot = &mut ring.slots[slot_idx]; + slot.kept_bufs.clear(); + let ok = super::title_textures::own_work(|| -> windows::core::Result<()> { + slot.alloc.Reset()?; + slot.list.Reset(&slot.alloc, None)?; + for &(h, start, count) in &runs { + let Some(dst) = heap_bufs.get(&h) else { continue }; + let mut offset = start as u64 * PAGE as u64; + let mut rem = count as u64 * PAGE as u64; + while rem > 0 { + let chunk = rem.min(ZERO_BUF_BYTES); + slot.list.CopyBufferRegion(dst, offset, &zero_src, 0, chunk); + offset += chunk; + rem -= chunk; + } + } + let mut barriers: Vec = Vec::with_capacity(heap_bufs.len()); + for buf in heap_bufs.values() { + slot.kept_bufs.push(buf.clone()); + barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::transmute_copy(buf), + pResourceAfter: std::mem::zeroed(), + }), + }, + }); + } + if !barriers.is_empty() { + slot.list.ResourceBarrier(&barriers); + } + slot.list.Close()?; + let cmd: ID3D12CommandList = slot.list.cast()?; + let q_raw = self.queue.as_raw(); + let list_raw = cmd.as_raw(); + if super::real::is_adopted(q_raw) { + let exec: unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) = std::mem::transmute(super::real::orig_fn(q_raw, 10)); + exec(q_raw, 1, &list_raw); + } else { + self.queue.ExecuteCommandLists(&[Some(cmd)]); + } + Ok(()) }) + .is_ok(); + if ok { + self.value += 1; + let _ = self.queue.Signal(&self.fence, self.value); + slot.fence_val = self.value; + } } /// Pages no resource used for `IDLE` go back to the pools. @@ -672,14 +1079,14 @@ impl Pages { /// Sweep expired idle pages, drain cooled tiles, and reclaim any completely empty 64 MiB /// pool heaps (above the warm spare count), returning their `ID3D12Heap`s to be dropped /// outside `PAGES.lock()`. - fn sweep_and_reclaim(&mut self, now: std::time::Instant) -> Vec { + fn sweep_and_reclaim(&mut self, now: std::time::Instant) -> Vec { self.sweep(now); - self.pool.drain_cooling(now); + self.pool.drain_cooling_before(now, self.cool_bound()); let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare_pools(), POOL_PAGES); let mut dropped = Vec::with_capacity(reclaimed_ids.len()); for idx in reclaimed_ids { - if let Some(h) = self.pools.take_heap(idx) { - dropped.push(h); + if let Some((heap, zero_buf)) = self.pools.take_heap(idx) { + dropped.push(RetiringHeap { zero_buf, heap }); } } if !dropped.is_empty() { @@ -771,6 +1178,76 @@ impl Pages { let _ = self.queue.Signal(&self.fence, self.value); } + /// Unmap selected tiles (`sel(i) == true`) of `res` (`D3D12_TILE_RANGE_FLAG_NULL`). + unsafe fn unmap_selected(&mut self, res: &ID3D12Resource, total: u32, sel: impl Fn(u32) -> bool) { + if total == 0 { + return; + } + let mut flags: Vec = Vec::new(); + let mut counts: Vec = Vec::new(); + let mut any_null = false; + for i in 0..total { + let f = if sel(i) { + any_null = true; + D3D12_TILE_RANGE_FLAG_NULL + } else { + D3D12_TILE_RANGE_FLAG_SKIP + }; + if flags.last().is_some_and(|&prev| prev == f) { + *counts.last_mut().unwrap() += 1; + } else { + flags.push(f); + counts.push(1); + } + } + if !any_null { + return; + } + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; + self.queue.UpdateTileMappings( + res, + 1, + Some(&coord), + Some(®ion), + None, + flags.len() as u32, + Some(flags.as_ptr()), + None, + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + self.value += 1; + let _ = self.queue.Signal(&self.fence, self.value); + } + + /// Decrement page refcounts for a superseded texture and collect any now-unshared pool tiles + /// so they stay quarantined until the deferred `UpdateTileMappings(NULL)` finishes on the GPU. + fn release_tiles_unshared(&mut self, used: Vec, used_extra: Vec<(usize, usize)>) -> Vec { + let mut unshared = Vec::new(); + for a in used { + if let Some(p) = self.pages.get_mut(&a) { + p.users = p.users.saturating_sub(1); + if p.users == 0 { + if let Some(p) = self.pages.remove(&a) { + unshared.push(p.tile); + } + } + } + } + for k in used_extra { + if let Some(p) = self.extra_pages.get_mut(&k) { + p.users = p.users.saturating_sub(1); + if p.users == 0 { + if let Some(p) = self.extra_pages.remove(&k) { + unshared.push(p.tile); + } + } + } + } + unshared + } + fn release_tiles(&mut self, used: Vec, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { for a in used { if let Some(p) = self.pages.get_mut(&a) { @@ -804,14 +1281,15 @@ impl Pages { } } - /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. - unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { - self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize) + /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue + /// (`phys[i]`: the title's physical page at owned page i, if any – see `page_key`). + unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, phys: &[Option]) -> Option<(Vec, Vec<(usize, usize)>)> { + self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize, phys) } /// `bind` for the tiles `range` of the resource's `total`, which start at subresource `sub`. #[allow(clippy::too_many_arguments)] - unsafe fn bind_range(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, sub: u32, range: std::ops::Range) -> Option<(Vec, Vec<(usize, usize)>)> { + unsafe fn bind_range(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, sub: u32, range: std::ops::Range, phys: &[Option]) -> Option<(Vec, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); @@ -820,7 +1298,8 @@ impl Pages { let mut preferred: Option = None; for i in range.clone() { let existing = if i < own { - self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) + let key = page_key(first + i * PAGE, phys.get(i).copied().flatten()); + self.pages.get(&key).map(|p| p.tile.0) } else { self.extra_pages.get(&(va, i)).map(|p| p.tile.0) }; @@ -831,9 +1310,11 @@ impl Pages { } } + let safe_before = self.cool_bound(); let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { + let pending_zero = &mut self.pending_zero_tiles; + let fresh = pool.take_batch_recycled(missing, preferred, now, safe_before, POOL_PAGES, pending_zero, || { let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; @@ -844,8 +1325,8 @@ impl Pages { let mut used_extra = Vec::new(); for i in range { let tile = if i < own { - let a = first + i * PAGE; - let t = match self.pages.get_mut(&a) { + let key = page_key(first + i * PAGE, phys.get(i).copied().flatten()); + let t = match self.pages.get_mut(&key) { Some(p) => { p.users += 1; p.idle_since = None; @@ -853,11 +1334,11 @@ impl Pages { } None => { let t = fresh_iter.next().unwrap(); - self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); + self.pages.insert(key, Page { tile: t, users: 1, idle_since: None }); t } }; - used.push(a); + used.push(key); t } else { let k = (va, i); @@ -879,6 +1360,9 @@ impl Pages { tiles.push(tile); } self.map(res, sub, &tiles); + if self.pending_zero_tiles.len() >= 256 { + self.flush_zero_tiles(dev); + } Some((used, used_extra)) } } @@ -967,6 +1451,30 @@ pub(super) fn canonical_va(va: usize) -> usize { if mapped { va } else { src } } +/// Keys of `Pages::pages` for the title's physical pages (title addresses never have bit 63). +const PHYS_KEY: usize = 1 << 63; + +/// The key of the page of video memory for title page address `a`: the physical page mapped +/// there (`phys`), else the address. A retail game maps one physical page under render targets +/// at two addresses (aliasing, as on the console): keyed by address, each got video memory of +/// its own (1.85 GB more in its first 40 s) and what the GPU wrote through one never showed in +/// the other. +fn page_key(a: usize, phys: Option) -> usize { + phys.map_or(a, |p| PHYS_KEY | p) +} + +/// The physical pages under a GPU-owned texture's owned pages (`require_aligned`), asked before +/// `PAGES` is taken; empty for others (keyed by address) and without the console size. +fn physical_pages_under(va: usize, console_bytes: Option, require_aligned: bool) -> Vec> { + if !require_aligned { + return Vec::new(); + } + match console_bytes.and_then(|b| owned_pages(va, Some(b), usize::MAX)) { + Some((first, n)) if n > 0 => crate::hle::kernelx::physical_pages(first, n), + _ => Vec::new(), + } +} + /// A texture at `va` as a reserved resource on the title's shared 64 KiB pages /// (`console_bytes`: its size on the console; tiles past the owned page boundaries are shared by /// `(va, tile_index)` so repeated placements at the same address do not leak). None: it cannot be. @@ -991,6 +1499,7 @@ unsafe fn place_on_pages( if (require_aligned || console_bytes.is_none()) && va % PAGE != 0 { return None; } + let phys = physical_pages_under(va, console_bytes, require_aligned); // reserved textures have the PC's 64 KiB tiles let tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*desc }; static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -1034,10 +1543,10 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used: Vec::new(), used_extra: Vec::new(), levels, gpu_owned: require_aligned }); true - } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None }); + } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total, &phys) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, levels: None, gpu_owned: require_aligned }); true } else { false @@ -1061,8 +1570,10 @@ unsafe fn place_on_pages( Some(hr) } -/// Unmap a placed texture superseded by a placement with a different address range, returning its -/// unshared tiles (`extra_pages` and unshared tail pages) to the cooling pool immediately. +/// Defer unmapping a placed texture superseded by a placement with a different address range +/// until all live device queues finish in-flight work, and quarantine its unshared tiles behind +/// both the live queues and `pages.fence` (never calling `UpdateTileMappings(NULL)` concurrently +/// with executing title queues). pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { unmap_placed(res, true); } @@ -1076,24 +1587,51 @@ pub(super) unsafe fn unmap_superseded_target(res: &ID3D12Resource) { unsafe fn unmap_placed(res: &ID3D12Resource, immediate_cool: bool) { let key = res.as_raw() as usize; - let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); - for pages in g.values_mut().flatten() { - let Some(t) = pages.targets.get_mut(&key) else { continue }; - if !t.mapped { - return; - } - let total = t.total; - let used = std::mem::take(&mut t.used); - let used_extra = std::mem::take(&mut t.used_extra); - t.mapped = false; - if let Some(l) = t.levels.as_mut() { - LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); - l.groups.iter_mut().for_each(|g| g.3 = false); + let found_dev = { + let mut g = PAGES.lock().unwrap(); + let mut hit = None; + for (&dev_key, slot) in g.iter_mut() { + let Some(pages) = slot.as_mut() else { continue }; + let Some(t) = pages.targets.get_mut(&key) else { continue }; + if !t.mapped { + return; + } + let total = t.total; + let used = std::mem::take(&mut t.used); + let used_extra = std::mem::take(&mut t.used_extra); + t.mapped = false; + t.mapping_gen = t.mapping_gen.wrapping_add(1); + let gen = t.mapping_gen; + if let Some(l) = t.levels.as_mut() { + LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); + l.groups.iter_mut().for_each(|g| g.3 = false); + } + let unshared = if immediate_cool { + pages.release_tiles_unshared(used, used_extra) + } else { + pages.release_tiles(used, used_extra, now, false); + Vec::new() + }; + pages.unsealed_unmaps.push(PendingUnmapOp::Whole { + res: res.clone(), + key, + gen, + total, + tiles: unshared, + }); + hit = Some(dev_key); + break; + } + hit + }; + if let Some(dev_key) = found_dev { + let mut dev: Option = None; + if res.GetDevice(&mut dev).is_ok() { + if let Some(dev) = dev { + seal_and_drain_unmaps(&dev, dev_key, None); + } } - pages.unmap(res, total); - pages.release_tiles(used, used_extra, now, immediate_cool); - return; } } @@ -1105,26 +1643,36 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { } let Some(dev) = dev else { return false }; let key = res.as_raw() as usize; - let mut g = PAGES.lock().unwrap(); - let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; - let Some((va, console_bytes, total, mapped)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped)) else { - return false; + let target = |g: &mut std::sync::MutexGuard<'_, std::collections::BTreeMap>>| { + let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return None }; + pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped, t.gpu_owned)) }; + // (the physical pages are asked without `PAGES` held) + let Some((va, console_bytes, _, mapped, gpu_owned)) = target(&mut PAGES.lock().unwrap()) else { return false }; if mapped { return true; } + let phys = physical_pages_under(va, console_bytes, gpu_owned); + let mut g = PAGES.lock().unwrap(); + let Some((va, console_bytes, total, mapped, _)) = target(&mut g) else { return false }; + if mapped { + return true; + } + let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; // (lazy levels: they get their pages again with their next texels) if let Some(t) = pages.targets.get_mut(&key).filter(|t| t.levels.is_some()) { t.mapped = true; + t.mapping_gen = t.mapping_gen.wrapping_add(1); return true; } - let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { + let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total, &phys) else { return false; }; if let Some(t) = pages.targets.get_mut(&key) { t.used = used; t.used_extra = used_extra; t.mapped = true; + t.mapping_gen = t.mapping_gen.wrapping_add(1); } true } @@ -1156,6 +1704,32 @@ struct RetireQueue { fences: std::collections::HashMap, b impl RetireQueue { fn new() -> Self { Self { fences: std::collections::HashMap::new(), batches: Vec::new() } } + /// Signal one fence value on each queue in `queues`; returns `None` if any fence creation or + /// signal fails so callers never mistake a failed signal for an idle GPU. + fn signal_queues_with( + &mut self, + queues: &[(usize, Q)], + mut make_fence: impl FnMut() -> Option, + mut signal: impl FnMut(&Q, &F, u64) -> bool, + ) -> Option> { + let mut marks = Vec::with_capacity(queues.len()); + for (k, q) in queues { + let (f, v) = match self.fences.entry(*k) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => { + let Some(f) = make_fence() else { return None }; + e.insert((f, 0)) + } + }; + if !signal(q, f, *v + 1) { + return None; + } + *v += 1; + marks.push((f.clone(), *v)); + } + Some(marks) + } + /// Seal `heaps` behind `unmap_mark` and one fence signal per queue (signaled BEFORE queueing). /// Returns `heaps` immediately when zero marks were signaled and `unmap_mark` is `None`. fn retire_with(&mut self, heaps: Vec, unmap_mark: Option<(F, u64)>, queues: &[(usize, Q)], mut make_fence: impl FnMut() -> Option, mut signal: impl FnMut(&Q, &F, u64) -> bool) -> Vec { @@ -1186,9 +1760,17 @@ impl RetireQueue { } } -unsafe impl Send for RetireQueue {} +/// Reclaimed pool/arena heap paired with its optional placed `zero_buf` alias. +/// `zero_buf` is declared before `heap` so Rust drops the placed buffer before its backing heap. +struct RetiringHeap { + zero_buf: Option, + heap: ID3D12Heap, +} + +unsafe impl Send for RetiringHeap {} +unsafe impl Send for RetireQueue {} -static RETIRE: Mutex>>> = Mutex::new(None); +static RETIRE: Mutex>>> = Mutex::new(None); static RETIRING_BATCHES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// Collect all known live command queues belonging to `dev_key` (deduplicated by raw ptr). @@ -1216,7 +1798,7 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu /// go as a resource the title released does (`late_release::hold_heap`), outside all locks too: /// a texture the title released may still map pages of one, and is held there until the work /// queued before its release is done – a heap gone under that work is a page fault of the GPU. -unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_reclaimed: Vec, unmap_mark: Option<(ID3D12Fence, u64)>, extra_queue: Option<&ID3D12CommandQueue>) { +unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_reclaimed: Vec, unmap_mark: Option<(ID3D12Fence, u64)>, extra_queue: Option<&ID3D12CommandQueue>) { let queues = collect_device_queues(dev_key, extra_queue); let live_keys: HashSet = queues.iter().map(|&(k, _)| k).collect(); let (immediate, done, _drop_outside_locks) = { @@ -1231,11 +1813,110 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla RETIRING_BATCHES.fetch_add(rq.batches.len().wrapping_sub(before), std::sync::atomic::Ordering::AcqRel); (immediate, done, pruned) }; - for heap in immediate.into_iter().chain(done.into_iter().flat_map(|b| b.heaps)) { - super::late_release::hold_heap(heap); + for rh in immediate.into_iter().chain(done.into_iter().flat_map(|b| b.heaps)) { + if let Some(buf) = rh.zero_buf { + super::late_release::hold(buf.into_raw() as usize, false); + } + super::late_release::hold_heap(rh.heap); } } +/// Signal every live queue on `dev_key` using `RETIRE`'s per-queue fences (never locking `PAGES`). +unsafe fn signal_device_queues( + dev: &ID3D12Device, + dev_key: usize, + extra_queue: Option<&ID3D12CommandQueue>, +) -> Option> { + let queues = collect_device_queues(dev_key, extra_queue); + let mut guard = RETIRE.lock().unwrap(); + let map = guard.get_or_insert_with(std::collections::HashMap::new); + let rq = map.entry(dev_key).or_insert_with(RetireQueue::new); + rq.signal_queues_with( + &queues, + || dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok(), + |q, f, v| q.Signal(f, v).is_ok(), + ) +} + +/// Seal any unsealed deferred unmaps and/or a cooling-tile fence probe behind all live queues on +/// `dev_key`, drain every completed unmap batch onto `pages.queue` (skipping cancelled/remapped +/// targets), and drop popped COM resource references outside `PAGES.lock()`. +unsafe fn seal_and_drain_unmaps(dev: &ID3D12Device, dev_key: usize, extra_queue: Option<&ID3D12CommandQueue>) { + // Snapshot `unsealed_unmaps` BEFORE releasing `PAGES.lock()` to signal live queues so any + // unmaps pushed concurrently after `signal_device_queues` are never sealed with stale marks. + let (snapshot_ops, need_cool_probe, has_pending_or_probe) = { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return }; + let ops = std::mem::take(&mut pages.unsealed_unmaps); + let need_probe = pages.has_live_queues && pages.cool_probe.is_none() && (!pages.pool.cooling.is_empty() || !pages.idle.is_empty()); + let has_waiters = !pages.pending_unmaps.is_empty() || pages.cool_probe.is_some(); + (ops, need_probe, has_waiters) + }; + let need_seal_unmaps = !snapshot_ops.is_empty(); + if !need_seal_unmaps && !need_cool_probe && !has_pending_or_probe { + return; + } + let marks = if need_seal_unmaps || need_cool_probe { + signal_device_queues(dev, dev_key, extra_queue) + } else { + None + }; + let probe_at = std::time::Instant::now(); + let mut drop_outside: Vec = Vec::new(); + { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { + drop(g); + drop(snapshot_ops); + return; + }; + seal_snapshot_ops(snapshot_ops, marks.clone(), &mut pages.pending_unmaps); + if pages.has_live_queues && pages.cool_probe.is_none() && (!pages.pool.cooling.is_empty() || !pages.idle.is_empty()) { + if let Some(probe_marks) = marks { + pages.cool_probe = Some((probe_at, probe_marks)); + } + } + if let Some((at, ref probe_marks)) = pages.cool_probe { + if probe_marks.iter().all(|(f, v)| super::real::fence_completed(f) >= *v) { + pages.safe_cool_before = Some(pages.safe_cool_before.map_or(at, |prev| prev.max(at))); + pages.cool_probe = None; + } + } + let ready = drain_ready_unmap_batches(&mut pages.pending_unmaps, |f| super::real::fence_completed(f)); + let mut newly_fenced_tiles: Vec = Vec::new(); + for op in ready { + match op { + PendingUnmapOp::Whole { res, key, gen, total, tiles } => { + match pages.targets.get(&key) { + Some(t) if t.mapping_gen != gen && t.mapped => { + if let Some(lv) = t.levels.as_ref() { + // Lazy texture was remapped without binding all levels: unmap only + // still-unmapped level groups so recycled tiles have no stale PTEs. + let lv_clone = lv.clone(); + pages.unmap_selected(&res, total, |tile_idx| { + lv_clone.groups.iter().any(|&(_, first, count, mapped)| { + !mapped && tile_idx >= first && tile_idx < first + count + }) + }); + } + } + _ => { + pages.unmap(&res, total); + } + } + newly_fenced_tiles.extend(tiles); + drop_outside.push(res); + } + } + } + if !newly_fenced_tiles.is_empty() { + pages.fenced_tiles.push_back((pages.value, newly_fenced_tiles)); + } + pages.drain_fenced_tiles(); + } + drop(drop_outside); +} + /// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device, /// release any previously retired heaps whose GPU fences have completed, and periodically (once /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind @@ -1250,14 +1931,18 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let now = std::time::Instant::now(); let mut newly_reclaimed = Vec::new(); let mut do_reclaim = false; + let mut need_unmap_work = false; let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; + let mut mapping_wait: Option<(ID3D12Fence, u64)> = None; { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { + pages.has_live_queues = true; + pages.drain_fenced_tiles(); + pages.flush_zero_tiles(&dev); let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { - let _ = queue.Wait(&pages.fence, pages.value); - super::list_x::note_internal_wait(key, "texture page mappings", &pages.fence, pages.value); + mapping_wait = Some((pages.fence.clone(), pages.value)); pages.waited.insert(key, pages.value); } if now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { @@ -1268,16 +1953,69 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { unmap_mark = Some((pages.fence.clone(), pages.value)); } } + need_unmap_work = !pages.unsealed_unmaps.is_empty() + || !pages.pending_unmaps.is_empty() + || pages.cool_probe.is_some() + || !pages.pool.cooling.is_empty() + || !pages.idle.is_empty(); } } + if let Some((fence, value)) = mapping_wait { + if !super::sparse::cpu_waited_for_mappings(&fence, value, "texture page mappings") { + let _ = queue.Wait(&fence, value); + super::list_x::note_internal_wait(queue.as_raw() as usize, "texture page mappings", &fence, value); + } + } + if need_unmap_work { + seal_and_drain_unmaps(&dev, dev_key, Some(queue)); + } if do_reclaim { - newly_reclaimed.extend(ARENAS.lock().unwrap().sweep_dropped_for(dev_key, now)); + newly_reclaimed.extend( + ARENAS + .lock() + .unwrap() + .sweep_dropped_for(dev_key, now) + .into_iter() + .map(|heap| RetiringHeap { zero_buf: None, heap }), + ); } if do_reclaim || !newly_reclaimed.is_empty() || RETIRING_BATCHES.load(std::sync::atomic::Ordering::Acquire) > 0 { retire_heaps_and_sweep(&dev, dev_key, newly_reclaimed, unmap_mark, Some(queue)); } } +/// Fast-path wait for any tile mappings or recycled-tile zero-fills queued on `queue`'s device +/// after `title_textures::refresh` (for example while `record_deferred` waited on PSO builds). +pub(super) unsafe fn wait_pending_mappings(queue: &ID3D12CommandQueue) { + let mut dev: Option = None; + if queue.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let dev_key = dev.as_raw() as usize; + let key = queue.as_raw() as usize; + let mut mapping_wait: Option<(ID3D12Fence, u64)> = None; + { + let mut g = PAGES.lock().unwrap(); + if let Some(Some(pages)) = g.get_mut(&dev_key) { + if pages.queue.as_raw() as usize == key { + return; + } + pages.flush_zero_tiles(&dev); + if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { + mapping_wait = Some((pages.fence.clone(), pages.value)); + pages.waited.insert(key, pages.value); + } + } + } + if let Some((fence, value)) = mapping_wait { + if !super::sparse::cpu_waited_for_mappings(&fence, value, "texture page mappings") { + let _ = queue.Wait(&fence, value); + super::list_x::note_internal_wait(key, "texture page mappings", &fence, value); + } + } +} + #[cfg(test)] pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); @@ -1298,9 +2036,32 @@ pub(super) fn mapped_tiles_for(device: usize, resource: usize) -> Option<(Vec<(u #[cfg(test)] pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { + let (su, sp) = super::vram_small::bytes_for(device); let g = PAGES.lock().unwrap(); - let Some(Some(p)) = g.get(&device) else { return (0, 0) }; - ((p.pages.len() + p.extra_pages.len()) * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + let Some(Some(p)) = g.get(&device) else { return (su, sp) }; + ((p.pages.len() + p.extra_pages.len()) * PAGE + su, p.pools.len() * POOL_PAGES as usize * PAGE + sp) +} + +/// Immediately evict all unreferenced idle pages and small-pool slots on `device` so GPU tests +/// sharing the process's singleton `ID3D12Device` do not observe stale `IDLE` expiries mid-test. +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + super::vram_small::flush_idle_for(device); + let mut g = PAGES.lock().unwrap(); + if let Some(Some(p)) = g.get_mut(&device) { + let now = std::time::Instant::now(); + while let Some((key, since)) = p.idle.pop_front() { + let still_idle = |pg: &Page| pg.idle_since == Some(since); + let page = match key { + PageKey::Own(a) if p.pages.get(&a).is_some_and(still_idle) => p.pages.remove(&a), + PageKey::Extra(va, i) if p.extra_pages.get(&(va, i)).is_some_and(still_idle) => p.extra_pages.remove(&(va, i)), + _ => None, + }; + if let Some(pg) = page { + p.pool.push_cooling(pg.tile, now); + } + } + } } /// Pool/tile identities used by one mapped resource: title pages, then extra pages. @@ -1341,9 +2102,21 @@ pub fn page_owners() -> String { ) } +/// Whether `va` already has a live (or still within `IDLE`) 64 KiB page on `device` (e.g., an +/// existing GPU-owned render target that a sampled view at the same 64 KiB-aligned address should +/// alias). +fn has_live_page(device: usize, va: usize) -> bool { + let g = PAGES.lock().unwrap(); + let now = std::time::Instant::now(); + g.get(&device) + .and_then(|p| p.as_ref()) + .is_some_and(|p| p.pages.get(&va).is_some_and(|pg| pg.idle_since.is_none_or(|s| now.duration_since(s) < IDLE))) +} + pub fn page_bytes() -> (usize, usize) { + let (su, sp) = super::vram_small::bytes(); let g = PAGES.lock().unwrap(); - g.values().flatten().fold((0, 0), |(used, pools), p| { + g.values().flatten().fold((su, sp), |(used, pools), p| { (used + (p.pages.len() + p.extra_pages.len()) * PAGE, pools + p.pools.len() * POOL_PAGES as usize * PAGE) }) } @@ -1354,6 +2127,20 @@ fn tier2(dev: &ID3D12Device) -> bool { unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.ResourceHeapTier.0 >= 2 } } +/// Whether a sampled reserved texture should defer tile mapping per mip level (`level_pages`). +/// Sampled views aliasing an already-live 64 KiB GPU page (`aliases_live`, e.g., an SRV placed +/// over a render target, depth buffer, or Hi-Z UAV pyramid) must map immediately onto those live +/// pages rather than staying lazy: their CPU memory is zeros so upload-driven level mapping +/// would leave every tile unmapped. +fn should_use_lazy_levels(level_pages_on: bool, aliases_live: bool, desc: &D3D12_RESOURCE_DESC) -> bool { + !aliases_live + && level_pages_on + && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && desc.DepthOrArraySize == 1 + && desc.SampleDesc.Count == 1 + && desc.Flags == D3D12_RESOURCE_FLAG_NONE +} + /// A sampled texture of the title at `va` (`desc`: the PC description, `console_bytes` its size on /// the console) backed by shared 64 KiB video-memory pages; None when reserved placement is not /// available (the caller falls back to a committed resource). @@ -1375,8 +2162,17 @@ pub unsafe fn place_pages( if console_has_packed_3d_mips(desc) { return None; } + // a texture of less than 64 KiB that does not alias a live page: a block of a shared heap + // (`vram_small`), with no reserved resource and no tile mappings of its own + let aliases_live = va % PAGE == 0 && has_live_page(dev.as_raw() as usize, canonical_va(va)); + if !aliases_live { + if let Some(hr) = super::vram_small::place(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { + PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + return Some(hr); + } + } // (one slice: the tiles of an array's packed levels are not asked about here) - let lazy = level_pages() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.DepthOrArraySize == 1 && desc.SampleDesc.Count == 1 && desc.Flags == D3D12_RESOURCE_FLAG_NONE; + let lazy = should_use_lazy_levels(level_pages(), aliases_live, desc); // (as `place`: without a size every PC tile went on the title's pages from `va` on) let console_bytes = console_bytes.or_else(|| { let least = least_texture_bytes(desc); @@ -1413,7 +2209,7 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; let mut fresh = Vec::new(); for (k, sub, first, n, levels) in todo { - let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { continue }; + let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, &[]) else { continue }; let Some(t) = pages.targets.get_mut(&key) else { return fresh }; t.used.extend(used); t.used_extra.extend(used_extra); @@ -1616,6 +2412,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st let dev_key = dev.as_raw() as usize; let (taken, expired) = ARENAS.lock().unwrap().take_for(dev_key, va, info.SizeInBytes as usize, align, now, |size, align| arena_heap(dev, va, size, align)); if !expired.is_empty() { + let expired = expired.into_iter().map(|heap| RetiringHeap { zero_buf: None, heap }).collect(); retire_heaps_and_sweep(dev, dev_key, expired, None, None); } let (heap, offset, id) = taken?; @@ -2491,4 +3288,131 @@ mod tests { assert!(new_calls < old_calls); } } + + /// `page_key` keys physical-backed GPU-owned pages by physical page (high bit set, disjoint + /// from title VAs) so aliased render targets at two VAs share one backing tile, and falls back + /// to the title VA otherwise. + #[test] + fn page_key_aliases_same_physical_page_across_virtual_addresses() { + let va1 = 0x10_0000_0000usize; + let va2 = 0x11_0000_0000usize; + let phys = 0x2_0000_0000usize; + assert_eq!(page_key(va1, Some(phys)), page_key(va2, Some(phys))); + assert_ne!(page_key(va1, Some(phys)), page_key(va1, None)); + assert_ne!(page_key(va1, Some(phys)), page_key(va1, Some(phys + PAGE))); + assert_eq!(page_key(va1, None), va1); + } + + #[test] + fn tile_pool_tracks_dirty_bits_only_for_recycled_tiles() { + let mut pool = TilePool::new(); + let now = std::time::Instant::now(); + let mut recycled = Vec::new(); + let mut next_h = 0u32; + + // Fresh heap tiles are never marked recycled (D3D12 guarantees fresh heaps are zeroed). + let first = pool + .take_batch_recycled(4, None, now, None, POOL_PAGES, &mut recycled, || { + let h = next_h; + next_h += 1; + Some(h) + }) + .unwrap(); + assert_eq!(first, vec![(0, 0), (0, 1), (0, 2), (0, 3)]); + assert!(recycled.is_empty(), "freshly allocated heap tiles must not need GPU zeroing"); + + // Returned tiles are marked dirty and reported in `recycled` when re-taken. + pool.return_tiles(&[(0, 1), (0, 2)]); + let again = pool + .take_batch_recycled(3, Some(0), now, None, POOL_PAGES, &mut recycled, || None) + .unwrap(); + assert_eq!(again, vec![(0, 1), (0, 2), (0, 4)]); + assert_eq!(recycled, vec![(0, 1), (0, 2)], "only previously returned tiles require zeroing"); + + // Cooled tiles also mark dirty when drained back into free_by_heap. + recycled.clear(); + pool.push_cooling((0, 0), now); + let later = now + COOL + std::time::Duration::from_millis(1); + let cooled = pool + .take_batch_recycled(1, Some(0), later, None, POOL_PAGES, &mut recycled, || None) + .unwrap(); + assert_eq!(cooled, vec![(0, 0)]); + assert_eq!(recycled, vec![(0, 0)]); + } + + #[test] + fn coalesce_tile_runs_merges_adjacent_tiles_per_heap() { + let mut tiles = vec![(1, 5), (0, 3), (0, 2), (1, 6), (0, 3), (0, 10), (1, 4)]; + assert_eq!(coalesce_tile_runs(&mut tiles), vec![(0, 2, 2), (0, 10, 1), (1, 4, 3)]); + let mut empty = Vec::new(); + assert!(coalesce_tile_runs(&mut empty).is_empty()); + } + + #[test] + fn pending_unmap_batches_wait_for_all_live_queues_and_hold_on_signal_error() { + use std::collections::VecDeque; + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let f1 = Arc::new(AtomicU64::new(0)); + let f2 = Arc::new(AtomicU64::new(0)); + let mut q: VecDeque>> = VecDeque::new(); + q.push_back(PendingUnmapBatch { + ops: vec!["unmap_a"], + marks: Some(vec![(f1.clone(), 1), (f2.clone(), 1)]), + }); + q.push_back(PendingUnmapBatch { + ops: vec!["unmap_failed_signal"], + marks: None, + }); + f1.store(1, Ordering::SeqCst); + assert!(drain_ready_unmap_batches(&mut q, |f| f.load(Ordering::SeqCst)).is_empty()); + assert_eq!(q.len(), 2); + f2.store(1, Ordering::SeqCst); + assert_eq!(drain_ready_unmap_batches(&mut q, |f| f.load(Ordering::SeqCst)), vec!["unmap_a"]); + assert_eq!(q.len(), 1); + assert!(drain_ready_unmap_batches(&mut q, |f| f.load(Ordering::SeqCst)).is_empty()); + } + + #[test] + fn seal_and_drain_unmaps_does_not_attach_stale_marks_to_concurrent_unmaps() { + use std::collections::VecDeque; + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let mut unsealed: Vec<&'static str> = vec!["unmap_before_signal"]; + let mut pending: VecDeque>> = VecDeque::new(); + let snapshot = std::mem::take(&mut unsealed); + let q_fence = Arc::new(AtomicU64::new(0)); + let stale_marks = Some(vec![(q_fence.clone(), 1)]); + unsealed.push("unmap_after_signal"); + seal_snapshot_ops(snapshot, stale_marks, &mut pending); + assert_eq!(unsealed, vec!["unmap_after_signal"]); + q_fence.store(1, Ordering::SeqCst); + assert_eq!(drain_ready_unmap_batches(&mut pending, |f| f.load(Ordering::SeqCst)), vec!["unmap_before_signal"]); + assert!(pending.is_empty()); + let snapshot2 = std::mem::take(&mut unsealed); + seal_snapshot_ops(snapshot2, Some(vec![(q_fence.clone(), 2)]), &mut pending); + assert!(drain_ready_unmap_batches(&mut pending, |f| f.load(Ordering::SeqCst)).is_empty()); + q_fence.store(2, Ordering::SeqCst); + assert_eq!(drain_ready_unmap_batches(&mut pending, |f| f.load(Ordering::SeqCst)), vec!["unmap_after_signal"]); + } + + #[test] + fn tile_pool_cooling_respects_gpu_fence_barrier_across_long_stalls() { + let t0 = std::time::Instant::now(); + let mut pool = TilePool::new(); + pool.add_heap_at(0, 4); + let taken = pool.take_batch(4, None, t0, 4, || None).unwrap(); + assert_eq!(pool.free_total, 0); + + pool.push_cooling(taken[0], t0 + std::time::Duration::from_secs(1)); + pool.push_cooling(taken[1], t0 + std::time::Duration::from_secs(2)); + + let t_stall = t0 + std::time::Duration::from_secs(10); + pool.drain_cooling_before(t_stall, Some(t0 + std::time::Duration::from_millis(500))); + assert_eq!(pool.free_total, 0, "cooling tiles must stay held while GPU fence barrier has not passed them"); + + pool.drain_cooling_before(t_stall, Some(t0 + std::time::Duration::from_millis(1500))); + assert_eq!(pool.free_total, 1); + + pool.drain_cooling_before(t_stall, Some(t0 + std::time::Duration::from_millis(2500))); + assert_eq!(pool.free_total, 2); + } } diff --git a/crates/xcl/src/hle/d3d12x/vram_small.rs b/crates/xcl/src/hle/d3d12x/vram_small.rs new file mode 100644 index 0000000000..9b45ef5bc7 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/vram_small.rs @@ -0,0 +1,677 @@ +//! 4 KiB sub-allocated default heaps for small (< 64 KiB) sampled textures. +//! +//! A console title packs thousands of small mip-tails, icons, decals and LUTs at 256 B – 4 KiB +//! offsets inside its texture pools. Backing each one with a 64 KiB reserved resource in +//! `vram::Pages` wastes up to 16× video memory (one full 64 KiB `extra_pages` tile per small +//! texture) and submits a `CreateReservedResource` + `GetResourceTiling` + `UpdateTileMappings` +//! round trip for every placement. +//! +//! Direct3D 12 supports 4 KiB placement (`D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT`) for +//! single-sample non-RT/DS textures whose allocation info fits under 64 KiB. Placing those in +//! shared 16 MiB default heaps packs up to 4 096 textures into one heap with zero tile mappings, +//! shares the exact `(heap, offset)` across repeated placements at the same `(va, size)` so +//! same-address aliases see each other's uploads, and recycles released blocks by size class +//! after `IDLE` + `COOL`. `XCL_VRAM_SMALL=0` disables this path. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::util::HRESULT; + +/// Allocation unit: 4 KiB (`D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT`). +const UNIT: usize = 0x1000; +/// Largest small-resource size handled here: 60 KiB (`15 * 4 KiB < 64 KiB`). +const MAX_UNITS: u32 = 15; +/// Units per shared default heap: 16 MiB (`4096 * 4 KiB`). +const POOL_UNITS: u32 = 4096; +/// Keep an unreferenced `(va, units)` slot this long so immediate re-placements reuse it. +const IDLE: Duration = Duration::from_secs(2); +/// Wait before reusing a freed block for a different address (in-flight GPU work). +const COOL: Duration = Duration::from_secs(2); + +/// Key identifying a shared small-texture backing slot: `(title_va, size_in_4k_units)`. +type SlotKey = (usize, u32); + +/// Block location inside a device's small pools: `(pool_index, offset_in_4k_units, size_in_4k_units)`. +type Block = (u32, u32, u32); + +/// GPU fence snapshot captured when a pooled block enters `cooling`. A block cannot be recycled +/// until BOTH wall-clock `COOL` has elapsed AND every captured title-queue fence has completed, +/// preventing premature aliasing across multi-second pipeline-compile stalls. +#[derive(Default)] +struct GpuMarks(Vec<(ID3D12Fence, u64)>); + +unsafe impl Send for GpuMarks {} + +impl GpuMarks { + fn capture() -> Self { + Self(super::alloc_pool::pending_gpu_marks()) + } + + fn is_complete(&self) -> bool { + self.0.iter().all(|(f, v)| unsafe { super::real::fence_completed(f) } >= *v) + } +} + +struct Pool { + heap: H, + /// Bump pointer in 4 KiB units (`0..=POOL_UNITS`). + next_unit: u32, +} + +struct Slot { + pool: u32, + offset: u32, + users: u32, + idle_since: Option, +} + +struct SmallPools { + pools: Vec>, + /// Per-size-class (`1..=MAX_UNITS`) reusable blocks `(pool, offset)`. + free: [Vec<(u32, u32)>; (MAX_UNITS as usize) + 1], + /// Blocks given back, reusable only after `COOL` AND GPU fence completion (`G`). + cooling: VecDeque<(Block, Instant, G)>, + /// Live or idle-kept `(va, units)` → backing block. + slots: HashMap, + /// Idle slots, oldest first (`sweep_idle`). + idle: VecDeque<(SlotKey, Instant)>, + /// Live resource raw pointer → `(va, units)`. + resources: HashMap, + /// Total 4 KiB units currently held by `slots` (live + idle-kept). + used_units: usize, +} + +impl SmallPools { + fn new() -> Self { + SmallPools { + pools: Vec::new(), + free: std::array::from_fn(|_| Vec::new()), + cooling: VecDeque::new(), + slots: HashMap::new(), + idle: VecDeque::new(), + resources: HashMap::new(), + used_units: 0, + } + } + + fn sweep_idle_with(&mut self, now: Instant, mut capture_gate: impl FnMut() -> G) { + while self.idle.front().is_some_and(|&(_, since)| now.duration_since(since) >= IDLE) { + let Some((key, since)) = self.idle.pop_front() else { break }; + if self.slots.get(&key).is_some_and(|s| s.idle_since == Some(since)) { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.cooling.push_back(((s.pool, s.offset, key.1), now, capture_gate())); + } + } + } + } + + fn drain_cooling_with(&mut self, now: Instant, mut gpu_ready: impl FnMut(&G) -> bool) { + while self.cooling.front().is_some_and(|(_, at, gate)| now.duration_since(*at) >= COOL && gpu_ready(gate)) { + if let Some(((pool, offset, units), _, _)) = self.cooling.pop_front() { + self.free[units as usize].push((pool, offset)); + } + } + } + + /// Try to acquire an existing shared slot for `(va, units)` or allocate a block from existing + /// pools / free lists without creating a new D3D12 heap. + fn try_acquire_with(&mut self, key: SlotKey, now: Instant, capture_gate: impl FnMut() -> G, gpu_ready: impl FnMut(&G) -> bool) -> Option<(H, u32)> { + self.sweep_idle_with(now, capture_gate); + if let Some(s) = self.slots.get_mut(&key) { + s.users += 1; + s.idle_since = None; + return Some((self.pools[s.pool as usize].heap.clone(), s.offset)); + } + let units = key.1; + debug_assert!((1..=MAX_UNITS).contains(&units)); + self.drain_cooling_with(now, gpu_ready); + let (pool, offset) = if let Some(b) = self.free[units as usize].pop() { + b + } else if let Some((idx, p)) = self.pools.iter_mut().enumerate().rev().find(|(_, p)| p.next_unit + units <= POOL_UNITS) { + let off = p.next_unit; + p.next_unit += units; + (idx as u32, off) + } else { + return None; + }; + let heap = self.pools[pool as usize].heap.clone(); + self.slots.insert(key, Slot { pool, offset, users: 1, idle_since: None }); + self.used_units += units as usize; + Some((heap, offset)) + } + + /// Register a newly created pool heap and acquire `(va, units)`. + /// Re-checks `try_acquire` first under the lock so two threads racing to create a new 16 MiB + /// pool do not push a redundant empty heap (the extra `heap` drops cleanly if another thread + /// already added room or created the same slot). + fn add_pool_and_acquire_with(&mut self, heap: H, key: SlotKey, now: Instant, mut capture_gate: impl FnMut() -> G, mut gpu_ready: impl FnMut(&G) -> bool) -> (H, u32) { + if let Some(got) = self.try_acquire_with(key, now, &mut capture_gate, &mut gpu_ready) { + return got; + } + let pool_idx = self.pools.len() as u32; + self.pools.push(Pool { heap, next_unit: 0 }); + if let Some(got) = self.try_acquire_with(key, now, &mut capture_gate, &mut gpu_ready) { + return got; + } + // `pool_idx` has `next_unit == 0` and `units <= MAX_UNITS < POOL_UNITS`, so `try_acquire` + // above always succeeds. + unreachable!("fresh pool {pool_idx} must fit {} units", key.1); + } + + fn note_resource(&mut self, res: usize, key: SlotKey) { + self.resources.insert(res, key); + } + + /// Release one user of `key`. When `rollback` is true (creation failed before the GPU ever saw + /// the resource), the block returns directly to `free` if this was its only user. + fn release_key(&mut self, key: SlotKey, now: Instant, rollback: bool) { + let Some(s) = self.slots.get_mut(&key) else { return }; + s.users = s.users.saturating_sub(1); + if s.users == 0 { + if rollback { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.free[key.1 as usize].push((s.pool, s.offset)); + } + } else { + s.idle_since = Some(now); + self.idle.push_back((key, now)); + } + } + } + + fn forget(&mut self, res: usize, now: Instant) -> bool { + let Some(key) = self.resources.remove(&res) else { + return false; + }; + self.release_key(key, now, false); + true + } + + fn bytes(&self) -> (usize, usize) { + (self.used_units * UNIT, self.pools.len() * POOL_UNITS as usize * UNIT) + } + + #[cfg(test)] + fn flush_idle_with(&mut self, now: Instant, mut capture_gate: impl FnMut() -> G) { + while let Some((key, since)) = self.idle.pop_front() { + if self.slots.get(&key).is_some_and(|s| s.idle_since == Some(since)) { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.cooling.push_back(((s.pool, s.offset, key.1), now, capture_gate())); + } + } + } + } +} + +impl SmallPools { + #[cfg(test)] + fn try_acquire(&mut self, key: SlotKey, now: Instant) -> Option<(H, u32)> { self.try_acquire_with(key, now, || (), |_| true) } + #[cfg(test)] + fn add_pool_and_acquire(&mut self, heap: H, key: SlotKey, now: Instant) -> (H, u32) { self.add_pool_and_acquire_with(heap, key, now, || (), |_| true) } + #[cfg(test)] + fn sweep_idle(&mut self, now: Instant) { self.sweep_idle_with(now, || ()); } + #[cfg(test)] + fn flush_idle(&mut self, now: Instant) { self.flush_idle_with(now, || ()); } +} + +impl SmallPools { + fn try_acquire(&mut self, key: SlotKey, now: Instant) -> Option<(H, u32)> { self.try_acquire_with(key, now, GpuMarks::capture, GpuMarks::is_complete) } + fn add_pool_and_acquire(&mut self, heap: H, key: SlotKey, now: Instant) -> (H, u32) { self.add_pool_and_acquire_with(heap, key, now, GpuMarks::capture, GpuMarks::is_complete) } + fn sweep_idle(&mut self, now: Instant) { self.sweep_idle_with(now, GpuMarks::capture); } + #[cfg(test)] + fn flush_idle(&mut self, now: Instant) { self.flush_idle_with(now, GpuMarks::capture); } +} + +// D3D12 heaps are free-threaded. +unsafe impl Send for SmallPools {} + +static SMALL_POOLS: Mutex>> = Mutex::new(BTreeMap::new()); + +fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_VRAM_SMALL").map_or(true, |v| v.trim() != "0")) +} + +/// Whether `desc` and `console_bytes` are eligible for 4 KiB small-resource sub-allocation. +fn candidate(desc: &D3D12_RESOURCE_DESC, console_bytes: Option) -> bool { + const PAGE: u64 = 0x1_0000; + desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN + && desc.SampleDesc.Count <= 1 + && desc.Flags.0 & 0x7 == 0 + && matches!(desc.Dimension, D3D12_RESOURCE_DIMENSION_TEXTURE1D | D3D12_RESOURCE_DIMENSION_TEXTURE2D | D3D12_RESOURCE_DIMENSION_TEXTURE3D) + && console_bytes.is_some_and(|b| b > 0 && b < PAGE) +} + +/// Place a sub-64 KiB sampled texture at 4 KiB granularity in a shared default heap. +/// Returns `None` if the texture is not a small resource (the caller falls back to `vram::Pages` +/// or a committed resource). +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn place( + dev: &ID3D12Device, + this: *mut c_void, + va: usize, + desc: &D3D12_RESOURCE_DESC, + state: u32, + clear: *const c_void, + console_bytes: Option, + riid: *const windows_sys::core::GUID, + ppv: *mut *mut c_void, +) -> Option { + if !enabled() || !candidate(desc, console_bytes) { + return None; + } + let small_desc = D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..*desc }; + let info = dev.GetResourceAllocationInfo(0, &[small_desc]); + if info.SizeInBytes == u64::MAX || info.SizeInBytes == 0 || info.Alignment != UNIT as u64 || info.SizeInBytes >= 0x1_0000 { + return None; + } + let units = (info.SizeInBytes as usize).div_ceil(UNIT) as u32; + if !(1..=MAX_UNITS).contains(&units) { + return None; + } + let dev_key = dev.as_raw() as usize; + let key = (va, units); + let now = Instant::now(); + + let (heap, offset_units) = { + let mut g = SMALL_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(SmallPools::new); + pools.try_acquire(key, now) + } + .or_else(|| { + // Create a new 16 MiB default heap outside `SMALL_POOLS.lock()`. + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_UNITS as u64 * UNIT as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + // 64 KiB heap alignment is valid for 4 KiB-aligned small resources at any 4 KiB offset. + Alignment: D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut new_heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&heap_desc, &mut new_heap)) { + crate::xlog_warn!("D3D12.X: small texture pool CreateHeap: {e}"); + return None; + } + let new_heap = new_heap?; + let mut g = SMALL_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(SmallPools::new); + Some(pools.add_pool_and_acquire(new_heap, key, Instant::now())) + })?; + + let hr = super::real::dev_create_placed_resource( + this, + heap.as_raw() as usize, + offset_units as usize * UNIT, + &small_desc as *const _ as usize, + state as usize, + clear as usize, + riid, + ppv, + ); + if hr < 0 || (*ppv).is_null() { + let mut g = SMALL_POOLS.lock().unwrap(); + if let Some(pools) = g.get_mut(&dev_key) { + pools.release_key(key, Instant::now(), true); + } + return None; + } + let raw = *ppv as usize; + SMALL_POOLS.lock().unwrap().entry(dev_key).or_insert_with(SmallPools::new).note_resource(raw, key); + Some(hr) +} + +/// Release a small-pool texture on COM release. Returns `true` if `resource` belonged to a small +/// pool (so `vram::forget` can skip locking `PAGES`). +pub(super) fn forget(resource: usize) -> bool { + let mut g = SMALL_POOLS.lock().unwrap(); + let now = Instant::now(); + for pools in g.values_mut() { + if pools.forget(resource, now) { + return true; + } + } + false +} + +/// `(used_bytes, pool_bytes)` across all devices. +pub(super) fn bytes() -> (usize, usize) { + let g = SMALL_POOLS.lock().unwrap(); + g.values().fold((0, 0), |(used, pools), p| { + let (u, t) = p.bytes(); + (used + u, pools + t) + }) +} + +#[cfg(test)] +pub(super) fn bytes_for(device: usize) -> (usize, usize) { + let mut g = SMALL_POOLS.lock().unwrap(); + let Some(p) = g.get_mut(&device) else { return (0, 0) }; + p.sweep_idle(Instant::now()); + p.bytes() +} + +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + let mut g = SMALL_POOLS.lock().unwrap(); + if let Some(p) = g.get_mut(&device) { + p.flush_idle(Instant::now()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn small_pool_packs_shares_and_recycles_by_size_class() { + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let mut p: SmallPools = SmallPools::new(); + let alloc = |p: &mut SmallPools, va: usize, units: u32, res: usize, now: Instant| -> (u32, u32) { + let got = p.try_acquire((va, units), now).unwrap_or_else(|| { + let id = p.pools.len() as u32; + p.add_pool_and_acquire(id, (va, units), now) + }); + p.note_resource(res, (va, units)); + got + }; + + // Sixteen 4 KiB textures pack into 64 KiB (not 16 * 64 KiB = 1 MiB). + for i in 0..16usize { + let (h, off) = alloc(&mut p, 0x10_0000 + i * UNIT, 1, 100 + i, at(0)); + assert_eq!((h, off), (0, i as u32)); + } + assert_eq!(p.bytes(), (16 * UNIT, POOL_UNITS as usize * UNIT)); + + // Re-placing the exact same (va, units) shares the exact same (heap, offset) with zero growth. + let (h_dup, off_dup) = alloc(&mut p, 0x10_4000, 1, 200, at(10)); + assert_eq!((h_dup, off_dup), (0, 4)); + assert_eq!(p.bytes().0, 16 * UNIT); + + // Releasing one of the two aliases keeps the slot alive; releasing both makes it idle. + assert!(p.forget(200, at(20))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 1); + assert!(p.forget(104, at(30))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 0); + + // Re-acquiring within IDLE reuses the exact same slot. + let (h_re, off_re) = alloc(&mut p, 0x10_4000, 1, 201, at(1000)); + assert_eq!((h_re, off_re), (0, 4)); + assert!(p.forget(201, at(1100))); + + // After IDLE (2 s) + COOL (2 s), the 4 KiB block is recycled for a new address. + let (h_wait, off_wait) = alloc(&mut p, 0x20_0000, 1, 202, at(3200)); + assert_eq!((h_wait, off_wait), (0, 16), "still cooling at +2.1s, must not reuse yet"); + let (h_rec, off_rec) = alloc(&mut p, 0x20_1000, 1, 203, at(5300)); + assert_eq!((h_rec, off_rec), (0, 4), "block (0, 4) recycled after IDLE + COOL"); + + // Rollback on creation failure immediately returns the block to the free list. + let (h_fail, off_fail) = p.try_acquire((0x30_0000, 4), at(5400)).unwrap(); + assert_eq!((h_fail, off_fail), (0, 17)); + p.release_key((0x30_0000, 4), at(5400), true); + let (h_next, off_next) = alloc(&mut p, 0x30_4000, 4, 204, at(5400)); + assert_eq!((h_next, off_next), (0, 17)); + + // Concurrent CreateHeap race: if room already exists in pool 0, `add_pool_and_acquire` + // must reuse existing room instead of pushing a redundant empty 16 MiB pool. + let pools_before = p.pools.len(); + let (h_raced, _) = p.add_pool_and_acquire(999, (0x40_0000, 1), at(5500)); + assert_eq!(h_raced, 0); + assert_eq!(p.pools.len(), pools_before, "must not push redundant pool when room already exists"); + + // `flush_idle` clears unreferenced idle slots while keeping live (`users > 0`) slots intact. + let used_before_flush = p.bytes().0; + let _ = alloc(&mut p, 0x50_0000, 2, 205, at(5600)); + assert!(p.forget(205, at(5610))); + assert_eq!(p.bytes().0, used_before_flush + 2 * UNIT); + p.flush_idle(at(5620)); + assert_eq!(p.bytes().0, used_before_flush, "flush_idle must reclaim unreferenced slots immediately"); + } + + #[test] + fn candidate_filters_large_gpu_owned_and_msaa_textures() { + let mut d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(candidate(&d, Some(16 * 1024))); + assert!(!candidate(&d, Some(64 * 1024)), "64 KiB stays on vram::Pages"); + assert!(!candidate(&d, None)); + assert!(!candidate(&d, Some(0))); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + assert!(!candidate(&d, Some(16 * 1024))); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + d.SampleDesc.Count = 4; + assert!(!candidate(&d, Some(16 * 1024))); + d.SampleDesc.Count = 1; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + assert!(!candidate(&d, Some(16 * 1024))); + } + + /// On the GPU: 512 small 4 KiB (64x64 BC1) and 16 KiB (64x64 RGBA8) sampled textures pack at + /// 4 KiB granularity inside a single 16 MiB heap (16x and 4x smaller than 64 KiB tiles), + /// same-address placements alias their pixels on hardware, adjacent 4 KiB textures have zero + /// crosstalk, and a small sampled texture over an existing 64 KiB GPU target falls back to + /// `vram::Pages` so target aliasing is preserved. + #[test] + fn gpu_small_textures_pack_at_4k_granularity_and_preserve_pixels() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().expect("DXGI factory"); + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let mut dev: Option = None; + for (adapter, _) in crate::gpu::adapter::candidates(&factory, &sel) { + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() && dev.is_some() { + break; + } + } + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.ResourceHeapTier.0 < 2 + { + crate::gpu::recomp::runner::skip_test(&format!("resource heap tier {} < 2", opts.ResourceHeapTier.0)); + return; + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + + let desc_of = |w: u64, h: u32, fmt: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + ..Default::default() + }; + let place_sampled = |va: usize, d: &D3D12_RESOURCE_DESC, cbytes: u64| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::vram::place_pages(dev.as_raw(), va, d, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(cbytes), riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "place_pages at {va:#x} failed: {hr:x?}"); + assert!(super::super::vram::is_placed_texture(p as usize)); + ID3D12Resource::from_raw(p) + }; + + // 1. 512 x 64x64 BC1 (2 KiB on console -> 4 KiB small resource on PC): must pack into + // 2 MiB (16x smaller than 512 x 64 KiB = 32 MiB!) inside a single 16 MiB heap. + super::super::vram::flush_idle_for(dev_key); + let bc1 = desc_of(64, 64, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE); + let bc1_info = dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..bc1 }]); + if bc1_info.SizeInBytes == u64::MAX || bc1_info.SizeInBytes == 0 || bc1_info.Alignment != UNIT as u64 || bc1_info.SizeInBytes >= 0x1_0000 { + crate::gpu::recomp::runner::skip_test(&format!( + "adapter does not support 4 KiB small-resource placement for 64x64 BC1 (align={}, size={})", + bc1_info.Alignment, bc1_info.SizeInBytes + )); + return; + } + let (small0, _) = bytes_for(dev_key); + let (pages0, _) = super::super::vram::page_bytes_for(dev_key); + let bc1_base = 0x60_0000_0000usize; + let mut bc1_res = Vec::with_capacity(512); + for k in 0..512usize { + bc1_res.push(place_sampled(bc1_base + k * 0x1000, &bc1, 2048)); + } + let (small_after_bc1, small_pool_after_bc1) = bytes_for(dev_key); + let bc1_small_delta = small_after_bc1 - small0; + let bc1_total_delta = super::super::vram::page_bytes_for(dev_key).0 - pages0; + println!("512 x 64x64 BC1: +{bc1_small_delta} B in small pools (pool={small_pool_after_bc1} B), +{bc1_total_delta} B total (vs 33554432 B as 64 KiB tiles)"); + assert_eq!(bc1_small_delta, 512 * UNIT, "each 64x64 BC1 must take 4 KiB in small pool"); + assert_eq!(bc1_total_delta, 512 * UNIT, "zero 64 KiB Pages tiles allocated for 4 KiB BC1 textures"); + drop(bc1_res); + + // 2. Hardware upload + readback: two adjacent 64x64 RGBA8 (16 KiB) textures and a + // same-address alias verify zero crosstalk and exact pixel sharing on the GPU. + super::super::vram::flush_idle_for(dev_key); + let rgba = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + let rgba_info = dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..rgba }]); + if rgba_info.SizeInBytes != 16384 || rgba_info.Alignment != UNIT as u64 { + crate::gpu::recomp::runner::skip_test(&format!( + "step 2: adapter does not support 4 KiB 16 KiB placement for 64x64 RGBA8 (align={}, size={})", + rgba_info.Alignment, rgba_info.SizeInBytes + )); + return; + } + let va_a = 0x61_0000_1000usize; + let va_b = 0x61_0000_5000usize; + let a1 = place_sampled(va_a, &rgba, 16384); + let (small_after_a1, _) = bytes_for(dev_key); + let a2 = place_sampled(va_a, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_after_a1, "same-va small texture must share slot"); + let b = place_sampled(va_b, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0 - small_after_a1, 16384, "64x64 RGBA8 must take 16 KiB"); + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fill_a = vec![0x3Cu8; 64 * 64 * 4]; + let fill_b = vec![0xA5u8; 64 * 64 * 4]; + let sub = |data: Vec| crate::gpu::texture::Subresource { rows: 64, row_bytes: 64 * 4, depth: 1, data }; + // (this branch has no `texture::upload_batch`: one upload each) + for (res, fill) in [(&a2, &fill_a), (&b, &fill_b)] { + crate::gpu::texture::upload(&dev, &queue, res, &[sub(fill.clone())], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON).expect("upload failed"); + } + + let readback_tex = |r: &ID3D12Resource| -> Vec { + let rd = r.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb, + ).unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + }; + + assert_eq!(readback_tex(&a1), fill_a, "same-va alias a1 must see pixels uploaded to a2"); + assert_eq!(readback_tex(&b), fill_b, "adjacent 4 KiB texture b must not crosstalk with a"); + drop((b, a2, a1)); + + // 3. A small sampled texture at a 64 KiB-aligned va occupied by an existing GPU-owned + // render target must stay on vram::Pages (not vram_small) so it aliases the target. + if opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 { + crate::gpu::recomp::runner::skip_test(&format!("step 3: tiled resources tier {} < 2", opts.TiledResourcesTier.0)); + return; + } + super::super::vram::flush_idle_for(dev_key); + let rt_va = 0x62_0000_0000usize; + let rt_desc = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let mut rt_raw = std::ptr::null_mut(); + let hr = super::super::vram::place(dev.as_raw(), rt_va, &rt_desc, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), Some(16384), riid, &mut rt_raw); + assert!(hr.is_some_and(|h| h >= 0) && !rt_raw.is_null()); + let rt = ID3D12Resource::from_raw(rt_raw); + let small_before_alias = bytes_for(dev_key).0; + let sampled_view = place_sampled(rt_va, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_before_alias, "sampled view over live GPU target must alias vram::Pages, not vram_small"); + drop((sampled_view, rt)); + } + } + + #[test] + fn small_pool_blocks_recycle_until_gpu_fence_completes_even_after_cool() { + use std::sync::{atomic::{AtomicBool, Ordering}, Arc}; + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let gpu_done = Arc::new(AtomicBool::new(false)); + let mut p: SmallPools> = SmallPools::new(); + + let (h0, off0) = p.add_pool_and_acquire_with(1, (0x1000, 2), at(0), || gpu_done.clone(), |d| d.load(Ordering::Acquire)); + assert_eq!((h0, off0), (1, 0)); + p.note_resource(0x2001, (0x1000, 2)); + assert!(p.forget(0x2001, at(10))); + + p.sweep_idle_with(at(2_500), || gpu_done.clone()); + let (h1, off1) = p.try_acquire_with((0x2000, 2), at(12_500), || gpu_done.clone(), |d| d.load(Ordering::Acquire)).unwrap(); + assert_eq!((h1, off1), (1, 2), "must not alias cooling small-pool block before GPU fence completes"); + + gpu_done.store(true, Ordering::Release); + let (h2, off2) = p.try_acquire_with((0x3000, 2), at(12_600), || gpu_done.clone(), |d| d.load(Ordering::Acquire)).unwrap(); + assert_eq!((h2, off2), (1, 0)); + } + + #[test] + fn candidate_accepts_small_texture1d_for_4k_small_pool() { + let mut d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE1D, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(candidate(&d, Some(4096)), "small sampled TEXTURE1D must qualify for 4 KiB SmallPools"); + assert!(!candidate(&d, Some(64 * 1024)), "64 KiB TEXTURE1D stays on default placement"); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + assert!(!candidate(&d, Some(4096)), "UAV TEXTURE1D must not enter SmallPools"); + } +} diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 495991543d..01b4c51a78 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -495,6 +495,17 @@ pub mod mirrors { PAGES.write().unwrap_or_else(|e| e.into_inner()) } + /// The mapped backing CPU address for a GPU-view address `va`: `Some(Some(addr))` if mapped, + /// `Some(None)` if explicitly unmapped, `None` if `CopyPageMappingsBatchX` never touched it. + pub fn mapped_source(va: usize) -> Option> { + if MAPPED.load(Ordering::Acquire) == 0 { + return None; + } + let off = va & (PAGE - 1); + let e = *read_pages().shown.get(&(va - off))?; + Some((e.at != 0).then(|| e.at + off)) + } + /// What one `apply_batches` call did, in 64 KiB pages. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Mapped { @@ -1821,6 +1832,16 @@ pub fn physical_page_at(va: usize) -> bool { AWAY.lock().unwrap().as_ref().is_some_and(|a| a.at.contains_key(&(va & !(PHYS_PAGE - 1)))) } +/// The physical page mapped away from home at each of the `n` 64 KiB pages from `va` (None: none +/// there, or a page at its home). The console maps one page at several addresses at once; here it +/// is at one (`map_pages` moves it), so `d3d12x::vram` asks which page an address had to let +/// textures at two addresses of one page share its video memory. +pub fn physical_pages(va: usize, n: usize) -> Vec> { + let g = AWAY.lock().unwrap(); + let Some(a) = g.as_ref() else { return vec![None; n] }; + (0..n).map(|i| va.checked_add(i * PHYS_PAGE).and_then(|at| a.at.get(&at).copied())).collect() +} + /// Counts the calls that map or unmap physical pages in a GPU view (`mirrors`): what /// `physical_page_at` says there may have changed. static GPU_VIEW_MAP_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 3d5dac8089..ad4b51013c 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -964,7 +964,13 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } let windows = windows as u32; - move || if heap { windows | recomp::HEAP_WINDOWS } else { windows } + move || { + if heap { + windows | recomp::HEAP_WINDOWS | if recomp::pso::heap_flat() { recomp::HEAP_FLAT } else { 0 } + } else { + windows + } + } }; if opts.graphics_records { return graphics_worker(path, runtime_windows()); @@ -1155,7 +1161,7 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows: println!( "{written} program(s) written to {} (split wave64: {split}, {} windows{}, {failures} failure(s))", dir.display(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" } ); if written == wanted { 0 } else { @@ -1862,7 +1868,9 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R } progress.total.store(inputs.iter().map(Input::len).sum(), Ordering::Relaxed); let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; - if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } + if windows > 1 && recomp::pso::heap_windows() { + windows |= recomp::HEAP_WINDOWS | if recomp::pso::heap_flat() { recomp::HEAP_FLAT } else { 0 }; + } let workers = prepare_workers(); for input in &inputs { if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } @@ -1980,7 +1988,7 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz crate::xlog_info!("Shader preparation: compute pipelines in {workers} worker processes{}", if used_only { ", those an earlier run used" } else { "" }); let (cancelled, failed, _) = in_workers(workers, records, progress, |i| { let mut c = worker_command(&me); - c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT)).to_string()); if used_only { c.arg("--used-only"); } c.env("XCL_PRECOMPILE_SLICE", format!("{i}/{workers}")); c @@ -2114,7 +2122,7 @@ fn graphics_in_workers(inputs: &[Input], windows: u32, workers: usize, progress: progress.graphics.store(true, Ordering::Relaxed); let (cancelled, failed, summaries) = in_workers(workers, buildable.len(), progress, |i| { let mut c = worker_command(&me); - c.arg("shaders").arg(&jobs[i].0).args(["--graphics-records", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + c.arg("shaders").arg(&jobs[i].0).args(["--graphics-records", "--windows"]).arg((windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT)).to_string()); // (the title's adapter: its blobs are the ones it takes) if std::env::var_os("XCL_ADAPTER").is_none() && !progress.adapter.is_empty() { c.env("XCL_ADAPTER", &progress.adapter); } c @@ -2294,7 +2302,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); @@ -2347,6 +2355,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): // into the translation cache too, so the title does not translate it again if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { + // the title's pipeline would leave it out too (`gpu::rt_leave_out`) + if crate::gpu::rt_leave_out::left_out(&blob) { + record_done(); + continue; + } match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { @@ -2444,6 +2457,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on skipped.into_inner(), t0.elapsed().as_secs_f64() ); + if crate::gpu::rt_leave_out::enabled() { + println!("compute programs passed over (XCL_RT_LEAVE_OUT): {}", crate::gpu::rt_leave_out::left_out_count()); + } if let Some(p) = pipelines { if startup.is_none() { make_pipelines(p, pipeline_jobs.into_inner().unwrap()); From a68f609f57e1ec7626c264418f689fe863d7175f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:45:53 +0100 Subject: [PATCH 012/175] =?UTF-8?q?D3D12.X:=20light=20the=20retail=20world?= =?UTF-8?q?=20=E2=80=93=20barrier=20groups,=20depth=20twins,=20ambient?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Work in progress from the 2026-11-27/28 sessions on an RX 9070 XT (one retail title), saved as one commit. Not split into PRs, not rebased: origin/main has moved on (31 commits, the shader preparation and pipeline library work) and origin/nvidia-dev / origin/amd-dev differ. What was wrong and what changed: - The title makes every state transition through command list #146, Barrier(groups) (enhanced barriers). XCL answered it with a UAV barrier only, so no PC texture left the state it was made in and the world was dark. New hle/d3d12x/barrier_groups.rs turns the groups' texture barriers into legacy transitions through resource_barrier_x (depth twins and format aliases see them); `legal` drops what the PC would refuse (an illegal one fails Close with E_INVALIDARG and the title stops). XCL_BARRIER_GROUPS=0 off, XCL_BARRIER_LOG=1 logs kinds. - Tiled lighting tests depth EQUAL against a class buffer (console D16S8, PC R24G8) that only compute writes through a UAV. Depth UAV twins are on by default (depth_uav DEFAULT_ON), and the stencil plane's twin is now copied to and from the plane through a buffer (StencilCopy, list_x::stencil_copies_on). - ambient.rs: the stand-in no longer keeps the title's own probe resolve while XCL_RT_LEAVE_OUT leaves out the programs that feed it (that kept garbage: a flat green wash and bright bands); XCL_AMBIENT_KEEP overrides. A frame-based estimate from CS_CacheScreenSpaceRadiance (64x36 cells, slow mean; credit in THIRD_PARTY.md) raises the fill: XCL_AMBIENT_FRAME (default 0.8, 0 off). - sRGB textures with unordered access made typeless (opt-in, XCL_SRGB_UAV=1); XCL_DUMP_TARGETS also writes each depth twin as a picture of its raw bytes; XCL_RAM_MB=auto (ram_budget.rs), XCL_MEM_MAP=1 (mem_map.rs), lazy-level texture uploads. Measured (guarded runs, 200 s, intro to the first world scenes): exit 0x0, no device removal, no crash, no TDR; the world is lit; 5-7 presents per 2 s in the world; peak commit about 21 GB. Still wrong: round hard-edged patches where one lamp lights everything inside a screen circle (made inside the class-0 tiled lighting shaders; the class buffer itself is right), characters lit only inside such patches, dark scenes, small dark triangles on diagonals. Most likely cause: the title ray-traces lamp shadows and bounce light, and CS_RaytracingResolve / CS_ScreenProbes_ActivateRays are left out here (XCL_RT_LEAVE_OUT); with them allowed, world entry compiles push title commit from about 10 to 21 GB and a 32 GB PC runs out (the shader preparation work on origin/main targets this). Tests: cargo test --release -p xcl --lib -- --test-threads=4 ambient barrier_groups depth_uav format_alias: 42 passed, 0 failed. Whole suite not run. Written with Claude Code (Claude Mythos 5.2, then Claude Opus 5.5). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/eh.rs | 121 +++- crates/xcl/src/gpu/recomp/dxc.rs | 1 + crates/xcl/src/gpu/uma.rs | 18 + crates/xcl/src/heap_count.rs | 405 +++++++++++ crates/xcl/src/hle/d3d12x/alloc_pool.rs | 94 ++- crates/xcl/src/hle/d3d12x/ambient.rs | 264 ++++++- crates/xcl/src/hle/d3d12x/barrier_groups.rs | 477 +++++++++++++ crates/xcl/src/hle/d3d12x/bind.rs | 122 +++- crates/xcl/src/hle/d3d12x/clamp.rs | 3 + crates/xcl/src/hle/d3d12x/console_heap.rs | 97 ++- crates/xcl/src/hle/d3d12x/console_list.rs | 56 ++ crates/xcl/src/hle/d3d12x/cpu_writes.rs | 5 +- crates/xcl/src/hle/d3d12x/depth_uav.rs | 119 +++- crates/xcl/src/hle/d3d12x/device_x.rs | 31 +- crates/xcl/src/hle/d3d12x/gpu_awake.rs | 1 + crates/xcl/src/hle/d3d12x/indirect_guard.rs | 4 + crates/xcl/src/hle/d3d12x/list_x.rs | 140 +++- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/present.rs | 93 ++- crates/xcl/src/hle/d3d12x/real.rs | 356 ++++++++-- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 48 +- crates/xcl/src/hle/d3d12x/scatter.rs | 3 + crates/xcl/src/hle/d3d12x/sparse.rs | 4 + crates/xcl/src/hle/d3d12x/texture_upload.rs | 90 ++- crates/xcl/src/hle/d3d12x/title_textures.rs | 389 +++++++++- crates/xcl/src/hle/d3d12x/vram.rs | 8 + crates/xcl/src/hle/dstorage.rs | 2 +- crates/xcl/src/hle/kernelx.rs | 144 +++- crates/xcl/src/hle/kernelx/alias.rs | 672 ++++++++++++++++++ crates/xcl/src/hle/kernelx/guards.rs | 480 +++++++++++++ crates/xcl/src/hle/kernelx/lazy.rs | 20 +- crates/xcl/src/hle/kernelx/sections.rs | 324 +++++++++ crates/xcl/src/host.rs | 13 + crates/xcl/src/lib.rs | 7 + crates/xcl/src/mem_map.rs | 401 +++++++++++ crates/xcl/src/ram_budget.rs | 174 +++++ crates/xcl/src/vfs_hooks.rs | 7 +- 37 files changed, 5054 insertions(+), 140 deletions(-) create mode 100644 crates/xcl/src/heap_count.rs create mode 100644 crates/xcl/src/hle/d3d12x/barrier_groups.rs create mode 100644 crates/xcl/src/hle/kernelx/alias.rs create mode 100644 crates/xcl/src/hle/kernelx/guards.rs create mode 100644 crates/xcl/src/hle/kernelx/sections.rs create mode 100644 crates/xcl/src/mem_map.rs create mode 100644 crates/xcl/src/ram_budget.rs diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index e02ae7528e..ec8c1a7360 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -113,7 +113,8 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i if !ctx.is_null() { let c = &*ctx; let mut seen: Vec = Vec::new(); - for (n, v) in [("rax", c.Rax), ("rbx", c.Rbx), ("rcx", c.Rcx), ("rdx", c.Rdx), ("rsi", c.Rsi), ("rdi", c.Rdi), ("rbp", c.Rbp), ("r8", c.R8), ("r9", c.R9), ("r10", c.R10), ("r11", c.R11), ("r12", c.R12), ("r13", c.R13), ("r14", c.R14), ("r15", c.R15)] { + let fault = if rec.ExceptionCode as u32 == 0xC000_0005 && rec.NumberParameters >= 2 { rec.ExceptionInformation[1] as u64 } else { 0 }; + for (n, v) in [("the fault address", fault), ("rax", c.Rax), ("rbx", c.Rbx), ("rcx", c.Rcx), ("rdx", c.Rdx), ("rsi", c.Rsi), ("rdi", c.Rdi), ("rbp", c.Rbp), ("r8", c.R8), ("r9", c.R9), ("r10", c.R10), ("r11", c.R11), ("r12", c.R12), ("r13", c.R13), ("r14", c.R14), ("r15", c.R15)] { let p = v as usize; if p < 0x1_0000 || seen.contains(&(p & !0xFFFF)) { continue; @@ -123,16 +124,55 @@ unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i if !d.is_empty() { crate::xlog_error!("page of {n}={p:#x}: {d}"); } + let g = crate::hle::kernelx::given_up::describe(p); + if !g.is_empty() { + crate::xlog_error!("{n}={p:#x}: {g}"); + } + // which memory it is, and what it holds there + if crate::gpu::shader::readable(p & !7, 64) { + let kind = match crate::gpu::uma::get() { + Some(u) if u.is_sparse(p) => "a sparse window", + Some(u) if u.is_view(p) => "a GPU view", + Some(u) if u.is_committed(p) => "the coherent window", + Some(u) if u.contains(p) => "unified memory", + _ => "outside unified memory", + }; + let words: Vec = (0..8).map(|i| format!("{:016x}", ((p & !7) as *const u64).add(i).read_unaligned())).collect(); + crate::xlog_error!("memory at {n}={p:#x} ({kind}): {}", words.join(" ")); + if kind != "outside unified memory" { + crate::xlog_error!("buffer views compute dispatches were given over {n}={p:#x}: {}", crate::hle::d3d12x::real::dispatch_views_over(p)); + // the neighbourhood, as dwords: what was written over an object shows its + // extent and stride (single words, records, a block) + let from = (p & !15).saturating_sub(192); + if crate::gpu::shader::readable(from, 448) { + for row in 0..7 { + let at = from + 64 * row; + let w: Vec = (0..16).map(|i| format!("{:08x}", ((at + 4 * i) as *const u32).read_unaligned())).collect(); + crate::xlog_error!(" {at:#x}: {}", w.join(" ")); + } + } + } + } } crate::xlog_error!("page events so far: {}", crate::hle::kernelx::pagelog::counts()); } crate::report::write_final(Some(msg)); crate::log::flush(); } - match TITLE_FILTER.load(Ordering::Acquire) { + let verdict = match TITLE_FILTER.load(Ordering::Acquire) { 0 => 0, // EXCEPTION_CONTINUE_SEARCH f => std::mem::transmute:: i32>(f)(info), + }; + // Continuing the search hands the process to Windows Error Reporting, which snapshots it for + // its dump: with a title's tens of GB committed, that doubled the system's commit charge in + // one second (measured: +24 GB). The report is written, so the process ends here with the + // exception's code (`XCL_WER=1`: Windows gets it as before). + if verdict == 0 && std::env::var_os("XCL_WER").is_none() { + let code = if info.is_null() || (*info).ExceptionRecord.is_null() { 0xC000_0005u32 } else { (*(*info).ExceptionRecord).ExceptionCode as u32 }; + crate::log::flush(); + windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), code); } + verdict } static ORIG_NT_TERMINATE: AtomicUsize = AtomicUsize::new(0); @@ -436,6 +476,76 @@ unsafe fn code_bytes_at(rip: usize, most: usize) -> usize { (in_page + 1..=most).rev().find(|&n| crate::gpu::shader::readable(rip, n)).unwrap_or(in_page) } +thread_local! { + /// the address this thread's last `monitorx` armed (rAX) + static MONITORED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// `mwaitx` (ECX bit 1: EBX is a timeout in TSC ticks): waits here, without leaving the handler, +/// until the monitored quadword changes or about a quarter of a millisecond has passed (a late or +/// spurious wake-up is allowed: the title's loop checks and waits again). Returning at +/// once, as before, made a title's wait on a GPU fence two exceptions per turn of its loop – a +/// retail title's world: 61 000 turns a second on the thread that waits for the GPU. +unsafe fn mwaitx_wait(ecx: u32, ebx: u32) { + use std::arch::x86_64::{_mm_pause, _rdtsc}; + const MOST_TICKS: u64 = 800_000; + let at = MONITORED.with(|m| m.get()); + if at == 0 || !at.is_multiple_of(8) || !crate::gpu::shader::readable(at, 8) { + std::hint::spin_loop(); + return; + } + let cell = &*(at as *const std::sync::atomic::AtomicU64); + let seen = cell.load(Ordering::Relaxed); + // (the title's own timeout is 1000 ticks, a pause: it is not kept, the quadword is polled) + let _ = (ecx, ebx); + let end = _rdtsc().saturating_add(MOST_TICKS); + while cell.load(Ordering::Relaxed) == seen && _rdtsc() < end { + _mm_pause(); + } +} + +/// Emulated console-only instructions by kind, logged every 2 s while there are any: each one is +/// an exception (kernel and back), so a title that runs them in a loop pays for it in frame time. +fn count_emulated(what: &crate::insn::ConsoleOnly, rip: usize) { + use crate::insn::ConsoleOnly as C; + const NAMES: [&str; 8] = ["clwb", "clzero", "rdpru", "monitorx", "mwaitx", "rdpid", "extrq", "insertq"]; + static N: [AtomicUsize; 8] = [const { AtomicUsize::new(0) }; 8]; + static LAST_MS: AtomicUsize = AtomicUsize::new(0); + static SITES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let k = match what { + C::Clwb => 0, + C::Clzero | C::ClzeroLoop { .. } => 1, + C::Rdpru => 2, + C::Monitorx => 3, + C::Mwaitx => 4, + C::Rdpid(_) => 5, + C::Extrq { .. } => 6, + C::Insertq { .. } => 7, + C::Ud2 => return, + }; + N[k].fetch_add(1, Ordering::Relaxed); + if let Ok(mut g) = SITES.try_lock() { + match g.iter().position(|e| e.0 == rip) { + Some(i) => g[i].1 += 1, + None if g.len() < 4096 => g.push((rip, 1)), + None => {} + } + } + let now = (crate::log::uptime() * 1000.0) as usize; + let last = LAST_MS.load(Ordering::Relaxed); + if now >= last + 2000 && LAST_MS.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_ok() { + let counts: Vec = (0..8).map(|i| (NAMES[i], N[i].swap(0, Ordering::Relaxed))).filter(|c| c.1 > 0).map(|(n, c)| format!("{c} {n}")).collect(); + let top = SITES.lock().map_or(String::new(), |mut g| { + g.sort_by_key(|e| std::cmp::Reverse(e.1)); + let t = g.iter().take(6).map(|&(a, c)| format!("{} x{c}", modules::describe_address(a))).collect::>().join(", "); + let sites = g.len(); + g.clear(); + format!("{sites} places, most: {t}") + }); + crate::xlog_info!("emulated console CPU instructions ({} ms): {}; {top}", now - last, counts.join(", ")); + } +} + /// A title's STATUS_ILLEGAL_INSTRUCTION: an instruction the console's Zen 2 has and this CPU /// lacks (`insn`) is emulated and stepped over (EXCEPTION_CONTINUE_EXECUTION); anything else is /// logged with its code bytes and goes on to the title's handlers. @@ -462,6 +572,7 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics } } } + count_emulated(&what, rip); let mut step = len; match what { ConsoleOnly::Ud2 => return 0, @@ -474,10 +585,8 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; } } - ConsoleOnly::Monitorx => {} - ConsoleOnly::Mwaitx => { - std::hint::spin_loop(); - } + ConsoleOnly::Monitorx => MONITORED.with(|m| m.set(ctx.Rax as usize)), + ConsoleOnly::Mwaitx => mwaitx_wait(ctx.Rcx as u32, ctx.Rbx as u32), ConsoleOnly::Clzero => { // with an address-size prefix (0x67, among the prefixes before 0F 01 FC) the line // is at EAX, zero-extended – as a Zen 5 runs it diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index ab9486a98e..d29d1a50b5 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -386,6 +386,7 @@ impl DxcMalloc { if heap.is_null() { Err(format!("HeapCreate for DXC: {}", std::io::Error::last_os_error())) } else { + crate::heap_count::note_heap("DXC", heap as usize); Ok(Self { heap }) } } diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index b86d4a6ea8..1c07197c32 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -894,7 +894,22 @@ impl Uma { // a block of XCL's pool goes back to the pool let mut g = self.pool.lock().unwrap(); if p >= g.0 && p < g.1 { + // (a block freed twice would be handed to two owners at once, each writing over + // the other's records) + if g.2.contains(&p) { + drop(g); + static TWICE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = TWICE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_error!("UMA: pool block {p:#x} freed while it is free ({k} so far) - left out"); + } + return true; + } g.2.push(p); + drop(g); + for grain in 0..ARENA_BLOCK / GRAIN { + crate::hle::kernelx::pagelog::note("XCL arena block freed", p + grain * GRAIN, 0, ARENA_BLOCK); + } return true; } } @@ -972,6 +987,9 @@ impl Arena { None => u.alloc(ARENA_BLOCK, GRAIN)? as usize, }; blocks.push(p); + for grain in 0..ARENA_BLOCK / GRAIN { + crate::hle::kernelx::pagelog::note("XCL arena block taken", p + grain * GRAIN, 0, ARENA_BLOCK); + } self.at = p + n; self.end = p + ARENA_BLOCK; Some(p as *mut u8) diff --git a/crates/xcl/src/heap_count.rs b/crates/xcl/src/heap_count.rs new file mode 100644 index 0000000000..5959c93080 --- /dev/null +++ b/crates/xcl/src/heap_count.rs @@ -0,0 +1,405 @@ +//! XCL's own heap, counted (`XCL_HEAP_COUNT=1`, with `XCL_ACTIVITY`): how much of the process's +//! commit is memory XCL's own code allocated, by the size of the allocations, and from where: +//! every allocation of 64 KiB or more with its call stack, and one smaller allocation in +//! `SAMPLE` (chosen by its address) standing for `SAMPLE` times its bytes. +//! +//! The process holds the title's memory, the driver's, the shader compiler's and XCL's own in one +//! number (`memory: N MB committed by the process`). The title's is found by its addresses; +//! this tells XCL's apart from the rest. Every allocation of XCL's Rust code goes through +//! `Counting` (the system allocator with counters around it). Off, it costs one relaxed load an +//! allocation. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; + +/// The allocator of the crate: the system's, counted while `on()`. +pub struct Counting; + +/// 0: not asked yet, 1: off, 2: on +static STATE: AtomicU8 = AtomicU8::new(0); + +/// upper bounds of the size classes, the last one open +const CLASSES: [usize; 7] = [256, 4 << 10, 64 << 10, 1 << 20, 16 << 20, 256 << 20, usize::MAX]; +const CLASS_NAMES: [&str; 7] = ["<256 B", "<4 KiB", "<64 KiB", "<1 MiB", "<16 MiB", "<256 MiB", "larger"]; +/// live bytes and live allocations of each class +static BYTES: [AtomicUsize; 7] = [const { AtomicUsize::new(0) }; 7]; +static COUNT: [AtomicUsize; 7] = [const { AtomicUsize::new(0) }; 7]; + +/// allocations of this many bytes or more are kept with where they were made (`SITES`) +const LARGE: usize = 64 << 10; +/// one smaller allocation in this many is kept with where it was made (by its address: the +/// free of an allocation not kept costs nothing) +const SAMPLE: usize = 256; +/// frames kept of a kept allocation's call stack (the allocator's own left out) +const FRAMES: usize = 12; +const SLOTS: usize = 1 << 16; + +#[derive(Clone, Copy)] +struct Site { + /// the allocation (0: free slot, 1: a slot freed, passed over in a search) + ptr: usize, + size: usize, + frames: [usize; FRAMES], +} + +/// The large allocations alive, an open-addressed table by address (no allocation of its own: +/// it is used inside the allocator). +struct Sites(std::cell::UnsafeCell<[Site; SLOTS]>); +// SAFETY: only touched under `LOCK` +unsafe impl Sync for Sites {} +static SITES: Sites = Sites(std::cell::UnsafeCell::new([Site { ptr: 0, size: 0, frames: [0; FRAMES] }; SLOTS])); +static LOCK: AtomicBool = AtomicBool::new(false); +/// large allocations the full table had no slot for +static UNTRACKED: AtomicUsize = AtomicUsize::new(0); + +fn class(size: usize) -> usize { + CLASSES.iter().position(|&c| size < c).unwrap_or(CLASSES.len() - 1) +} + +/// Whether an allocation of `size` bytes at `ptr` is kept with its call stack. +fn kept(ptr: usize, size: usize) -> bool { + size >= LARGE || ((ptr >> 4).wrapping_mul(0xD6E8_FEB8_6659_FD93) >> (usize::BITS - SAMPLE.trailing_zeros())) == 0 +} + +/// The bytes a kept allocation stands for. +fn weight(size: usize) -> usize { + if size >= LARGE { size } else { size * SAMPLE } +} + +fn slot_of(ptr: usize) -> usize { + (ptr >> 4).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> (usize::BITS - SLOTS.trailing_zeros()) +} + +fn locked(f: impl FnOnce(&mut [Site; SLOTS]) -> R) -> R { + while LOCK.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() { + std::hint::spin_loop(); + } + // SAFETY: `LOCK` is held + let r = f(unsafe { &mut *SITES.0.get() }); + LOCK.store(false, Ordering::Release); + r +} + +/// Whether allocations are counted (`XCL_HEAP_COUNT=1`). The variable is read without the +/// standard library's `env` (it allocates: this runs inside the allocator). +fn on() -> bool { + match STATE.load(Ordering::Relaxed) { + 2 => true, + 1 => false, + _ => { + let mut buf = [0u16; 4]; + const NAME: [u16; 15] = { + let s = b"XCL_HEAP_COUNT\0"; + let mut w = [0u16; 15]; + let mut i = 0; + while i < 15 { + w[i] = s[i] as u16; + i += 1; + } + w + }; + let n = unsafe { windows_sys::Win32::System::Environment::GetEnvironmentVariableW(NAME.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) }; + let yes = n == 1 && buf[0] == b'1' as u16; + STATE.store(if yes { 2 } else { 1 }, Ordering::Relaxed); + yes + } + } +} + +fn added(ptr: *mut u8, size: usize) { + if ptr.is_null() { + return; + } + let c = class(size); + BYTES[c].fetch_add(size, Ordering::Relaxed); + COUNT[c].fetch_add(1, Ordering::Relaxed); + if kept(ptr as usize, size) { + let mut frames = [0usize; FRAMES]; + // (skips this function and the allocator's method) + unsafe { + windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace(2, FRAMES as u32, frames.as_mut_ptr() as *mut *mut std::ffi::c_void, std::ptr::null_mut()); + } + let kept = locked(|t| { + let first = slot_of(ptr as usize); + for k in 0..64 { + let s = &mut t[(first + k) & (SLOTS - 1)]; + if s.ptr <= 1 { + *s = Site { ptr: ptr as usize, size, frames }; + return true; + } + } + false + }); + if !kept { + UNTRACKED.fetch_add(1, Ordering::Relaxed); + } + } +} + +fn removed(ptr: *mut u8, size: usize) { + let c = class(size); + BYTES[c].fetch_sub(size, Ordering::Relaxed); + COUNT[c].fetch_sub(1, Ordering::Relaxed); + if kept(ptr as usize, size) { + locked(|t| { + let first = slot_of(ptr as usize); + for k in 0..64 { + let s = &mut t[(first + k) & (SLOTS - 1)]; + if s.ptr == ptr as usize { + s.ptr = 1; + return; + } + if s.ptr == 0 { + return; + } + } + }); + } +} + +// SAFETY: every call goes to the system allocator unchanged; the counters only watch +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + let p = System.alloc(l); + if on() { + added(p, l.size()); + } + p + } + + unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 { + let p = System.alloc_zeroed(l); + if on() { + added(p, l.size()); + } + p + } + + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + if on() { + removed(p, l.size()); + } + System.dealloc(p, l) + } + + unsafe fn realloc(&self, p: *mut u8, l: Layout, new_size: usize) -> *mut u8 { + let q = System.realloc(p, l, new_size); + if on() && !q.is_null() { + removed(p, l.size()); + added(q, new_size); + } + q + } +} + +/// The title's allocations XCL serves from the process heap (`kernelx::XMemAllocDefault`): +/// live bytes and live allocations. They share that heap with XCL's own. +static TITLE: [AtomicUsize; 2] = [const { AtomicUsize::new(0) }; 2]; + +/// Whether the counters run (`XCL_HEAP_COUNT=1`): callers that count for others ask first. +pub fn counting() -> bool { + on() +} + +/// The title got `bytes` from the process heap. +pub fn title_added(bytes: usize) { + TITLE[0].fetch_add(bytes, Ordering::Relaxed); + TITLE[1].fetch_add(1, Ordering::Relaxed); +} + +/// The title gave `bytes` of the process heap back. +pub fn title_removed(bytes: usize) { + TITLE[0].fetch_sub(bytes, Ordering::Relaxed); + TITLE[1].fetch_sub(1, Ordering::Relaxed); +} + +/// What the process heap holds, by a walk of it under its lock: (bytes allocated, bytes +/// committed, milliseconds the walk took). XCL's own allocations, the title's from +/// `XMemAllocDefault` and those of the driver, Direct3D and the C runtime are all in it. +fn process_heap() -> Option<(usize, usize, u128)> { + use windows_sys::Win32::System::Memory::{GetProcessHeap, HeapSummary, HEAP_SUMMARY}; + let t = std::time::Instant::now(); + let mut s: HEAP_SUMMARY = unsafe { std::mem::zeroed() }; + s.cb = std::mem::size_of::() as u32; + (unsafe { HeapSummary(GetProcessHeap(), 0, &mut s) } != 0).then(|| (s.cbAllocated, s.cbCommitted, t.elapsed().as_millis())) +} + +/// Windows heaps XCL made for someone else's allocations (the shader compiler's, one a worker): +/// (whose, handle). They are not in the counters above, and a heap keeps memory it once used. +static OTHER_HEAPS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// A serialized Windows heap `whose` allocations go to (`lines` reports what it holds). +pub fn note_heap(whose: &'static str, heap: usize) { + OTHER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()).push((whose, heap)); +} + +/// (heaps, bytes allocated in them, bytes they have committed) of the noted heaps of `whose`. +fn other_heaps(whose: &str) -> (usize, usize, usize) { + use windows_sys::Win32::System::Memory::{HeapSummary, HEAP_SUMMARY}; + let heaps: Vec = OTHER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|h| h.0 == whose).map(|h| h.1).collect(); + let (mut allocated, mut committed) = (0, 0); + for &h in &heaps { + let mut s: HEAP_SUMMARY = unsafe { std::mem::zeroed() }; + s.cb = std::mem::size_of::() as u32; + if unsafe { HeapSummary(h as _, 0, &mut s) } != 0 { + allocated += s.cbAllocated; + committed += s.cbCommitted; + } + } + (heaps.len(), allocated, committed) +} + +/// (live bytes, live allocations) of XCL's own heap; zeros while not counted. +pub fn live() -> (usize, usize) { + (BYTES.iter().map(|b| b.load(Ordering::Relaxed)).sum(), COUNT.iter().map(|c| c.load(Ordering::Relaxed)).sum()) +} + +/// The kept allocations alive, copied into `alive` (made with room for the whole table: no +/// allocation under the lock), but for `alive`'s own buffer, a large allocation of the report's +/// and not XCL's memory being reported. +fn snapshot_into(alive: &mut Vec) { + let own = alive.as_ptr() as usize; + locked(|t| { + for s in t.iter().filter(|s| s.ptr > 1 && s.ptr != own) { + alive.push(*s); + } + }); +} + +/// The lines of the activity log: the heap by size class, then the places that hold the most +/// in large allocations, as offsets in xcl.exe (symbolized afterwards from its .pdb). None: off. +pub fn lines(top: usize) -> Option> { + if !on() { + return None; + } + let (bytes, count) = live(); + let classes: Vec = (0..CLASSES.len()) + .filter(|&c| COUNT[c].load(Ordering::Relaxed) != 0) + .map(|c| format!("{} {} MB in {}", CLASS_NAMES[c], BYTES[c].load(Ordering::Relaxed) >> 20, COUNT[c].load(Ordering::Relaxed))) + .collect(); + let mut out = vec![format!("XCL's own heap: {} MB in {} allocations; by size: {}", bytes >> 20, count, classes.join(", "))]; + let (heaps, allocated, committed) = other_heaps("DXC"); + if heaps != 0 { + out.push(format!("the shader compiler's heaps: {heaps} heaps, {} MB in use, {} MB committed", allocated >> 20, committed >> 20)); + } + // (the walk holds the heap's lock: every third time, a minute apart) + static WALKS: AtomicUsize = AtomicUsize::new(0); + let title = (TITLE[0].load(Ordering::Relaxed), TITLE[1].load(Ordering::Relaxed)); + match (WALKS.fetch_add(1, Ordering::Relaxed) % 3 == 0).then(process_heap).flatten() { + Some((allocated, committed, ms)) => out.push(format!( + "the process heap: {} MB in use, {} MB committed (walked in {ms} ms); of it XCL's own {} MB, the title's {} MB in {} (XMemAllocDefault), others' (driver, Direct3D, C runtime) {} MB", + allocated >> 20, + committed >> 20, + bytes >> 20, + title.0 >> 20, + title.1, + allocated.saturating_sub(bytes + title.0) >> 20 + )), + None => out.push(format!("the title's allocations from the process heap (XMemAllocDefault): {} MB in {}", title.0 >> 20, title.1)), + } + // (copied out under the lock, added up after it: adding up allocates) + let mut alive: Vec = Vec::with_capacity(SLOTS); + snapshot_into(&mut alive); + // (xcl.exe's own base: in host mode the process's executable is the title's) + let base = { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT}; + let mut m = std::ptr::null_mut(); + let flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; + unsafe { GetModuleHandleExW(flags, lines as *const u16, &mut m) }; + m as usize + }; + for (large, what) in [(true, "large"), (false, "small")] { + let mut by_site: std::collections::HashMap<[usize; FRAMES], (usize, usize)> = std::collections::HashMap::new(); + for s in alive.iter().filter(|s| (s.size >= LARGE) == large) { + let e = by_site.entry(s.frames).or_default(); + e.0 += weight(s.size); + e.1 += 1; + } + let mut sites: Vec<_> = by_site.into_iter().collect(); + sites.sort_by_key(|s| std::cmp::Reverse(s.1 .0)); + let total: usize = sites.iter().map(|s| s.1 .0).sum(); + out.push(if large { + format!( + "XCL's own heap, large allocations: {} MB in {} from {} places ({} not kept: table full); xcl.exe at {base:#x}", + total >> 20, + alive.iter().filter(|s| s.size >= LARGE).count(), + sites.len(), + UNTRACKED.load(Ordering::Relaxed) + ) + } else { + format!("XCL's own heap, small allocations: about {} MB, from 1 in {SAMPLE} of them kept ({} from {} places)", total >> 20, sites.iter().map(|s| s.1 .1).sum::(), sites.len()) + }); + for (frames, (bytes, n)) in sites.into_iter().take(top) { + let stack: Vec = frames.iter().take_while(|&&f| f != 0).map(|&f| if f >= base && f - base < (64 << 20) { format!("+{:#x}", f - base) } else { format!("{f:#x}") }).collect(); + if large { + out.push(format!("XCL's own heap, large: {} MB in {} from {}", bytes >> 20, n, stack.join(" "))); + } else { + out.push(format!("XCL's own heap, small: about {} MB ({} kept) from {}", bytes >> 20, n, stack.join(" "))); + } + } + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn about_one_small_allocation_in_sample_is_kept() { + let n = (0..1usize << 20).filter(|&k| kept(0x2_0000_0000 + 16 * k, 48)).count(); + let want = (1usize << 20) / SAMPLE; + assert!(n > want / 2 && n < want * 2, "{n} of {} kept, want about {want}", 1 << 20); + assert!(kept(0x1234_0000, LARGE), "every large one"); + assert_eq!(weight(LARGE), LARGE); + assert_eq!(weight(100), 100 * SAMPLE); + } + + #[test] + fn the_reports_own_buffer_is_not_reported() { + let mut alive: Vec = Vec::with_capacity(SLOTS); + // (as the switch on would keep it: a large allocation of the report itself) + added(alive.as_mut_ptr() as *mut u8, SLOTS * std::mem::size_of::()); + let other = 0x4321_0000usize; + added(other as *mut u8, 2 << 20); + snapshot_into(&mut alive); + assert!(alive.iter().all(|s| s.ptr != alive.as_ptr() as usize), "the report's buffer is left out"); + assert!(alive.iter().any(|s| s.ptr == other), "an allocation of XCL's is kept"); + removed(other as *mut u8, 2 << 20); + removed(alive.as_mut_ptr() as *mut u8, SLOTS * std::mem::size_of::()); + } + + #[test] + fn sizes_fall_in_their_class() { + assert_eq!(class(0), 0); + assert_eq!(class(255), 0); + assert_eq!(class(256), 1); + assert_eq!(class((64 << 10) - 1), 2); + assert_eq!(class(64 << 10), 3); + assert_eq!(class(1 << 30), 6); + assert_eq!(class(usize::MAX), 6); + } + + #[test] + fn a_large_allocation_is_kept_with_its_place_until_it_is_freed() { + // (straight at the table: the switch is the process's, read once) + let p = 0x1234_5670usize as *mut u8; + added(p, 3 << 20); + let found = locked(|t| t.iter().find(|s| s.ptr == p as usize).copied()); + let site = found.expect("kept"); + assert_eq!(site.size, 3 << 20); + assert_ne!(site.frames[0], 0, "its call stack was taken"); + removed(p, 3 << 20); + assert!(locked(|t| t.iter().all(|s| s.ptr != p as usize))); + // a small one is kept only when its address is one of the sampled ones + let mut picked = (0x1000_0000usize..).step_by(16).filter(|&a| kept(a, 100)); + let (q, r) = (picked.next().unwrap(), (0x1000_0000usize..).step_by(16).find(|&a| !kept(a, 100)).unwrap()); + added(q as *mut u8, 100); + added(r as *mut u8, 100); + assert!(locked(|t| t.iter().any(|s| s.ptr == q)), "a sampled small allocation is kept"); + assert!(locked(|t| t.iter().all(|s| s.ptr != r)), "another is only counted"); + removed(q as *mut u8, 100); + removed(r as *mut u8, 100); + assert!(locked(|t| t.iter().all(|s| s.ptr != q))); + } +} diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index cc75f07a5c..5ade3d8775 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -430,14 +430,12 @@ pub unsafe fn release_when_done(alloc: usize, cleanup: Box) } /// Run deferred `release_when_done` cleanups whose GPU fences have all completed (polled once -/// per `PresentX`, outside `STATE` so cleanups and COM drops cannot re-enter `STATE`). +/// per `PresentX`, outside `STATE` so cleanups and COM drops cannot re-enter `STATE`), and drop +/// excess idle put-aside PC command allocators so bursts do not keep GBs of non-local memory. pub unsafe fn release_finished() { - let done: Vec = { + let (done, excess_aside): (Vec, Vec) = { let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; - if s.pending_releases.is_empty() { - return; - } let mut ready = Vec::new(); let mut i = 0; while i < s.pending_releases.len() { @@ -447,7 +445,8 @@ pub unsafe fn release_finished() { i += 1; } } - ready + let excess = take_excess_aside(s); + (ready, excess) }; for item in done { (item.cleanup)(); @@ -457,6 +456,53 @@ pub unsafe fn release_finished() { drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); } } + for b in excess_aside { + super::real::dispatch_chain::allocator_reset(b); + super::console_list::allocator_reset(b as *mut c_void); + drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); + } +} + +/// Reclaim all idle XCL-created PC allocators sitting in `s.aside` (never dropping the title's +/// own `alloc`), and whenever `s.cur[alloc]` is an idle XCL-created allocator while `alloc` itself +/// is idle in `s.aside`, switch `alloc` back to itself and drop the idle XCL-created backing too. +/// This prevents titles with hundreds of command allocators from keeping gigabytes of non-local +/// driver command-buffer memory idle in system RAM. +unsafe fn take_excess_aside(s: &mut State) -> Vec { + let mut drop_list = Vec::new(); + let mut switch_back = Vec::new(); + for (&alloc, list) in s.aside.iter_mut() { + let mut i = 0; + while i < list.len() { + let b = list[i]; + if b != alloc && s.backings.get(&b).is_none_or(|x| x.free()) { + list.swap_remove(i); + s.backings.remove(&b); + drop_list.push(b); + } else { + i += 1; + } + } + // If `cur` is an idle XCL-made allocator and the title's own `alloc` is also idle in + // `aside`, restore `alloc` as `cur` and reclaim the idle XCL-made allocator. + if let Some(&cur) = s.cur.get(&alloc) { + if cur != alloc + && s.backings.get(&cur).is_none_or(|x| x.free()) + && s.backings.get(&alloc).is_none_or(|x| x.free()) + { + if let Some(pos) = list.iter().position(|&b| b == alloc) { + list.swap_remove(pos); + switch_back.push((alloc, cur)); + } + } + } + } + for (alloc, cur) in switch_back { + s.cur.remove(&alloc); + s.backings.remove(&cur); + drop_list.push(cur); + } + drop_list } /// The title's allocator `alloc` is gone (its last Release): nothing of it stays here – a later @@ -589,11 +635,23 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu s.cur.insert(a, next); s.swaps += 1; if s.swaps.is_power_of_two() { - let aside: usize = s.aside.values().map(|v| v.len()).sum(); + let (mut aside, mut free, mut pinned) = (0usize, 0usize, 0usize); + for v in s.aside.values() { + for b in v { + aside += 1; + match s.backings.get(b) { + None => free += 1, + Some(x) if !x.users.is_empty() => pinned += 1, + Some(x) if x.idle() => free += 1, + Some(_) => {} + } + } + } crate::xlog_info!( - "D3D12.X: {} allocator resets so far with recordings still held or on the GPU – another PC allocator took its place ({} made, {aside} put aside now)", + "D3D12.X: {} allocator resets so far with recordings still held or on the GPU – another PC allocator took its place ({} made, {aside} put aside now: {free} idle, {pinned} held by lists, {} on GPU)", s.swaps, - s.made + s.made, + aside.saturating_sub(free + pinned) ); } Some(0) @@ -603,6 +661,24 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu mod tests { use super::*; + #[test] + fn excess_idle_aside_allocators_are_reclaimed_while_title_and_busy_ones_stay() { + let (own, spare1, spare2, pinned_alloc, list) = (0x1000usize, 0x2000usize, 0x3000usize, 0x4000usize, 0x5000usize); + let mut s = State::default(); + s.aside.insert(own, vec![own, spare1, spare2, pinned_alloc]); + s.backings.insert(own, Backing::default()); + s.backings.insert(spare1, Backing::default()); + s.backings.insert(spare2, Backing::default()); + let mut pinned = Backing::default(); + pinned.users.insert(list); + s.backings.insert(pinned_alloc, pinned); + + let mut dropped = unsafe { take_excess_aside(&mut s) }; + dropped.sort_unstable(); + assert_eq!(dropped, vec![spare1, spare2], "both idle XCL-made allocators are dropped"); + assert_eq!(s.aside[&own], vec![own, pinned_alloc], "title's own allocator and pinned allocator remain"); + } + /// When a title list goes, the segments that recorded its put-off dispatches on its own /// allocator hold neither the PC allocator it stands for now nor the ones put aside: `forget` /// then releases those the GPU is done with (they were left behind, with what was held on them). diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 75c6ce3aac..669aca26db 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -11,7 +11,19 @@ //! * `0` / `off` / `none`: disabled. //! //! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, -//! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`. +//! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`, `XCL_AMBIENT_FRAME`, +//! `XCL_AMBIENT_KEEP`. +//! +//! The sky alone leaves a night scene black wherever no lamp reaches. So the fill is also raised +//! to an estimate taken from the frame itself: the light the visible surfaces send out, which the +//! title keeps for its own screen traces (`CS_CacheScreenSpaceRadiance`, the frame before), is +//! averaged in 64x36 cells right after that program, and every texel of the resolve's output gets +//! `XCL_AMBIENT_FRAME` (default 0.8; 0: off) of the cells around it, a fifth of it their slow +//! mean. The idea and the 64x36 cells, the 5x5 taps, the damping of lamps and the slow mean with +//! its jump are from mavis-9070xt's fork of VIctory (GPL-3.0-or-later), +//! `crates/victory-gpu/src/ambient.rs` (`keep`, `mean`, `raise`), after beloooo's +//! VIctory-Belobug-AMD. Not ported (2026-11-28): the directional gather at 160x90 points, the +//! normal rebuilt from depth and the bound on the title's own value. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; @@ -45,6 +57,7 @@ struct Config { reflect: f32, settle_ms: f32, air: f32, + frame: f32, } impl Default for Config { @@ -58,6 +71,7 @@ impl Default for Config { reflect: 0.50, settle_ms: 250.0, air: 0.0, + frame: 0.8, } } } @@ -92,6 +106,7 @@ fn config() -> &'static Config { reflect: env_f32("XCL_AMBIENT_REFLECT", def.reflect, 0.05, 4.0), settle_ms: env_f32("XCL_AMBIENT_SETTLE_MS", def.settle_ms, 0.0, 10_000.0), air: env_f32("XCL_AMBIENT_AIR", def.air, 0.0, 16.0), + frame: env_f32("XCL_AMBIENT_FRAME", def.frame, 0.0, 4.0), } }) } @@ -127,6 +142,23 @@ pub fn active() -> bool { } } +/// Whether the fill keeps what the title's own resolve stored where that is the larger +/// (`XCL_AMBIENT_KEEP=1` / `=0`). Unset: kept, unless programs that feed the resolve are left out +/// (`XCL_RT_LEAVE_OUT`) – then what it stores is made of memory nothing wrote this frame (on a +/// retail title: one colour all over, as bright as the fill's cap lets it be). +fn keeps_title_light() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| keeps(std::env::var("XCL_AMBIENT_KEEP").ok().as_deref(), crate::gpu::rt_leave_out::enabled())) +} + +fn keeps(switch: Option<&str>, programs_left_out: bool) -> bool { + match switch.map(str::trim) { + Some("1") => true, + Some("0") => false, + _ => !programs_left_out, + } +} + /// The title's rays bring no light: traversal is held back, or runs with every ray missing. fn rays_find_nothing(traversal_allowed: bool, every_ray_misses: bool) -> bool { !traversal_allowed || every_ray_misses @@ -139,6 +171,8 @@ pub(super) enum PassRole { TemporalResolve, ReflectionHistory, InscatteringVolume, + /// keeps the light visible surfaces send out (`CS_CacheScreenSpaceRadiance`) + Radiance, } fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool { @@ -163,6 +197,8 @@ fn classify_cs(blob: &[u8]) -> Option { Some(PassRole::ReflectionHistory) } else if contains_ascii_ci(blob, b"CS_AccumulateLocalLightInscatteringVolume") { Some(PassRole::InscatteringVolume) + } else if contains_ascii_ci(blob, b"CS_CacheScreenSpaceRadiance") { + Some(PassRole::Radiance) } else { None } @@ -371,6 +407,10 @@ fn score_dispatch_target_for_role(role: PassRole, rd: &D3D12_RESOURCE_DESC, view if role == PassRole::ReflectionHistory && view_fmt == 42 { return None; } + // (the light of visible surfaces is R11G11B10_FLOAT) + if role == PassRole::Radiance && view_fmt != 26 { + return None; + } score_dispatch_target(rd, view_fmt, groups) } @@ -495,6 +535,8 @@ struct AmbientDevice { fill_r9_pso: ID3D12PipelineState, reflect_pso: ID3D12PipelineState, air_pso: ID3D12PipelineState, + keep_pso: ID3D12PipelineState, + mean_pso: ID3D12PipelineState, sky_copy: ID3D12Resource, sky_level: ID3D12Resource, dummy_depth: ID3D12Resource, @@ -505,6 +547,7 @@ struct AmbientDevice { next_group: AtomicU32, sky_ready: AtomicBool, last_sky_us: AtomicU64, + last_keep_us: AtomicU64, } unsafe impl Send for AmbientDevice {} @@ -587,6 +630,80 @@ void main(uint3 gtid : SV_GroupThreadID, uint gidx : SV_GroupIndex) { } "#; +/// The cells the frame's light is kept in, and the float4s of the level buffer: the sky's level, +/// the cells' slow mean, the cells. +const FRAME_CELLS: (u32, u32) = (64, 36); +const LEVEL_ELEMENTS: u32 = 2 + FRAME_CELLS.0 * FRAME_CELLS.1; +/// A change of the cells' mean by more than this factor is taken at once (a cut, a new room). +const FRAME_JUMP: f32 = 3.0; + +/// The light visible surfaces send out (`out_uav`, read only), averaged into the 64x36 cells of +/// the level buffer, `share` of it. Lamps and glints count, but not for everything. +const FRAME_KEEP_HLSL: &str = r#" +Texture2D _unused : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint _u2; + uint _u3; + uint _u4; + float share; + float _p6; + float _p7; +}; +[numthreads(8, 8, 1)] +void main(uint3 at : SV_DispatchThreadID) { + if (at.x >= 64 || at.y >= 36 || width == 0 || height == 0) return; + float3 sum = float3(0.0, 0.0, 0.0); + [loop] + for (uint y = 0; y < 5; ++y) { + [loop] + for (uint x = 0; x < 5; ++x) { + float2 at_texel = (float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(width, height) / float2(64.0, 36.0); + uint2 p = min(uint2(at_texel), uint2(width - 1, height - 1)); + float3 c = out_uav[p].rgb; + c = all(isfinite(c)) ? max(c, 0.0) : float3(0.0, 0.0, 0.0); + sum += c / max(1.0, dot(c, float3(0.2126, 0.7152, 0.0722)) / 20.0); + } + } + sky_level[2 + at.y * 64 + at.x] = float4(sum * (share / 25.0), 1.0); +} +"#; + +/// The slow mean of the cells: `follow` of the way to this frame's mean, all of it when the mean +/// changed by more than `jump` either way. +const FRAME_MEAN_HLSL: &str = r#" +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint _u0; + uint _u1; + uint _u2; + uint _u3; + uint _u4; + float follow; + float jump; + float _p7; +}; +[numthreads(1, 1, 1)] +void main() { + float3 sum = float3(0.0, 0.0, 0.0); + [loop] + for (uint i = 0; i < 2304; ++i) { + float3 c = sky_level[2 + i].rgb; + sum += all(isfinite(c)) ? c : float3(0.0, 0.0, 0.0); + } + float3 now = sum / 2304.0; + float4 was = sky_level[1]; + bool kept = was.a > 0.0 && all(isfinite(was.rgb)); + float a = max(dot(now, float3(0.2126, 0.7152, 0.0722)), 1e-5); + float b = max(dot(was.rgb, float3(0.2126, 0.7152, 0.0722)), 1e-5); + bool jumped = jump > 0.0 && max(a / b, b / a) > jump; + sky_level[1] = float4(kept ? lerp(was.rgb, now, jumped ? 1.0 : saturate(follow)) : now, 1.0); +} +"#; + /// Screen-space radiance floor + 8-tap IGN-rotated golden-angle horizon crease AO + outlier /// probe tile suppression (requires typed UAV load on `out_uav`). const AMBIENT_FILL_HLSL: &str = r#" @@ -603,6 +720,27 @@ cbuffer C : register(b0) { uint sky_ready; float fallback_level; }; +// The light the frame before sent out around this texel: 64x36 cells from `sky_level[2]` on, +// their slow mean at `sky_level[1]` (its fourth part 0: nothing kept yet, no light). +float3 frame_light(uint2 tid) { + float4 mean = sky_level[1]; + if (!(mean.a > 0.0)) { + return float3(0.0, 0.0, 0.0); + } + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(63, 35)); + float wx = (k & 1) ? f.x : 1.0 - f.x; + float wy = (k >> 1) ? f.y : 1.0 - f.y; + sum += wx * wy * sky_level[2 + q.y * 64 + q.x].rgb; + } + float3 found = lerp(sum, mean.rgb, 0.2); + return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { float d0 = depth_tex.Load(int3(dc, 0)); if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { @@ -633,7 +771,8 @@ float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { if (tid.x >= width || tid.y >= height) return; - float3 amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + float3 amb = ((sky_ready & 1u) != 0u) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + amb = max(amb, frame_light(tid.xy)); float ao = 1.0; if (has_depth != 0 && depth_w > 0 && depth_h > 0) { int2 dc = int2( @@ -648,6 +787,9 @@ void main(uint3 tid : SV_DispatchThreadID) { float cap_lum = 4.0 * amb_lum; float4 cur = out_uav[tid.xy]; float3 existing = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + if ((sky_ready & 2u) == 0u) { + existing = float3(0.0, 0.0, 0.0); + } if (existing.g < 0.5 * min(existing.r, existing.b) && max(existing.r, existing.b) > 0.02) { existing = float3(0.0, 0.0, 0.0); } @@ -690,6 +832,27 @@ uint pack_r9g9b9e5(float3 c) { uint3 m = min(uint3(floor(c * inv_s + 0.5)), uint3(511u, 511u, 511u)); return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); } +// The light the frame before sent out around this texel: 64x36 cells from `sky_level[2]` on, +// their slow mean at `sky_level[1]` (its fourth part 0: nothing kept yet, no light). +float3 frame_light(uint2 tid) { + float4 mean = sky_level[1]; + if (!(mean.a > 0.0)) { + return float3(0.0, 0.0, 0.0); + } + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(63, 35)); + float wx = (k & 1) ? f.x : 1.0 - f.x; + float wy = (k >> 1) ? f.y : 1.0 - f.y; + sum += wx * wy * sky_level[2 + q.y * 64 + q.x].rgb; + } + float3 found = lerp(sum, mean.rgb, 0.2); + return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { float d0 = depth_tex.Load(int3(dc, 0)); if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { @@ -720,8 +883,8 @@ float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { if (tid.x >= width || tid.y >= height) return; - float3 raw_amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); - float3 amb = clamp(raw_amb, 0.0, 0.65); + float3 raw_amb = ((sky_ready & 1u) != 0u) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + float3 amb = max(clamp(raw_amb, 0.0, 0.65), frame_light(tid.xy)); float ao = 1.0; if (has_depth != 0 && depth_w > 0 && depth_h > 0) { int2 dc = int2( @@ -733,7 +896,7 @@ void main(uint3 tid : SV_DispatchThreadID) { } float3 amb_ao = amb * ao; float3 existing = unpack_r9g9b9e5(out_uav[tid.xy]); - if (!all(isfinite(existing))) existing = float3(0.0, 0.0, 0.0); + if (!all(isfinite(existing)) || (sky_ready & 2u) == 0u) existing = float3(0.0, 0.0, 0.0); if (existing.g < 0.5 * min(existing.r, existing.b) && max(existing.r, existing.b) > 0.02) { existing = float3(0.0, 0.0, 0.0); } @@ -762,6 +925,27 @@ cbuffer C : register(b0) { uint sky_ready; float fallback_level; }; +// The light the frame before sent out around this texel: 64x36 cells from `sky_level[2]` on, +// their slow mean at `sky_level[1]` (its fourth part 0: nothing kept yet, no light). +float3 frame_light(uint2 tid) { + float4 mean = sky_level[1]; + if (!(mean.a > 0.0)) { + return float3(0.0, 0.0, 0.0); + } + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(63, 35)); + float wx = (k & 1) ? f.x : 1.0 - f.x; + float wy = (k >> 1) ? f.y : 1.0 - f.y; + sum += wx * wy * sky_level[2 + q.y * 64 + q.x].rgb; + } + float3 found = lerp(sum, mean.rgb, 0.2); + return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { float d0 = depth_tex.Load(int3(dc, 0)); if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { @@ -792,7 +976,8 @@ float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { if (tid.x >= width || tid.y >= height) return; - float3 amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + float3 amb = ((sky_ready & 1u) != 0u) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + amb = max(amb, frame_light(tid.xy)); float ao = 1.0; if (has_depth != 0 && depth_w > 0 && depth_h > 0) { int2 dc = int2( @@ -873,6 +1058,8 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let fill_r9_bc = compile_cs_sm5(AMBIENT_FILL_R9G9B9E5_HLSL)?; let reflect_bc = compile_cs_sm5(REFLECT_CLAMP_HLSL)?; let air_bc = compile_cs_sm5(AIR_CAP_HLSL)?; + let keep_bc = compile_cs_sm5(FRAME_KEEP_HLSL)?; + let mean_bc = compile_cs_sm5(FRAME_MEAN_HLSL)?; // Shared compute RS: [0] 8 root constants (b0), [1] 1 SRV (t0), [2] 2 UAVs (u0..u1) let srv_range = D3D12_DESCRIPTOR_RANGE { @@ -971,6 +1158,8 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let fill_r9_pso = make_cs(&fill_r9_bc, "xcl ambient fill_r9")?; let reflect_pso = make_cs(&reflect_bc, "xcl ambient reflect_clamp")?; let air_pso = make_cs(&air_bc, "xcl ambient air_cap")?; + let keep_pso = make_cs(&keep_bc, "xcl ambient frame_keep")?; + let mean_pso = make_cs(&mean_bc, "xcl ambient frame_mean")?; let default_hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let make_res = |rd: &D3D12_RESOURCE_DESC, init: D3D12_RESOURCE_STATES| -> Option { @@ -995,7 +1184,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let sky_level = make_res( &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: 256, + Width: (LEVEL_ELEMENTS as u64 * 16).next_multiple_of(256), Height: 1, DepthOrArraySize: 1, MipLevels: 1, @@ -1043,6 +1232,8 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { fill_r9_pso, reflect_pso, air_pso, + keep_pso, + mean_pso, sky_copy, sky_level, dummy_depth, @@ -1053,6 +1244,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { next_group: AtomicU32::new(0), sky_ready: AtomicBool::new(false), last_sky_us: AtomicU64::new(0), + last_keep_us: AtomicU64::new(0), }) } @@ -1147,7 +1339,7 @@ pub(super) unsafe fn after_draw(list: *mut c_void, pso_resolved: usize) { Format: DXGI_FORMAT_UNKNOWN, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 1, StructureByteStride: 16, ..Default::default() }, + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_ELEMENTS, StructureByteStride: 16, ..Default::default() }, }, }; create_srv(dev_raw, ad.sky_copy.as_raw(), &sky_srv, cpu0 as usize); @@ -1424,11 +1616,11 @@ pub(super) unsafe fn after_compute_dispatch( return; } let Some(role) = role_of(pso_resolved) else { return }; - if !matches!(role, PassRole::TemporalResolve | PassRole::ReflectionHistory | PassRole::InscatteringVolume) { + if !matches!(role, PassRole::TemporalResolve | PassRole::ReflectionHistory | PassRole::InscatteringVolume | PassRole::Radiance) { return; } let cfg = config(); - if role == PassRole::InscatteringVolume && cfg.air <= 0.0 { + if role == PassRole::InscatteringVolume && cfg.air <= 0.0 || role == PassRole::Radiance && cfg.frame <= 0.0 { return; } let ty = list_x::tracked_list_type(list); @@ -1454,7 +1646,8 @@ pub(super) unsafe fn after_compute_dispatch( let Some(dev) = dev else { return }; let Some(ad) = get_device(&dev) else { return }; let sky_ready = ad.sky_ready.load(Ordering::Acquire); - if !sky_ready { + // (keeping the frame's light needs no sky) + if !sky_ready && role != PassRole::Radiance { static NO_SKY: AtomicU64 = AtomicU64::new(0); if NO_SKY.fetch_add(1, Ordering::Relaxed) < 2 { crate::xlog_info!( @@ -1479,7 +1672,7 @@ pub(super) unsafe fn after_compute_dispatch( return; }; let can_typed_load = typed_uav_load_supported(&dev, DXGI_FORMAT(uav_fmt)); - if matches!(role, PassRole::ReflectionHistory | PassRole::InscatteringVolume) && !can_typed_load { + if matches!(role, PassRole::ReflectionHistory | PassRole::InscatteringVolume | PassRole::Radiance) && !can_typed_load { static NO_LOAD: AtomicU64 = AtomicU64::new(0); if NO_LOAD.fetch_add(1, Ordering::Relaxed) < 2 { crate::xlog_info!("D3D12.X: ambient: {role:?} skipped (typed UAV load unsupported for fmt {uav_fmt})"); @@ -1528,7 +1721,7 @@ pub(super) unsafe fn after_compute_dispatch( Format: DXGI_FORMAT_UNKNOWN, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 1, StructureByteStride: 16, ..Default::default() }, + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_ELEMENTS, StructureByteStride: 16, ..Default::default() }, }, }; create_srv(dev_raw, depth_raw, &depth_srv, cpu0 as usize); @@ -1554,7 +1747,7 @@ pub(super) unsafe fn after_compute_dispatch( } else { ad.fill_write_pso.as_raw() }, - [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), sky_ready as u32, cfg.least.to_bits()], + [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), sky_ready as u32 | (keeps_title_light() as u32) << 1, cfg.least.to_bits()], (w.div_ceil(8), h.div_ceil(8), 1), ), PassRole::ReflectionHistory => ( @@ -1567,6 +1760,11 @@ pub(super) unsafe fn after_compute_dispatch( [w, h, d, 0, 0, cfg.air.to_bits(), 0, 0], (w.div_ceil(8), h.div_ceil(8), d.div_ceil(2)), ), + PassRole::Radiance => ( + ad.keep_pso.as_raw(), + [w, h, 0, 0, 0, cfg.frame.to_bits(), 0, 0], + (FRAME_CELLS.0.div_ceil(8), FRAME_CELLS.1.div_ceil(8), 1), + ), PassRole::SkyDome => return, }; set_heaps(list, 1, &heap_raw); @@ -1578,6 +1776,27 @@ pub(super) unsafe fn after_compute_dispatch( set_cs_table(list, 2, gpu0 + inc); dispatch(list, disp.0, disp.1, disp.2); uav_barrier(list, uav_res); + if role == PassRole::Radiance { + // the cells' slow mean, by the clock + let level = ad.sky_level.as_raw() as usize; + uav_barrier(list, level); + let now_us = monotonic_us(); + let prev_us = ad.last_keep_us.swap(now_us, Ordering::AcqRel); + let dt_s = if prev_us == 0 { 0.0 } else { now_us.saturating_sub(prev_us) as f32 * 1e-6 }; + let consts = [0, 0, 0, 0, 0, settle_alpha(dt_s, cfg.settle_ms, prev_us == 0).to_bits(), FRAME_JUMP.to_bits(), 0]; + super::dred::mark_pipeline(list, ad.mean_pso.as_raw() as usize, ad.mean_pso.as_raw() as usize); + set_pso(list, ad.mean_pso.as_raw()); + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + dispatch(list, 1, 1, 1); + uav_barrier(list, level); + list_x::restore_after_internal_pass(list, false, true); + static KEPT: AtomicU64 = AtomicU64::new(0); + let n = KEPT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: ambient: the frame's light kept from {w}x{h} fmt {uav_fmt} in {}x{} cells ({n} so far)", FRAME_CELLS.0, FRAME_CELLS.1); + } + return; + } list_x::restore_after_internal_pass(list, false, true); static LOGGED: AtomicU64 = AtomicU64::new(0); @@ -1600,6 +1819,14 @@ mod tests { assert!(!rays_find_nothing(true, false), "rays that hit bring the title's own light"); } + #[test] + fn the_titles_own_light_is_kept_unless_the_programs_that_feed_it_are_left_out() { + assert!(keeps(None, false)); + assert!(!keeps(None, true), "left-out programs: the resolve reads memory nothing wrote"); + assert!(keeps(Some("1"), true) && !keeps(Some(" 0 "), false), "the switch decides"); + assert!(keeps(Some("x"), false) && !keeps(Some(""), true), "any other value: as unset"); + } + #[test] fn mode_and_shader_classification_match_expected_passes() { assert_eq!(parse_mode(None), Mode::Auto); @@ -1615,6 +1842,7 @@ mod tests { assert_eq!(classify_cs(b"ILDN\0CS_ScreenProbes_TemporalResolve\0"), Some(PassRole::TemporalResolve)); assert_eq!(classify_cs(b"ILDN\0CS_UpdateHistory_16\0"), Some(PassRole::ReflectionHistory)); + assert_eq!(classify_cs(b"ILDN\0CS_CacheScreenSpaceRadiance\0"), Some(PassRole::Radiance)); assert_eq!(classify_cs(b"ILDN\0CS_CullInstances\0"), None); } @@ -1679,6 +1907,10 @@ mod tests { assert!(compile_cs_sm5(AMBIENT_FILL_R9G9B9E5_HLSL).is_some(), "AMBIENT_FILL_R9G9B9E5_HLSL failed D3DCompile"); assert!(compile_cs_sm5(REFLECT_CLAMP_HLSL).is_some(), "REFLECT_CLAMP_HLSL failed D3DCompile"); assert!(compile_cs_sm5(AIR_CAP_HLSL).is_some(), "AIR_CAP_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(FRAME_KEEP_HLSL).is_some(), "FRAME_KEEP_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(FRAME_MEAN_HLSL).is_some(), "FRAME_MEAN_HLSL failed D3DCompile"); + // the cells the fills read are the cells the keeping writes, and the mean sums all of them + assert_eq!((FRAME_CELLS, LEVEL_ELEMENTS), ((64, 36), 2 + 2304)); } #[test] @@ -1703,6 +1935,10 @@ mod tests { assert!(score_dispatch_target_for_role(PassRole::TemporalResolve, &r9_probe, DXGI_FORMAT_R32_UINT.0, [320, 360, 1]).is_some()); assert!(score_dispatch_target_for_role(PassRole::ReflectionHistory, &r9_probe, DXGI_FORMAT_R32_UINT.0, [320, 360, 1]).is_none()); assert!(score_dispatch_target_for_role(PassRole::ReflectionHistory, &hdr_scene, DXGI_FORMAT_R11G11B10_FLOAT.0, [320, 360, 1]).is_some()); + // the frame's light is kept from the R11G11B10_FLOAT image only + assert!(score_dispatch_target_for_role(PassRole::Radiance, &hdr_scene, DXGI_FORMAT_R11G11B10_FLOAT.0, [320, 360, 1]).is_some()); + assert!(score_dispatch_target_for_role(PassRole::Radiance, &r9_probe, DXGI_FORMAT_R32_UINT.0, [320, 360, 1]).is_none()); + assert!(score_dispatch_target_for_role(PassRole::Radiance, &hdr_scene, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [320, 360, 1]).is_none()); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/barrier_groups.rs b/crates/xcl/src/hle/d3d12x/barrier_groups.rs new file mode 100644 index 0000000000..1911754577 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/barrier_groups.rs @@ -0,0 +1,477 @@ +//! Command list #146 `Barrier(groups)`: a title's enhanced barriers as the PC's transitions. +//! +//! A title that names layouts instead of states makes all its transitions through this call (a +//! retail title's frame held 15 `ResourceBarrier` calls, its upscaler's, and thousands of these). +//! Answered with a UAV barrier alone, the PC's textures stayed in the state they were made in: +//! a render target was sampled without the driver ever taking it out of its compressed form, a +//! depth buffer read as a texture was never expanded, and a depth buffer the title moved into +//! unordered access never reached `depth_uav`, whose copies between a depth plane and its twin +//! hang on that transition. +//! +//! Each texture barrier becomes a legacy transition between the states its layouts stand for +//! (`state_of`), on the subresources it names, and goes the way a title's `ResourceBarrier` +//! goes (`list_x::resource_barrier_x`). A layout says where a texture is; the access bits only +//! say which uses the title makes of it there, so the states come from the layouts. A barrier to +//! the undefined layout (the title is done with what the texture holds) moves nothing; one from +//! it starts at the state the texture was last moved to here. Buffer and global barriers have no +//! layout: the UAV barrier `list_x::uav_barrier_x` sends stands for them. +//! +//! `XCL_BARRIER_GROUPS=0` turns the transitions off (the UAV barrier stays). + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::sharded::Sharded; + +/// D3D12_BARRIER_LAYOUT_UNDEFINED +const UNDEFINED: u32 = 0xFFFF_FFFF; +/// D3D12_BARRIER_SYNC_SPLIT +const SYNC_SPLIT: u32 = 0x8000_0000; +/// D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ +const ACCESS_DEPTH_READ: u32 = 0x40; +/// D3D12_RESOURCE_STATE_* +const RENDER_TARGET: u32 = 0x4; +const UNORDERED_ACCESS: u32 = 0x8; +const DEPTH_WRITE: u32 = 0x10; +const DEPTH_READ: u32 = 0x20; +const SHADER_RESOURCE: u32 = 0x40 | 0x80; +const COPY_DEST: u32 = 0x400; +const COPY_SOURCE: u32 = 0x800; +const RESOLVE_DEST: u32 = 0x1000; +const RESOLVE_SOURCE: u32 = 0x2000; +const SHADING_RATE_SOURCE: u32 = 0x100_0000; +/// D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY, END_ONLY +const BEGIN_ONLY: u32 = 1; +const END_ONLY: u32 = 2; +/// subresources of one barrier's range named one by one at most (more: all of the texture) +const RANGE_MOST: usize = 64; + +/// Whether the title's barrier groups become transitions (`XCL_BARRIER_GROUPS`, on unless "0"). +pub(super) fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_BARRIER_GROUPS").map_or(true, |v| v.trim() != "0"); + if !on { + crate::xlog_info!("D3D12.X: XCL_BARRIER_GROUPS=0 – the title's barrier groups (#146) move no texture"); + } + on + }) +} + +/// The state the PC has a texture in where the title has it in `layout` with `access` +/// (`depth`: a depth buffer). None: the undefined layout, or one XCL does not know. +pub(super) fn state_of(layout: u32, access: u32, depth: bool) -> Option { + // reading layouts take a depth buffer's read-only depth use with them + let read = |s: u32| if depth && (access & ACCESS_DEPTH_READ != 0 || access & 0x8000_0000 != 0) { s | DEPTH_READ } else { s }; + Some(match layout { + // COMMON / PRESENT, and the queues' own + 0 | 18 | 24 | 30 => 0, + // GENERIC_READ, DIRECT_QUEUE_GENERIC_READ, COMPUTE_QUEUE_GENERIC_READ, + // DIRECT_QUEUE_GENERIC_READ_COMPUTE_QUEUE_ACCESSIBLE + 1 | 19 | 25 | 31 => read(SHADER_RESOURCE | COPY_SOURCE), + 2 => RENDER_TARGET, + 3 | 20 | 26 => UNORDERED_ACCESS, + 4 => DEPTH_WRITE, + // (read by the depth test and by shaders at once) + 5 => DEPTH_READ | SHADER_RESOURCE, + 6 | 21 | 27 => read(SHADER_RESOURCE), + 7 | 22 | 28 => COPY_SOURCE, + 8 | 23 | 29 => COPY_DEST, + 9 => RESOLVE_SOURCE, + 10 => RESOLVE_DEST, + 11 => SHADING_RATE_SOURCE, + _ => return None, + }) +} + +/// The subresources a barrier's range names in a texture of `mips` levels, `array` slices and +/// `planes` planes: `range` is D3D12_BARRIER_SUBRESOURCE_RANGE (index or first level, levels, +/// first slice, slices, first plane, planes; no levels: the first word is a subresource index). +/// None: all of them. +pub(super) fn subresources(range: [u32; 6], mips: u32, array: u32, planes: u32) -> Option> { + let [first_mip, n_mips, first_slice, n_slices, first_plane, n_planes] = range; + let (mips, array, planes) = (mips.max(1), array.max(1), planes.max(1)); + if n_mips == 0 { + return (first_mip != u32::MAX && (mips * array * planes > 1)).then(|| vec![first_mip]); + } + // (slices and planes of 0 are one, as the PC reads the range) + let m = first_mip.min(mips)..first_mip.saturating_add(n_mips).min(mips); + let s = first_slice.min(array)..first_slice.saturating_add(n_slices.max(1)).min(array); + let p = first_plane.min(planes)..first_plane.saturating_add(n_planes.max(1)).min(planes); + let count = m.len() * s.len() * p.len(); + if count == (mips * array * planes) as usize || count > RANGE_MOST { + return None; + } + let mut out = Vec::with_capacity(count); + for plane in p { + for slice in s.clone() { + for mip in m.clone() { + out.push(mip + slice * mips + plane * mips * array); + } + } + } + Some(out) +} + +/// One texture barrier as the words of a D3D12_TEXTURE_BARRIER the PC reads it by. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Texture { + pub sync: (u32, u32), + pub access: (u32, u32), + pub layout: (u32, u32), + pub res: usize, + pub range: [u32; 6], +} + +/// What a texture is like for `transitions_of`: (depth buffer, levels, slices, planes). +pub(super) type Shape = (bool, u32, u32, u32); + +/// The transitions (PC D3D12_RESOURCE_BARRIERs as words) of the title's texture barriers `b`: +/// `shape` gives a texture's shape (None: not a texture XCL can ask), `last` the state a +/// texture was last moved to here, and `moved` notes the one it is in after a barrier. +pub(super) fn transitions_of(b: &[Texture], shape: &mut dyn FnMut(usize) -> Option, last: &mut dyn FnMut(usize) -> Option, moved: &mut dyn FnMut(usize, u32)) -> Vec<[u32; 8]> { + let mut out = Vec::with_capacity(b.len()); + for t in b { + if t.res == 0 { + continue; + } + let Some((depth, mips, array, planes)) = shape(t.res) else { continue }; + let after = state_of(t.layout.1, t.access.1, depth); + let before = match t.layout.0 { + UNDEFINED => last(t.res), + l => state_of(l, t.access.0, depth), + }; + if t.layout.1 != UNDEFINED && after.is_none() || t.layout.0 != UNDEFINED && before.is_none() { + unknown_layout(t.layout); + continue; + } + let (before, after) = match (before, after) { + (Some(b), Some(a)) => (b, a), + // to the undefined layout: the texture stays where it is; from it, never moved + // here: where it goes is where it is taken to be + (b, a) => { + if let Some(s) = b.or(a) { + moved(t.res, s); + } + continue; + } + }; + moved(t.res, after); + if before == after { + continue; + } + // a barrier split over two lists: its first half ends in SYNC_SPLIT, its second starts there + let flags = if t.sync.1 == SYNC_SPLIT { BEGIN_ONLY } else if t.sync.0 == SYNC_SPLIT { END_ONLY } else { 0 }; + let word = |sub: u32| [0, flags, t.res as u32, (t.res as u64 >> 32) as u32, sub, before, after, 0]; + match subresources(t.range, mips, array, planes) { + None => out.push(word(D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES)), + Some(subs) => out.extend(subs.into_iter().map(word)), + } + } + out +} + +fn unknown_layout(layout: (u32, u32)) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: a barrier group's texture barrier between layouts {:#x} and {:#x}, one of which XCL does not know: the texture is not moved ({n} so far)", layout.0, layout.1); + } +} + +/// The state each texture was last moved to by a barrier group (the title's recording order). +static LAST: Sharded = Sharded::new(); +/// Texture barriers read, and transitions made of them. +static COUNTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The last reference of `res` goes (`real::res_release`). +pub(super) fn forget(res: usize) { + if COUNTS[0].load(Ordering::Relaxed) != 0 { + LAST.remove(res); + } +} + +/// `state` as a texture with the PC resource flags `flags` (D3D12_RESOURCE_FLAGS) can be in it on +/// a direct list (`direct`) or a compute one: the reading states the texture or the list cannot +/// have are left out of it. None: it cannot be there at all (a render target state of a texture +/// that is none on the PC, a depth state on a compute list) – the PC refuses such a transition +/// when the list closes, and the title stops on that. +pub(super) fn legal(state: u32, flags: u32, direct: bool) -> Option { + const ALLOW_RENDER_TARGET: u32 = 0x1; + const ALLOW_DEPTH_STENCIL: u32 = 0x2; + const ALLOW_UNORDERED_ACCESS: u32 = 0x4; + const DENY_SHADER_RESOURCE: u32 = 0x8; + let mut s = state; + if s & RENDER_TARGET != 0 && flags & ALLOW_RENDER_TARGET == 0 || s & UNORDERED_ACCESS != 0 && flags & ALLOW_UNORDERED_ACCESS == 0 || s & DEPTH_WRITE != 0 && flags & ALLOW_DEPTH_STENCIL == 0 { + return None; + } + if flags & ALLOW_DEPTH_STENCIL == 0 { + s &= !DEPTH_READ; + } + if flags & DENY_SHADER_RESOURCE != 0 { + s &= !SHADER_RESOURCE; + } + if !direct { + if s & (RENDER_TARGET | DEPTH_WRITE | DEPTH_READ | RESOLVE_DEST | RESOLVE_SOURCE | SHADING_RATE_SOURCE) != 0 { + return None; + } + // (PIXEL_SHADER_RESOURCE) + s &= !0x80; + } + Some(s) +} + +/// What `transitions` asks of a texture once: its flags, its subresources, and its format. +#[derive(Clone, Copy)] +struct Asked { + flags: u32, + subresources: u32, + format: i32, +} + +/// The title's `n` barrier groups at `groups` (D3D12_BARRIER_GROUP) as transitions for the PC +/// list (`direct`: a direct one). Nothing with the switch off. +pub(super) unsafe fn transitions(n: u32, groups: *const c_void, direct: bool) -> Vec<[u32; 8]> { + if !enabled() || n == 0 || groups.is_null() { + return Vec::new(); + } + let count = (n as usize).min(256); + if !crate::gpu::shader::readable(groups as usize, count * std::mem::size_of::()) { + return Vec::new(); + } + let mut textures = Vec::new(); + for grp in std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, count) { + let nb = (grp.NumBarriers as usize).min(4096); + let p = grp.Anonymous.pTextureBarriers; + if grp.Type != D3D12_BARRIER_TYPE_TEXTURE || nb == 0 || p.is_null() || !crate::gpu::shader::readable(p as usize, nb * std::mem::size_of::()) { + continue; + } + for tb in std::slice::from_raw_parts(p, nb) { + let r = &tb.Subresources; + textures.push(Texture { + sync: (tb.SyncBefore.0 as u32, tb.SyncAfter.0 as u32), + access: (tb.AccessBefore.0 as u32, tb.AccessAfter.0 as u32), + layout: (tb.LayoutBefore.0 as u32, tb.LayoutAfter.0 as u32), + res: std::mem::transmute_copy(&tb.pResource), + range: [r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, r.NumPlanes], + }); + } + } + if textures.is_empty() { + return Vec::new(); + } + let mut asked: Vec<(usize, Asked)> = Vec::new(); + let mut out = transitions_of( + &textures, + &mut |res| { + if !crate::gpu::shader::readable(res, 8) { + return None; + } + let r = res as *mut c_void; + let d = ID3D12Resource::from_raw_borrowed(&r)?.GetDesc(); + if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return None; + } + let depth = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0; + let array = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { d.DepthOrArraySize as u32 }; + // (two planes: the depth-stencil formats R32G8X24 and R24G8 and their views) + let planes = if matches!(d.Format.0, 19..=22 | 44..=47) { 2 } else { 1 }; + if !asked.iter().any(|a| a.0 == res) { + asked.push((res, Asked { flags: d.Flags.0 as u32, subresources: d.MipLevels as u32 * array * planes, format: d.Format.0 })); + } + Some((depth, d.MipLevels as u32, array, planes)) + }, + &mut |res| LAST.get(res), + &mut |res, state| { + LAST.insert(res, state); + }, + ); + out.retain_mut(|w| { + let res = (w[2] as u64 | (w[3] as u64) << 32) as usize; + let Some(a) = asked.iter().find(|a| a.0 == res).map(|a| a.1) else { return false }; + if w[4] != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && w[4] >= a.subresources { + return refused(w, a, "a subresource the texture does not have"); + } + // a depth buffer the PC gave no unordered access (`device_x::pc_resource_desc`) cannot + // be in UNORDERED_ACCESS: one `depth_uav` keeps is taken from there by + // `depth_uav::plan_barriers`, any other rests where that would park it + let depth_only = a.flags & 0x2 != 0 && a.flags & 0x4 == 0; + let kept = depth_only && super::depth_uav::kept(res); + for i in 5..7 { + if depth_only && w[i] == UNORDERED_ACCESS { + if !kept { + w[i] = super::depth_uav::PARK; + } + continue; + } + match legal(w[i], a.flags, direct) { + Some(s) => w[i] = s, + None => return refused(w, a, if direct { "a state the PC's texture cannot be in" } else { "a state a compute list cannot move a texture to or from" }), + } + } + w[5] != w[6] + }); + let read = COUNTS[0].fetch_add(textures.len() as u64, Ordering::Relaxed) + textures.len() as u64; + let made = COUNTS[1].fetch_add(out.len() as u64, Ordering::Relaxed) + out.len() as u64; + if (read - textures.len() as u64).leading_zeros() != read.leading_zeros() && read >= 1024 { + crate::xlog_info!("D3D12.X: barrier groups (#146): {read} texture barriers of the title so far, {made} transitions made of them, {} not made (the PC would refuse them)", REFUSED.load(Ordering::Relaxed)); + } + if log_each() { + for w in &out { + let res = (w[2] as u64 | (w[3] as u64) << 32) as usize; + if let Some(a) = asked.iter().find(|a| a.0 == res).map(|a| a.1) { + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); + let mut g = SEEN.lock().unwrap(); + let seen = g.get_or_insert_with(Default::default); + if seen.len() < 400 && seen.insert((a.flags, a.format, w[4], w[5], w[6], w[1], direct)) { + crate::xlog_info!("D3D12.X: barrier groups: a transition of a kind not seen before: texture {res:#x} (flags {:#x}, format {}, {} subresources), subresource {:#x}, {:#x} → {:#x}, flags {:#x}, on a {} list", a.flags, a.format, a.subresources, w[4], w[5], w[6], w[1], if direct { "direct" } else { "compute or copy" }); + } + } + } + } + out +} + +/// Transitions not made: the PC would refuse them. +static REFUSED: AtomicU64 = AtomicU64::new(0); + +/// A transition that is not made (false, for `retain_mut`). +fn refused(w: &[u32; 8], a: Asked, why: &str) -> bool { + let n = REFUSED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: barrier groups: a transition of a texture (flags {:#x}, format {}, {} subresources) not made – {why}: subresource {:#x}, {:#x} → {:#x} ({n} so far)", a.flags, a.format, a.subresources, w[4], w[5], w[6]); + } + false +} + +/// `XCL_BARRIER_LOG=1`: each kind of transition made, once. +fn log_each() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_BARRIER_LOG").is_ok_and(|v| v.trim() == "1")) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + const NO_ACCESS: u32 = 0x8000_0000; + + #[test] + fn a_layout_stands_for_the_state_the_pc_has_the_texture_in() { + assert_eq!(state_of(2, 0x8, false), Some(RENDER_TARGET)); + assert_eq!(state_of(6, 0x80, false), Some(SHADER_RESOURCE)); + assert_eq!(state_of(21, 0x80, false), Some(SHADER_RESOURCE), "the direct queue's own"); + assert_eq!(state_of(3, 0x10, true), Some(UNORDERED_ACCESS)); + assert_eq!(state_of(4, 0x20, true), Some(DEPTH_WRITE)); + assert_eq!(state_of(5, 0x40, true), Some(DEPTH_READ | SHADER_RESOURCE)); + assert_eq!(state_of(6, 0x80, true), Some(SHADER_RESOURCE), "a depth buffer only shaders read"); + assert_eq!(state_of(6, 0x80 | 0x40, true), Some(SHADER_RESOURCE | DEPTH_READ)); + assert_eq!(state_of(31, NO_ACCESS, false), Some(SHADER_RESOURCE | COPY_SOURCE)); + assert_eq!(state_of(0, 0, false), Some(0)); + assert_eq!(state_of(UNDEFINED, NO_ACCESS, false), None); + assert_eq!(state_of(12, 0, false), None, "a video layout"); + } + + #[test] + fn a_state_the_pcs_texture_or_list_cannot_have_is_left_out_or_refused() { + // (flags: 1 render target, 2 depth, 4 unordered access, 8 no shader resource) + assert_eq!(legal(RENDER_TARGET, 0x1, true), Some(RENDER_TARGET)); + assert_eq!(legal(RENDER_TARGET, 0x0, true), None, "the PC's copy is no render target"); + assert_eq!(legal(UNORDERED_ACCESS, 0x1, true), None); + assert_eq!(legal(DEPTH_WRITE, 0x1, true), None); + assert_eq!(legal(SHADER_RESOURCE | DEPTH_READ, 0x0, true), Some(SHADER_RESOURCE), "not a depth buffer"); + assert_eq!(legal(SHADER_RESOURCE | DEPTH_READ, 0x2 | 0x8, true), Some(DEPTH_READ), "a depth buffer no shader reads"); + assert_eq!(legal(0, 0x0, true), Some(0)); + // a compute list + assert_eq!(legal(SHADER_RESOURCE, 0x0, false), Some(0x40)); + assert_eq!(legal(UNORDERED_ACCESS, 0x4, false), Some(UNORDERED_ACCESS)); + assert_eq!(legal(RENDER_TARGET, 0x1, false), None); + assert_eq!(legal(DEPTH_READ | SHADER_RESOURCE, 0x2, false), None); + assert_eq!(legal(COPY_SOURCE | SHADER_RESOURCE, 0x0, false), Some(COPY_SOURCE | 0x40)); + } + + #[test] + fn a_range_names_its_subresources_or_all_of_them() { + // an index + assert_eq!(subresources([u32::MAX, 0, 0, 0, 0, 0], 4, 2, 1), None); + assert_eq!(subresources([5, 0, 0, 0, 0, 0], 4, 2, 1), Some(vec![5])); + assert_eq!(subresources([0, 0, 0, 0, 0, 0], 1, 1, 1), None, "the one there is"); + // a range: all of it, a level of each slice, the stencil plane + assert_eq!(subresources([0, 4, 0, 2, 0, 1], 4, 2, 1), None); + assert_eq!(subresources([1, 1, 0, 2, 0, 1], 4, 2, 1), Some(vec![1, 5])); + assert_eq!(subresources([0, 1, 0, 1, 1, 1], 1, 1, 2), Some(vec![1])); + assert_eq!(subresources([0, 1, 0, 0, 0, 0], 1, 1, 1), None, "no slices and planes named: one of each"); + // past the texture: what there is of it + assert_eq!(subresources([2, 8, 0, 1, 0, 1], 4, 1, 1), Some(vec![2, 3])); + // more than are named one by one: all + assert_eq!(subresources([0, 1, 0, 100, 0, 1], 2, 100, 1), None); + } + + fn t(res: usize, layout: (u32, u32), access: (u32, u32)) -> Texture { + Texture { sync: (0, 0), access, layout, res, range: [u32::MAX, 0, 0, 0, 0, 0] } + } + + fn run(b: &[Texture], last: &mut std::collections::HashMap) -> Vec<(usize, u32, u32, u32, u32)> { + let known = last.clone(); + let mut moved = Vec::new(); + let out = transitions_of(b, &mut |res| (res != 0xBAD).then_some((res == 0xD, 1, 1, if res == 0xD { 2 } else { 1 })), &mut |res| known.get(&res).copied(), &mut |res, s| moved.push((res, s))); + last.extend(moved); + out.iter().map(|w| ((w[2] as u64 | (w[3] as u64) << 32) as usize, w[4], w[5], w[6], w[1])).collect() + } + + #[test] + fn texture_barriers_become_transitions_between_their_layouts_states() { + let mut last = Default::default(); + // render target → sampled → render target + assert_eq!(run(&[t(0xA, (2, 6), (0x8, 0x80))], &mut last), [(0xA, ALL, RENDER_TARGET, SHADER_RESOURCE, 0)]); + assert_eq!(run(&[t(0xA, (6, 2), (0x80, 0x8))], &mut last), [(0xA, ALL, SHADER_RESOURCE, RENDER_TARGET, 0)]); + // a depth buffer into unordered access and out of it + assert_eq!(run(&[t(0xD, (4, 3), (0x20, 0x10)), t(0xD, (3, 6), (0x10, 0x80))], &mut last), [(0xD, ALL, DEPTH_WRITE, UNORDERED_ACCESS, 0), (0xD, ALL, UNORDERED_ACCESS, SHADER_RESOURCE, 0)]); + // only the access changes: nothing to move + assert_eq!(run(&[t(0xA, (3, 3), (0x10, 0x10)), t(0xA, (6, 21), (0x80, 0x80))], &mut last), []); + // not a texture XCL can ask, and no resource + assert_eq!(run(&[t(0xBAD, (2, 6), (0x8, 0x80)), t(0, (2, 6), (0x8, 0x80))], &mut last), []); + } + + #[test] + fn the_undefined_layout_moves_nothing_and_is_left_from_where_the_texture_was() { + let mut last = Default::default(); + // never moved here: where it goes is noted, nothing is sent + assert_eq!(run(&[t(0xB, (UNDEFINED, 2), (NO_ACCESS, 0x8))], &mut last), []); + assert_eq!(last.get(&0xB), Some(&RENDER_TARGET)); + // to the undefined layout: it stays a render target + assert_eq!(run(&[t(0xB, (2, UNDEFINED), (0x8, NO_ACCESS))], &mut last), []); + assert_eq!(last.get(&0xB), Some(&RENDER_TARGET)); + // from it into unordered access: from the render target it still is + assert_eq!(run(&[t(0xB, (UNDEFINED, 3), (NO_ACCESS, 0x10))], &mut last), [(0xB, ALL, RENDER_TARGET, UNORDERED_ACCESS, 0)]); + // and where it already is: nothing + assert_eq!(run(&[t(0xB, (UNDEFINED, 3), (NO_ACCESS, 0x10))], &mut last), []); + // a texture first seen leaving for the undefined layout is where it says it was + assert_eq!(run(&[t(0xC, (6, UNDEFINED), (0x80, NO_ACCESS))], &mut last), []); + assert_eq!(last.get(&0xC), Some(&SHADER_RESOURCE)); + } + + #[test] + fn the_halves_of_a_split_barrier_are_the_pcs_begin_and_end() { + let mut last = Default::default(); + let mut first = t(0xA, (2, 6), (0x8, 0x80)); + first.sync = (0x4, SYNC_SPLIT); + let mut second = first; + second.sync = (SYNC_SPLIT, 0x8); + assert_eq!(run(&[first], &mut last), [(0xA, ALL, RENDER_TARGET, SHADER_RESOURCE, BEGIN_ONLY)]); + assert_eq!(run(&[second], &mut last), [(0xA, ALL, RENDER_TARGET, SHADER_RESOURCE, END_ONLY)]); + } + + #[test] + fn a_ranged_barrier_names_each_subresource() { + let mut last = Default::default(); + let mut b = t(0xD, (4, 6), (0x20, 0x80)); + b.range = [0, 1, 0, 1, 1, 1]; + assert_eq!(run(&[b], &mut last), [(0xD, 1, DEPTH_WRITE, SHADER_RESOURCE, 0)], "the stencil plane of a one-level depth buffer"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index c084a9f6ef..7076ff743c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -129,6 +129,7 @@ impl TwoPassBuf { } }; note_two_pass(TP_MADE); + super::real::note_va("two-pass buffer", res.GetGPUVirtualAddress(), bytes, false); Ok(TwoPassBuf { res, bytes, dev: dev.as_raw() as usize }) } } @@ -160,6 +161,7 @@ impl Drop for TwoPassBuf { fn drop(&mut self) { TWO_PASS[TP_ALIVE].fetch_sub(self.bytes, Ordering::Relaxed); note_two_pass(TP_GONE); + super::real::note_va("two-pass buffer", unsafe { self.res.GetGPUVirtualAddress() }, self.bytes, true); } } @@ -239,7 +241,7 @@ pub(super) fn release_allocator_res(allocator: usize) { let _gone = { let mut free = FREE_RES.lock().unwrap(); let now = std::time::Instant::now(); - let mut gone = free.take_idle(now, FREE_RES_IDLE); + let mut gone = free.take_idle(now, FREE_RES_IDLE + console_list::retire_age()); for b in bufs.into_iter().flatten().chain(aged.into_iter().map(|(b, _)| b)) { gone.extend(free.put(now, b.bytes, b.dev, b)); } @@ -251,7 +253,7 @@ pub(super) fn release_allocator_res(allocator: usize) { fn take_free(dev: usize, min: u64, max: u64) -> Option { let (gone, picked) = { let mut free = FREE_RES.lock().unwrap(); - (free.take_idle(std::time::Instant::now(), FREE_RES_IDLE), free.take(dev, min, max)) + (free.take_idle(std::time::Instant::now(), FREE_RES_IDLE + console_list::retire_age()), free.take(dev, min, max)) }; // (let go outside the lock) drop(gone); @@ -348,12 +350,14 @@ impl FreePool { /// The smallest kept on `dev` of `min..=max` bytes, of those the last handed back (so the /// ones no recording needs grow old and go). + /// One handed back less than `console_list::retire_age` ago is not taken yet. fn take(&mut self, dev: usize, min: u64, max: u64) -> Option { + let (now, retire) = (std::time::Instant::now(), console_list::retire_age()); let i = self .free .iter() .enumerate() - .filter(|(_, &(_, b, d, _))| d == dev && b >= min && b <= max) + .filter(|(_, &(at, b, d, _))| d == dev && b >= min && b <= max && now.saturating_duration_since(at) >= retire) .min_by_key(|&(i, &(_, b, _, _))| (b, std::cmp::Reverse(i)))? .0; let (_, b, _, t) = self.free.remove(i); @@ -1486,8 +1490,14 @@ unsafe fn emit_commands(this: *mut c_void, list: &ID3D12GraphicsCommandList, cmd let p = *p as *mut c_void; list.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&p)); } - Cmd::ComputeView(slot, va) => list.SetComputeRootUnorderedAccessView(*slot, *va), - Cmd::GraphicsView(slot, va) => list.SetGraphicsRootUnorderedAccessView(*slot, *va), + Cmd::ComputeView(slot, va) => { + super::real::note_root_view(list.as_raw() as usize, *slot, *va); + list.SetComputeRootUnorderedAccessView(*slot, *va) + } + Cmd::GraphicsView(slot, va) => { + super::real::note_root_view(list.as_raw() as usize, *slot, *va); + list.SetGraphicsRootUnorderedAccessView(*slot, *va) + } Cmd::Dispatch(n) => list.Dispatch(*n, 1, 1), Cmd::DispatchMesh(n) => pc_dm(this, *n, 1, 1), Cmd::Indirect(sig, buf, at) => pc_ei(this, *sig, 1, *buf, *at, 0, 0), @@ -1844,11 +1854,13 @@ unsafe fn emit_two_pass_stage(list: &ID3D12GraphicsCommandList, stage: &StageBin if compute_pass { list.SetComputeRootSignature(rs); for (k, &v) in stage.views.iter().enumerate() { + super::real::note_root_view(list.as_raw() as usize, k as u32, v); list.SetComputeRootUnorderedAccessView(k as u32, v); } } else { list.SetGraphicsRootSignature(rs); for (k, &v) in stage.views.iter().enumerate() { + super::real::note_root_view(list.as_raw() as usize, k as u32, v); list.SetGraphicsRootUnorderedAccessView(k as u32, v); } } @@ -2080,6 +2092,7 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman list.SetComputeRootSignature(ID3D12RootSignature::from_raw_borrowed(&rs_raw)); list.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&pso_raw)); for (slot, va) in rewrite.views { + super::real::note_root_view(list.as_raw() as usize, slot, va); list.SetComputeRootUnorderedAccessView(slot, va); } list.Dispatch(rewrite.groups, 1, 1); @@ -2441,6 +2454,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } flush_two_pass(this, RunEnd::Draw); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + if compute { + note_dispatch_views(this, raw_pso); + } if !gfx && !compute { // (a pipeline still being built: skipped above, `DrawPipeline::StandIn`) // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in @@ -2507,6 +2523,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if gfx && super::present::trace_frame() { trace_ui_draw(this, raw_pso, true); } + if gfx && super::present::trace_planes_from().is_some() { + trace_plane_draw(this, raw_pso, true); + } // (binds a compute root signature and a pipeline: before the dispatch's or draw's own) let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf); match bind_abi(this, list, pso, gfx, None, 0) { @@ -2857,6 +2876,9 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option if super::present::trace_frame() { trace_ui_draw(this, pso, false); } + if super::present::trace_planes_from().is_some() { + trace_plane_draw(this, pso, false); + } match bind_abi(this, &list, pso, true, None, 0) { Ok(_) => { super::targets::note_draw(this, super::targets::RAN); @@ -3106,6 +3128,50 @@ unsafe fn trace_ui_draw(this: *mut c_void, pso: usize, indirect: bool) { } } +/// `XCL_TRACE_PLANES=`: from that frame on, each pair of shaders that draws into a +/// presented resource is logged once with its root arguments (the first 80 pairs). +unsafe fn trace_plane_draw(this: *mut c_void, pso: usize, indirect: bool) { + let Some(from) = super::present::trace_planes_from() else { return }; + let frame = super::present::counters().1; + if frame < from { + return; + } + static WHY: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + let why = |k: usize, what: &str| { + let n = WHY[k].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 3 || n.is_power_of_two() { + crate::xlog_info!("plane trace: frame {frame} a draw on list {:#x} (pipeline {pso:#x}) is not traced: {what} (#{n})", this as usize); + } + }; + let Some(rt) = super::present::rt0_resource(this as usize) else { + why(0, "no render target 0 known for its list"); + return; + }; + if !super::present::is_presented(rt) { + return; + } + let (vs, ps) = match super::real::pso_shaders(super::pso_async::resolve(pso)) { + Some(x) => x, + None => { + why(2, "its pipeline has no known shaders"); + (0, pso as u64) + } + }; + static SEEN: Mutex> = Mutex::new(Vec::new()); + { + let mut g = SEEN.lock().unwrap(); + if g.len() >= 80 || g.contains(&(vs, ps, rt)) { + return; + } + g.push((vs, ps, rt)); + } + crate::xlog_info!( + "plane trace: frame {frame} draw into {rt:#x} (pipeline {pso:#x}, vs {vs:016x} ps {ps:016x}{}): {}", + if indirect { ", ExecuteIndirect" } else { "" }, + root_args_summary(this, 16) + ); +} + /// A draw's root arguments for the frame trace: constants, root buffers (their first words, as /// the CPU sees them), the first slots of descriptor tables (the PC resources they name). unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { @@ -3133,14 +3199,15 @@ unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { let slots: Vec = (0..slots) .map(|k| { let at = u.base() + t + 32 * k; - let w = super::console_heap::words_at((t + 32 * k) as u32); + let observed = super::console_heap::read_slot((t + 32 * k) as u32); + let w = observed.map(|(words, _)| words); // with `XCL_TRACE_SLOTS`: the image the T# describes (format, width, // height, first and last level of the view, levels of the texture, smallest // level of detail), the slot's own index in the shared heap, and the // resource the T#'s index names there – a T# the title copied as memory // carries its source slot's index, and samples whatever that slot holds now let image = w.filter(|_| more.is_some()).and_then(|w| crate::gpu::desc::image(&w)).map_or(String::new(), |t| { - let own = super::console_heap::slot(at as u64).map(|s| s.index); + let own = observed.and_then(|(_, index)| index); let named = super::console_heap::named_by_index(w.map_or(0, |w| w[0])); let nd = (named != 0 && named != super::console_heap::GONE).then(|| ID3D12Resource::from_raw_borrowed(&(named as *mut c_void)).map(|x| x.GetDesc())).flatten(); if nd.is_some() && super::title_textures::address(named).is_some() { @@ -3287,6 +3354,43 @@ fn bvh_builder_enabled() -> bool { *ON.get_or_init(|| std::env::var("XCL_BVH_BUILDER").is_ok_and(|v| v.trim() == "1")) } +/// `XCL_DIAG_VIEWS=1` turns on per-dispatch descriptor-table view tracking (off by default: +/// locks `HEAPS` and `DISPATCH_VIEWS` on every compute dispatch). +fn diag_views_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DIAG_VIEWS").is_ok_and(|v| v.trim() == "1")) +} + +/// The buffer descriptors (V#) in the first slots of a dispatch's descriptor tables, as the CPU +/// has them now: those in unified memory are written down (`real::note_dispatch_view`), so a +/// crash report can say which dispatches were given a view over an address. +unsafe fn note_dispatch_views(this: *mut c_void, pso: usize) { + if !diag_views_enabled() { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + let Some(layout) = layout else { return }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize); + if t == 0 { + continue; + } + for k in 0..8u32 { + let Some(w) = super::console_heap::words_at(t.wrapping_add(32 * k)) else { break }; + let base = ((w[1] as u64 & 0xFFFF) << 32) | w[0] as u64; + let stride = ((w[1] >> 16) & 0x3FFF) as u64; + let bytes = if stride == 0 { w[2] as u64 } else { w[2] as u64 * stride }; + if bytes == 0 || bytes > 1 << 30 || u.window_of(base as usize).is_none() { + continue; + } + super::real::note_dispatch_view(base, bytes, pso); + } + } +} + /// `Dispatch` / `DispatchX(x, y, z, flags)`. pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { if !bvh_builder_runs(flags, bvh_builder_enabled()) { @@ -3298,6 +3402,7 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f return; } let pso = with(this, |s| s.pso); + note_dispatch_views(this, pso); let _c = capture_work(this, || captured_dispatch(pso, [x, y, z], flags), false); // (recorded at the submit through this call, with everything below: counted there) if super::pso_async::waits_for(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z, flags)) { @@ -3450,6 +3555,7 @@ pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, s let align = align.max(16); if size <= crate::gpu::uma::ARENA_BLOCK / 2 { if let Some(p) = with(this, |s| s.arena.take(u, size, align, &mut s.uma)) { + crate::hle::kernelx::pagelog::note("upload memory given to the title (list arena)", p as usize, 0, size); return p; } } @@ -3605,12 +3711,14 @@ pub(super) unsafe fn rebind(this: *mut c_void, list: &ID3D12GraphicsCommandList, if gfx { list.SetGraphicsRootSignature(&b.rs); for (k, v) in b.views.iter().enumerate() { + super::real::note_root_view(list.as_raw() as usize, k as u32, *v); list.SetGraphicsRootUnorderedAccessView(k as u32, *v); } list.SetPipelineState(&b.pso); } else { list.SetComputeRootSignature(&b.rs); for (k, v) in b.views.iter().enumerate() { + super::real::note_root_view(list.as_raw() as usize, k as u32, *v); list.SetComputeRootUnorderedAccessView(k as u32, *v); } // (resolved here, and a compute pipeline has none of the state the hook of a title's call keeps) diff --git a/crates/xcl/src/hle/d3d12x/clamp.rs b/crates/xcl/src/hle/d3d12x/clamp.rs index d18cf537ea..5fa9a609f9 100644 --- a/crates/xcl/src/hle/d3d12x/clamp.rs +++ b/crates/xcl/src/hle/d3d12x/clamp.rs @@ -212,8 +212,11 @@ unsafe fn pass(list: &ID3D12GraphicsCommandList, args: usize, off: u64, io_limit list.SetComputeRoot32BitConstant(0, slot as u32, 0); // (as `bind::fold_counts_within` bounds the product) list.SetComputeRoot32BitConstant(0, most.saturating_add(crate::gpu::recomp::FOLD_X), 1); + super::real::note_root_view(list.as_raw() as usize, 1, res.GetGPUVirtualAddress() + off); list.SetComputeRootUnorderedAccessView(1, res.GetGPUVirtualAddress() + off); + super::real::note_root_view(list.as_raw() as usize, 2, c.gpu); list.SetComputeRootUnorderedAccessView(2, c.gpu); + super::real::note_root_view(list.as_raw() as usize, 3, io_limit); 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) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index ff6e744836..676a8dd27c 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -690,6 +690,65 @@ pub struct Slot { pub k: u32, } +/// A console slot looked up without reserving a page in the shared shader-visible heap: +/// used for descriptors whose shaders read UMA directly (CBVs, buffer V#s, BVH SRVs) and +/// never index into the shared PC heap. +#[derive(Clone, Copy, Debug)] +pub struct ShadowSlot { + pub at: usize, + pub pc_srv: u64, + pub pc_uav: u64, + pub sampler: bool, + /// Present only if the heap is unpaged or this page already has a place in the shared heap. + pub index: Option, + /// Non-zero only if this page already has a place in the shared heap. + pub shared_srv: u64, +} + +/// Whether `cpu` lies inside any registered console descriptor heap (without reserving a page). +pub fn contains(cpu: u64) -> bool { + let heaps = HEAPS.lock().unwrap(); + heaps.iter().any(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64) +} + +/// Look up the console slot behind `cpu` without reserving a page in the shared heap. +pub fn shadow_slot(cpu: u64) -> Option { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; + let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32; + if h.sampler { + let index = if h.pages.is_empty() { + Some(k) + } else { + h.pages.get((k / SAMPLER_PAGE_SLOTS) as usize).filter(|&&first| first != UNMAPPED).map(|&first| first + (k % SAMPLER_PAGE_SLOTS)) + }; + let shared_srv = index.filter(|_| !h.pages.is_empty()).and_then(|i| { + let g = GLOBAL_SAMPLER.lock().unwrap(); + let g = g.as_ref()?; + Some(g.cpu + i as u64 * g.inc as u64) + }).unwrap_or(0); + return Some(ShadowSlot { at: h.shadow + (k * SAMPLER_SLOT) as usize, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, sampler: true, index, shared_srv }); + } + let uav = ((2 * k + 1) * h.inc) as u64; + let index = if h.pages.is_empty() { + Some(2 * k) + } else { + h.pages.get((k / PAGE_SLOTS) as usize).filter(|&&first| first != UNMAPPED).map(|&first| first + 2 * (k % PAGE_SLOTS)) + }; + let shared_srv = index.filter(|_| !h.pages.is_empty()).and_then(|i| { + let g = GLOBAL.lock().unwrap(); + let g = g.as_ref()?; + Some(g.cpu + i as u64 * g.inc as u64) + }).unwrap_or(0); + Some(ShadowSlot { at: h.shadow + (k * SLOT) as usize, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, sampler: false, index, shared_srv }) +} + +/// Write descriptor words into a console slot looked up via `shadow_slot`. +pub fn write_shadow(s: &ShadowSlot, words: &[u32]) { + let n = words.len().min(if s.sampler { 4 } else { 8 }); + unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), s.at as *mut u32, n) }; +} + /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot /// of a heap in the shared heap gets its page's place there now if the page has none yet; one /// whose page finds no room there gets index 0, the null SRV / UAV pair. @@ -933,11 +992,30 @@ pub fn census() { /// The descriptor at a console GPU address (low 32 bits, as in a descriptor table), if it /// is in one of the console heaps. pub fn words_at(addr32: u32) -> Option<[u32; 8]> { - let u = crate::gpu::uma::get()?; - let s = slot((u.base() + addr32 as usize) as u64)?; - let mut w = [0u32; 8]; - unsafe { std::ptr::copy_nonoverlapping(s.at as *const u32, w.as_mut_ptr(), if s.sampler { 4 } else { 8 }) }; - Some(w) + let (words, _) = read_slot(addr32)?; + Some(words) +} + +/// Read guest memory and the slot's current PC index without allocating a page in the +/// shader-visible heap. A title can fill these slots by ordinary memory copies; inspecting +/// their words does not publish a new PC view. +pub(super) fn read_slot(addr32: u32) -> Option<([u32; 8], Option)> { + let at = crate::gpu::uma::get()?.base().checked_add(addr32 as usize)?; + let heaps = HEAPS.lock().unwrap(); + let (h, k) = heaps.iter().find_map(|h| { + let k = at.checked_sub(h.shadow)? / h.slot_bytes() as usize; + (k < h.n as usize).then_some((h, k as u32)) + })?; + let stride = h.slot_bytes() as usize; + let mut words = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping((h.shadow + k as usize * stride) as *const u32, words.as_mut_ptr(), stride / 4) }; + let index = if h.pages.is_empty() { + Some(if h.sampler { k } else { 2 * k }) + } else { + let (page, step) = if h.sampler { (SAMPLER_PAGE_SLOTS, 1) } else { (PAGE_SLOTS, 2) }; + h.pages.get((k / page) as usize).filter(|&&first| first != UNMAPPED).map(|first| first + step * (k % page)) + }; + Some((words, index)) } // --------------------------------------------------------------------------------------- @@ -1481,6 +1559,15 @@ mod tests { assert!(register(0xC1, 2 * PAGE_SLOTS, 0x30_0000, 0, 32, false, true, true)); assert!(register(0xC2, 16, 0x40_0000, 0, 32, false, true, true)); let (a, b) = (start(0xC1).unwrap(), start(0xC2).unwrap()); + // The dispatch trace inspects tables the title wrote directly. No PC descriptors + // have been published for this page, even after inspecting it. + assert_eq!(read_slot(rel(a + (PAGE_SLOTS * SLOT) as u64)), Some(([0; 8], None))); + assert!(contains(a + (PAGE_SLOTS * SLOT) as u64)); + let sh = shadow_slot(a + (PAGE_SLOTS * SLOT) as u64).unwrap(); + assert_eq!(sh.index, None); + assert_eq!(sh.shared_srv, 0); + write_shadow(&sh, &[1, 2, 3, 4]); + assert_eq!(PAGES_PLACED.load(Relaxed), 0); let placed = slot(a + 2 * SLOT as u64).unwrap(); assert_eq!(placed.index, base + 4, "page 0 of the first heap takes the room there is"); assert_ne!(placed.shared_srv, 0); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index b623dd876c..625f315b9f 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -680,7 +680,60 @@ pub fn pc_pso(pso: *mut c_void) -> *mut c_void { unsafe { (*(pso as *const ConsolePso)).pc as *mut c_void } } +/// How long what a finished recording held (unified-memory blocks, two-pass buffers) waits +/// before it is used again or let go, from when its allocator's reset said the GPU was done with +/// it (`XCL_RETIRE_MS`, 2000 by default; 0: at once). A retail title resets its allocators with +/// work still on the GPU about a hundred times a second in its world, and a block handed to the +/// next recording at once was written while a list still read it whenever that bookkeeping +/// missed a submit: its dispatch arguments over the title's own objects in upload memory (CPU +/// crashes on a vtable of `{groups, 1, 1, 0}`), and stale arguments and addresses for the GPU +/// (page faults at addresses no resource is at, device removals). +pub(super) fn retire_age() -> std::time::Duration { + #[cfg(test)] + { + std::time::Duration::ZERO + } + #[cfg(not(test))] + { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + std::time::Duration::from_millis(*MS.get_or_init(|| std::env::var("XCL_RETIRE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2000))) + } +} + +/// unified-memory blocks waiting out `retire_age`, oldest first +static RETIRED: Mutex> = Mutex::new(std::collections::VecDeque::new()); +/// committed unified memory left under which the oldest retired blocks go back early +const RETIRE_ROOM: usize = 96 << 20; + unsafe fn free_uma(blocks: &[usize]) { + let age = retire_age(); + if age.is_zero() { + return free_uma_now(blocks); + } + let now = std::time::Instant::now(); + let ready: Vec = { + let mut g = RETIRED.lock().unwrap(); + g.extend(blocks.iter().map(|&b| (now, b))); + let mut out = Vec::new(); + while g.front().is_some_and(|&(at, _)| now.saturating_duration_since(at) >= age) { + out.push(g.pop_front().unwrap().1); + } + // (draws with no room for their arguments are skipped: before that, the oldest go back) + if out.is_empty() && !g.is_empty() && crate::gpu::uma::get().is_some_and(|u| u.committed_state().0 < RETIRE_ROOM) { + let n = g.len().min(64); + out.extend(g.drain(..n).map(|e| e.1)); + static EARLY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = EARLY.fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed) + n as u64; + if (k / 64).is_power_of_two() { + crate::xlog_warn!("D3D12.X: {k} retired unified-memory blocks so far given back before {} ms: committed unified memory is under {} MB free", age.as_millis(), RETIRE_ROOM >> 20); + } + } + out + }; + free_uma_now(&ready); +} + +unsafe fn free_uma_now(blocks: &[usize]) { if let Some(u) = crate::gpu::uma::get() { for &b in blocks { if u.is_sparse(b) { @@ -985,10 +1038,13 @@ pub unsafe fn close(obj: *mut c_void) -> Result { None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), } ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap); + super::real::note_root_view(list.as_raw() as usize, 0, va(io_at)); list.SetComputeRootUnorderedAccessView(0, va(io_at)); + super::real::note_root_view(list.as_raw() as usize, 1, va(res_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); // (every window slot gets a buffer: direct DXIL compute reads all four, as in `bind`) for k in 0..4 { + super::real::note_root_view(list.as_raw() as usize, 2 + k as u32, windows.get(k).copied().filter(|&v| v != 0).unwrap_or(uma_va)); list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().filter(|&v| v != 0).unwrap_or(uma_va)); } let raw = real as *mut c_void; diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 5ebbb70da6..c26aa71296 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -137,6 +137,7 @@ unsafe fn write_now_in(va: usize, words: &[u32], run: &dyn Fn(usize, usize) -> O for (i, &w) in words.iter().enumerate() { (*((va + 4 * i) as *const AtomicU32)).store(w, Ordering::Release); } + crate::hle::kernelx::pagelog::note("list immediate written by the CPU after its submit", va, 0, bytes); note_placed(asked, va, bytes); } @@ -176,6 +177,7 @@ unsafe fn write_u64_now(va: usize, value: u64) { let (asked, va) = (va, cpu_at(va)); if u64_writable_now(va) { (*(va as *const AtomicU64)).store(value, Ordering::Release); + crate::hle::kernelx::pagelog::note("list 64-bit value written by the CPU after its submit", va, 0, 8); note_placed(asked, va, 8); } } @@ -188,6 +190,7 @@ pub(super) unsafe fn max_u64_now(va: usize, value: u64) { let (asked, va) = (va, cpu_at(va)); if u64_writable_now(va) { (*(va as *const AtomicU64)).fetch_max(value, Ordering::AcqRel); + crate::hle::kernelx::pagelog::note("list 64-bit value raised by the CPU", va, 0, 8); note_placed(asked, va, 8); } } @@ -199,7 +202,7 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } - crate::hle::kernelx::lazy::ensure(va, bytes); + let _opened = crate::hle::kernelx::lazy::ensure(va, bytes); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 5f750bf5be..f3b6100532 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -17,7 +17,8 @@ //! the shaders wrote reaches the next depth test or sampling). A transition names the state it //! leaves and the one it enters, so each copy starts and ends in states the title gave. //! -//! Behind `XCL_DEPTH_UAV_TWIN=1`; with the switch off nothing is registered, a UAV of a depth +//! On unless `XCL_DEPTH_UAV_TWIN=0` (a title that names layouts moves its buffers through +//! `barrier_groups`, whose transitions reach `plan_barriers`); with the switch off nothing is registered, a UAV of a depth //! buffer stays a null view and every hook stops at one atomic load. //! //! (After the depth+UAV twins of xcl-dev/xcl#1989 by raylitebull: registering at creation, DSVs, @@ -40,7 +41,7 @@ use windows::Win32::Graphics::Dxgi::Common::*; use super::sharded::Sharded; /// The switch's value when `XCL_DEPTH_UAV_TWIN` is not set. -const DEFAULT_ON: bool = false; +const DEFAULT_ON: bool = true; /// Whether depth buffers with unordered access are kept (`XCL_DEPTH_UAV_TWIN`). pub(super) fn enabled() -> bool { @@ -115,6 +116,10 @@ struct Twin { res: ID3D12Resource, /// its number in the log (`#n`) n: u64, + /// a stencil plane's twin: the buffer the two are copied through (no colour format shares + /// a family with a depth-stencil one, but the PC copies between a buffer and one plane); + /// it rests in COPY_DEST + through: Option, } // D3D12 resources are free-threaded @@ -375,7 +380,8 @@ unsafe fn plane_twin(o: &Object, plane: usize, dev: *mut c_void) -> Option<(ID3D let t = make_twin(dev, &key, twin_format(key.format, o.cell.console_format, plane))?; TWINS.fetch_add(1, Ordering::Relaxed); let n = MADE.fetch_add(1, Ordering::Relaxed) + 1; - inner.twins[plane] = Some(Twin { res: t.clone(), n }); + let through = if plane == 1 { make_through(dev, &key) } else { None }; + inner.twins[plane] = Some(Twin { res: t.clone(), n, through }); o.cell.twinned.store(true, Ordering::Relaxed); // (the state of the title's object; that of the UAV's own when the title made none) let state = inner.made_in.unwrap_or(o.state); @@ -451,9 +457,30 @@ pub(super) struct PlaneCopy { pub mips: u16, } +/// A copy between stencil plane subresources of a title's object and the same ones of the +/// stencil twin, through the twin's buffer. +pub(super) struct StencilCopy { + /// the object the title's transition names + pub depth: usize, + /// the stencil plane's subresources it copies, as the twin numbers them (the buffer's are + /// these + `first`) + pub subs: Vec, + /// the buffer's first stencil plane subresource + pub first: u32, + pub twin: ID3D12Resource, + pub through: ID3D12Resource, + pub width: u32, + pub height: u32, + pub mips: u16, +} + /// What goes on the PC list with a title's barriers (`plan_barriers`). #[derive(Default)] pub(super) struct Plan { + /// before them, and before `to_plane`: stencil twins into stencil planes (the buffer in PARK) + pub stencil_to_plane: Vec, + /// after them, and after `to_twin`: stencil planes into their twins (the buffer in PARK) + pub stencil_to_twin: Vec, /// before them: twins into depth planes (the buffer goes PARK → COPY_DEST / DEPTH_WRITE, the /// title's transition takes it on from there; the twin UNORDERED_ACCESS → COPY_SOURCE/SRV and back) pub to_plane: Vec, @@ -531,6 +558,32 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, } let key = o.cell.key; let r24g8_steps = (key.format == 44).then(|| matches!(o.cell.console_format, 118..=120)); + // the stencil plane's subresources the transition names, and its twin when shaders were + // given one: what they store there (a title's masks for its lighting) reaches the plane + // on the way out of UNORDERED_ACCESS, and what was drawn into the plane reaches the twin + // on the way in + let stencil_subs: Vec = if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { (0..n).collect() } else { (sub >= n && sub < 2 * n).then_some(sub - n).into_iter().collect() }; + let stencil = (direct && !stencil_subs.is_empty() && matches!(key.format, 19 | 44)).then(|| stencil_twin_if_made(&o)).flatten().map(|(twin, through)| StencilCopy { + depth: res, + subs: stencil_subs, + first: n, + twin, + through, + width: key.width, + height: key.height, + mips: key.mips.max(1), + }); + if let Some(s) = stencil { + let c = STENCIL_COPIES[leaving as usize].fetch_add(1, Ordering::Relaxed) + 1; + if c <= 2 || c.is_power_of_two() { + crate::xlog_info!("D3D12.X: depth UAV twin: the stencil plane of depth buffer {res:#x} ({}x{}) and its twin: {} ({c} such copies so far)", key.width, key.height, if leaving { "the twin is copied into the plane on the way out of UNORDERED_ACCESS" } else { "the plane is copied into the twin on the way into UNORDERED_ACCESS" }); + } + if leaving { + plan.stencil_to_plane.push(s); + } else { + plan.stencil_to_twin.push(s); + } + } if leaving { before = PARK; // (a twin whose last way in was not copied holds something else than the plane: not @@ -607,6 +660,57 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, plan } +/// Copies of a stencil plane into its twin, and of a twin into its plane. +static STENCIL_COPIES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// Copies of stencil planes into their twins, and of twins into their planes, so far. +pub(super) fn stencil_copies() -> (u64, u64) { + (STENCIL_COPIES[0].load(Ordering::Relaxed), STENCIL_COPIES[1].load(Ordering::Relaxed)) +} + +/// The stencil twin of `o`'s buffer and the buffer the two are copied through, when it has both. +fn stencil_twin_if_made(o: &Object) -> Option<(ID3D12Resource, ID3D12Resource)> { + let inner = o.cell.inner.lock().unwrap(); + let t = inner.twins[1].as_ref()?; + Some((t.res.clone(), t.through.clone()?)) +} + +/// The row pitch of an 8-bit plane `width` texels wide in a buffer (D3D12_TEXTURE_DATA_PITCH_ALIGNMENT). +pub(super) fn stencil_pitch(width: u32) -> u32 { + width.max(1).next_multiple_of(256) +} + +/// The buffer a stencil plane of `key`'s shape and its twin are copied through: room for the +/// largest subresource (one is copied at a time), resting in COPY_DEST. +unsafe fn make_through(dev: *mut c_void, key: &Key) -> Option { + if dev.is_null() { + return None; + } + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (stencil_pitch(key.width) as u64 * key.height.max(1) as u64).next_multiple_of(0x1_0000), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut out = std::ptr::null_mut(); + let hr = super::real::dev_create_committed_resource( + dev, + &heap as *const _ as usize, + 0, + &desc as *const _ as usize, + D3D12_RESOURCE_STATE_COPY_DEST.0 as usize, + 0, + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut out, + ); + (hr >= 0 && !out.is_null()).then(|| ID3D12Resource::from_raw(out)) +} + /// The depth twin of `o`'s buffer when it has one, and its number. fn twin_if_made(o: &Object) -> Option<(ID3D12Resource, u64)> { o.cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n)) @@ -1220,10 +1324,9 @@ fn plane_view(view: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, array: u16) -> D3 v } -/// (tests) Whether `res` is kept. -#[cfg(test)] +/// Whether `res` is kept (`barrier_groups`: its way into UNORDERED_ACCESS is `plan_barriers`'s). pub(super) fn kept(res: usize) -> bool { - OBJECTS.contains(res) + any_kept() && OBJECTS.contains(res) } /// (tests) The state line L2 gives for the buffer `res` is in, and whether that buffer has a @@ -1707,7 +1810,7 @@ mod tests { { let o = OBJECTS.get(buffer).unwrap(); TWINS.fetch_add(1, Ordering::Relaxed); - o.cell.inner.lock().unwrap().twins[1] = Some(Twin { res: unsafe { ID3D12Resource::from_raw(fake) }, n: 0 }); + o.cell.inner.lock().unwrap().twins[1] = Some(Twin { res: unsafe { ID3D12Resource::from_raw(fake) }, n: 0, through: None }); } let t = fake as usize; let before = clears(); @@ -1738,7 +1841,7 @@ mod tests { fn plant_depth_twin(res: usize, t: &ID3D12Resource) { let o = OBJECTS.get(res).unwrap(); TWINS.fetch_add(1, Ordering::Relaxed); - o.cell.inner.lock().unwrap().twins[0] = Some(Twin { res: t.clone(), n: 0 }); + o.cell.inner.lock().unwrap().twins[0] = Some(Twin { res: t.clone(), n: 0, through: None }); } fn tr(res: usize, sub: u32, before: u32, after: u32) -> [u32; 8] { diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index c8affa6ee3..8354827920 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -759,6 +759,13 @@ pub(super) unsafe fn pc_resource_desc_for_device(device: *mut c_void, x: &[u8; 0 strip_unsupported_uav_for_device(device, pc_resource_desc(x)) } +/// Whether an sRGB texture with unordered access is made typeless (`pc_resource_desc`): only +/// with `XCL_SRGB_UAV=1` (a retail title's world was not seen to look right with it yet). +fn srgb_uav() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SRGB_UAV").is_ok_and(|v| v.trim() == "1")) +} + /// the console resource desc (0x38 bytes, D3D12_RESOURCE_DESC) as a PC one: its tile layouts /// and console flag bits mean nothing to a PC driver pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { @@ -798,6 +805,14 @@ pub fn pc_resource_desc(x: &[u8; 0x38]) -> [u8; 0x38] { if format == 67 && flags & 5 != 0 { d[0x20..0x24].copy_from_slice(&26u32.to_le_bytes()); } + // an sRGB texture the console also lets shaders write (a retail title's G-buffer colour, a + // render target and a UAV): the PC has no unordered access for an sRGB format – typeless, + // so the title's sRGB views and a linear UAV of the same bytes both fit + // (`pc_shader_view_format`, `pc_uav_linear_format`) + let samples_x = u32::from_le_bytes(d[0x24..0x28].try_into().unwrap()); + if matches!(format, 29 | 91) && flags & 4 != 0 && flags & 2 == 0 && samples_x <= 1 && dim != D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32 && srgb_uav() { + d[0x20..0x24].copy_from_slice(&(if format == 29 { 27u32 } else { 90u32 }).to_le_bytes()); + } // a depth buffer the console also lets shaders write (a retail game's: ALLOW_DEPTH_STENCIL | // ALLOW_UNORDERED_ACCESS): the PC refuses the pair – the depth buffer stays if flags & 2 != 0 { @@ -896,6 +911,10 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { (87, 88) => 87, // a target made R11G11B10_FLOAT (`pc_resource_desc`) (26, 67) => 26, + // an sRGB texture with unordered access made typeless (`pc_resource_desc`): the view the + // title gave no format is the sRGB one (a UAV: `pc_uav_linear_format` of it) + (27, 0 | 27) => 29, + (90, 0 | 90) => 91, (_, v) => v, } } @@ -1493,7 +1512,7 @@ mod tests { 103, 107, // YUV (NV12, YUY2) ] { let (out_fmt, out_flags) = make(3, fmt, 1, 0x4); - if matches!((fmt, out_fmt), (85, 28) | (88, 87)) { + if matches!((fmt, out_fmt), (85, 28) | (88, 87) | (29, 27) | (91, 90)) { // promoted to a format a PC driver takes as a UAV of the same values: the flag // stays, and is valid there assert_eq!(out_flags & 0x4, 0x4, "format {fmt} promoted to {out_fmt} keeps ALLOW_UNORDERED_ACCESS"); @@ -1502,6 +1521,16 @@ mod tests { assert_eq!(out_flags & 0x4, 0, "format {fmt} must strip ALLOW_UNORDERED_ACCESS"); } } + // an sRGB render target with unordered access is typeless with both flags; without + // unordered access, multisampled or a depth buffer it stays what it is + if srgb_uav() { + assert_eq!((make(3, 29, 1, 0x5), make(3, 91, 1, 0x5)), ((27, 0x5), (90, 0x5))); + } else { + assert_eq!((make(3, 29, 1, 0x5), make(3, 91, 1, 0x5)), ((29, 0x1), (91, 0x1))); + } + assert_eq!((make(3, 29, 1, 0x1), make(3, 29, 4, 0x5)), ((29, 0x1), (29, 0x1))); + assert_eq!((pc_shader_view_format(27, 0), pc_shader_view_format(27, 29), pc_shader_view_format(27, 28), pc_shader_view_format(90, 0)), (29, 29, 28, 91)); + assert_eq!(pc_uav_linear_format(pc_shader_view_format(27, 0)), 28, "its UAV is the linear one"); // Multisampled textures never support UAV even on UAV-capable formats: assert_eq!(make(3, 28, 4, 0x5), (28, 0x1)); assert_eq!(make(3, 27, 2, 0x4), (27, 0x0)); diff --git a/crates/xcl/src/hle/d3d12x/gpu_awake.rs b/crates/xcl/src/hle/d3d12x/gpu_awake.rs index ecca7a012f..a6b3fbdc04 100644 --- a/crates/xcl/src/hle/d3d12x/gpu_awake.rs +++ b/crates/xcl/src/hle/d3d12x/gpu_awake.rs @@ -285,6 +285,7 @@ unsafe fn init_state(device: &ID3D12Device) -> Result { .map_err(|e| format!("CreateCommandList(COMPUTE) failed: {e}"))?; list.SetComputeRootSignature(&root_sig); list.SetPipelineState(&pso); + super::real::note_root_view(list.as_raw() as usize, 0, uav_va); list.SetComputeRootUnorderedAccessView(0, uav_va); list.Dispatch(1, 1, 1); list.Close().map_err(|e| format!("CommandList::Close failed: {e}"))?; diff --git a/crates/xcl/src/hle/d3d12x/indirect_guard.rs b/crates/xcl/src/hle/d3d12x/indirect_guard.rs index 1921a0946f..435776e5b6 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_guard.rs +++ b/crates/xcl/src/hle/d3d12x/indirect_guard.rs @@ -352,9 +352,13 @@ pub(super) unsafe fn check(list: *mut c_void, pso: usize, sig: usize, max: u32, let at = title.map_or(va, |t| t as u64); let constants = [max_groups(), slot, id as u32, (id >> 32) as u32, at as u32, (at >> 32) as u32, kind as u32]; l.SetComputeRoot32BitConstants(0, constants.len() as u32, constants.as_ptr() as *const c_void, 0); + super::real::note_root_view(l.as_raw() as usize, 1, va); l.SetComputeRootUnorderedAccessView(1, va); + super::real::note_root_view(l.as_raw() as usize, 2, g.out_va); l.SetComputeRootUnorderedAccessView(2, g.out_va); + super::real::note_root_view(l.as_raw() as usize, 3, g.seen_va); l.SetComputeRootUnorderedAccessView(3, g.seen_va); + super::real::note_root_view(l.as_raw() as usize, 4, shown); l.SetComputeRootUnorderedAccessView(4, shown); l.Dispatch(1, 1, 1); report(&g); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 7dc8182acc..fcc773e722 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1261,6 +1261,7 @@ fn pick_queue(last_queue: Option, device: usize, ty: D3D12_COMMAND_LIST_T } fn note_write(list: usize, va: u64, size: u64) { + crate::hle::kernelx::pagelog::note("list memory write recorded (the GPU writes it)", va as usize, 0, size as usize); recording(list).lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); } @@ -1799,6 +1800,7 @@ unsafe fn publish_cpu_cycle_break_with(va: u64, val: u64, uma: Option<&crate::gp if uma.is_some_and(|u| u.is_sparse(addr)) { return; } + crate::hle::kernelx::pagelog::note("Write64 value published by the CPU (cycle break)", addr, 0, 8); if uma.is_some_and(|u| u.in_committed_window(addr, 8)) { (*(addr as *const AtomicU64)).fetch_max(val, Ordering::AcqRel); } else { @@ -3675,6 +3677,17 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, ba }, }; pc::(this, PC_RESOURCE_BARRIER)(this, 1, &b); + barrier_groups_log(n, barriers); + // the title's texture barriers as transitions (`barrier_groups`), which go the way its + // ResourceBarrier calls go: the format aliases and the depth twins are kept from there + if super::barrier_groups::enabled() { + let moves = super::barrier_groups::transitions(n, barriers, list_type(this) == D3D12_COMMAND_LIST_TYPE_DIRECT); + if !moves.is_empty() { + resource_barrier_x(this, moves.len() as u32, moves.as_ptr()); + } + super::format_alias::on_uav_barrier(this, None); + return; + } let mut alias_writers: Vec<(usize, u32)> = Vec::new(); super::format_alias::filter_enhanced_barriers(n, barriers, &mut alias_writers); if !alias_writers.is_empty() { @@ -3683,6 +3696,58 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, ba super::format_alias::on_uav_barrier(this, None); } +/// `XCL_BARRIER_LOG=1`: what the title's #146 calls hold, as barrier groups – calls, and the +/// texture barriers by (layout before → after, access before → after, depth buffer or not), +/// logged at each power of two of calls. +unsafe fn barrier_groups_log(n: u32, groups: *const c_void) { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_BARRIER_LOG").is_ok_and(|v| v.trim() == "1")) { + return; + } + static CALLS: AtomicU64 = AtomicU64::new(0); + static KINDS: Mutex>> = Mutex::new(None); + let calls = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + let mut g = KINDS.lock().unwrap(); + let kinds = g.get_or_insert_with(HashMap::new); + let count = (n as usize).min(64); + if !groups.is_null() && count != 0 && crate::gpu::shader::readable(groups as usize, count * std::mem::size_of::()) { + for grp in std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, count) { + let nb = (grp.NumBarriers as usize).min(1024); + let p = grp.Anonymous.pTextureBarriers; + if grp.Type != D3D12_BARRIER_TYPE_TEXTURE { + *kinds.entry((grp.Type.0 as u32, 0, 0, 0, 0, false)).or_default() += nb as u64; + continue; + } + if p.is_null() || !crate::gpu::shader::readable(p as usize, nb * std::mem::size_of::()) { + *kinds.entry((99, 0, 0, 0, 0, false)).or_default() += 1; + continue; + } + for tb in std::slice::from_raw_parts(p, nb) { + let res: usize = transmute_copy(&tb.pResource); + let depth = res != 0 && readable_resource(res).is_some_and(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0); + *kinds.entry((1, tb.LayoutBefore.0 as u32, tb.LayoutAfter.0 as u32, tb.AccessBefore.0 as u32, tb.AccessAfter.0 as u32, depth)).or_default() += 1; + } + } + } else { + *kinds.entry((98, n, 0, 0, 0, false)).or_default() += 1; + } + if calls.is_power_of_two() && calls >= 16 { + let mut v: Vec<_> = kinds.iter().map(|(k, c)| (*c, *k)).collect(); + v.sort_unstable_by(|a, b| b.cmp(a)); + let text: Vec = v.iter().take(24).map(|(c, (ty, lb, la, ab, aa, depth))| format!("{c}x type {ty} layout {lb:#x}->{la:#x} access {ab:#x}->{aa:#x}{}", if *depth { " (depth)" } else { "" })).collect(); + crate::xlog_info!("D3D12.X: #146 barrier groups: {calls} calls, {} kinds: {}", v.len(), text.join("; ")); + } +} + +/// The description of the PC resource a barrier names at `res` (as `is_buffer` reads one). +unsafe fn readable_resource(res: usize) -> Option { + if !crate::gpu::shader::readable(res, 8) { + return None; + } + let r = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&r).map(|x| x.GetDesc()) +} + /// A UAV barrier for all resources on `list`, where a list takes one (a copy list and a bundle /// do not). unsafe fn flush_barrier(list: *mut c_void) { @@ -4260,12 +4325,33 @@ fn pc_va(va: u64) -> u64 { } } +/// Diagnostic: an address the title gave that is not in unified memory goes to the PC as it is. +/// When it is the title's ordinary memory (the CPU can read it) the PC's GPU has nothing there: +/// a page fault at that very address and a device removal. The first ones are logged with the +/// calls that led here. +fn note_cpu_address_as_gpu(va: u64) { + static N: AtomicU64 = AtomicU64::new(0); + // (below the unified-memory windows: where a retail title keeps its ordinary heaps) + if va < 0x1_0000_0000 || va >= 0x10_0000_0000 || !crate::gpu::shader::readable(va as usize, 16) { + return; + } + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 6 { + crate::xlog_error!("D3D12.X: the title's ordinary memory at {va:#x} goes to the GPU as an address (#{n}): {}", std::backtrace::Backtrace::force_capture().to_string().lines().filter(|l| l.contains("xcl::") || l.contains("game_")).take(14).map(|l| l.trim()).collect::>().join(" < ")); + } else if n.is_power_of_two() { + crate::xlog_error!("D3D12.X: the title's ordinary memory went to the GPU as an address {n} times so far (now {va:#x})"); + } +} + /// `pc_va` in `u`, whose windows have the PC addresses `window_va` (`real::uma_window_va`). A /// GPU view of the title's memory without a PC address of its window gets none (0, read as /// nothing): as it is, the console address is no PC address and hangs the device. fn pc_va_in(u: &crate::gpu::uma::Uma, va: u64, window_va: impl Fn(usize) -> Option) -> u64 { let p = va as usize; - let Some(k) = u.window_of(p).filter(|_| u.is_title_address(p)) else { return va }; + let Some(k) = u.window_of(p).filter(|_| u.is_title_address(p)) else { + note_cpu_address_as_gpu(va); + return va; + }; match window_va(k) { Some(w) => w + (p - u.window(k).0) as u64, None if u.is_view_window(k) => 0, @@ -4935,6 +5021,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } }); if let Some(p) = &plane_copies { + stencil_copies_on(this, &p.stencil_to_plane, false); plane_copies_on(this, &p.to_plane, false); } if !out.is_empty() { @@ -4942,6 +5029,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } if let Some(p) = &plane_copies { plane_copies_on(this, &p.to_twin, true); + stencil_copies_on(this, &p.stencil_to_twin, true); } if !alias_writers.is_empty() { super::format_alias::sync_title_writers(this, &alias_writers); @@ -4952,6 +5040,53 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } } +/// The copies between stencil planes and their twins around a title's barriers +/// (`depth_uav::plan_barriers`) on `list`, through each twin's buffer: into the twins +/// (`to_twin`) or into the planes. The depth buffer rests in `depth_uav::PARK` (COPY_SOURCE) +/// before and after, the twin in UNORDERED_ACCESS, the buffer in COPY_DEST. Whole subresources +/// (a D3D12 copy of a stencil plane takes the whole of it). +unsafe fn stencil_copies_on(list: *mut c_void, copies: &[super::depth_uav::StencilCopy], to_twin: bool) { + let barriers = |b: &[[u32; 8]]| pc::(list, PC_RESOURCE_BARRIER)(list, b.len() as u32, b.as_ptr()); + let tr = |res: usize, sub: u32, before: u32, after: u32| [0, 0, res as u32, (res as u64 >> 32) as u32, sub, before, after, 0]; + let all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + let at = |res: usize, k: u32| D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&res), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k } }; + let copy = pc::(list, PC_COPY_TEXTURE_REGION); + let (copy_src, copy_dst) = (D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32); + for c in copies { + let (twin, through) = (c.twin.as_raw() as usize, c.through.as_raw() as usize); + let mips = c.mips.max(1) as u32; + for &k in &c.subs { + let m = k % mips; + let (w, h) = ((c.width >> m).max(1), (c.height >> m).max(1)); + let placed = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&through), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R8_TYPELESS, Width: w, Height: h, Depth: 1, RowPitch: super::depth_uav::stencil_pitch(w) }, + }, + }, + }; + let plane = c.first + k; + if to_twin { + // plane → buffer → twin + copy(list, &placed, 0, 0, 0, &at(c.depth, plane), std::ptr::null()); + barriers(&[tr(through, all, copy_dst, copy_src), tr(twin, k, UNORDERED_ACCESS, copy_dst)]); + copy(list, &at(twin, k), 0, 0, 0, &placed, std::ptr::null()); + barriers(&[tr(twin, k, copy_dst, UNORDERED_ACCESS), tr(through, all, copy_src, copy_dst)]); + } else { + // twin → buffer → plane + barriers(&[tr(twin, k, UNORDERED_ACCESS, copy_src)]); + copy(list, &placed, 0, 0, 0, &at(twin, k), std::ptr::null()); + barriers(&[tr(twin, k, copy_src, UNORDERED_ACCESS), tr(through, all, copy_dst, copy_src), tr(c.depth, plane, super::depth_uav::PARK, copy_dst)]); + copy(list, &at(c.depth, plane), 0, 0, 0, &placed, std::ptr::null()); + barriers(&[tr(c.depth, plane, copy_dst, super::depth_uav::PARK), tr(through, all, copy_src, copy_dst)]); + } + } + } +} + /// The copies between depth planes and their twins around a title's barriers /// (`depth_uav::plan_barriers`) on `list`: into the twins (`to_twin`, after the barriers: the /// buffer rests in `depth_uav::PARK`, COPY_SOURCE) or into the planes (before them: the buffer @@ -5090,6 +5225,7 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds if let Some(d) = dst.as_ref() { let r: usize = transmute_copy(&d.pResource); super::present::note_use(r, super::present::USE_COPY); + super::present::trace_plane_copy("CopyTextureRegion", r, src.as_ref().map_or(0, |s| transmute_copy(&s.pResource))); super::placements::note_use(r); if let Some(s) = src.as_ref() { super::placements::note_use(transmute_copy(&s.pResource)); @@ -5328,6 +5464,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds Some(c::Op::Resolve { dst: c::describe(dst), dst_sub, src: c::describe(src), src_sub, format, region: None }) }); super::present::note_use(dst, super::present::USE_COPY); + super::present::trace_plane_copy("ResolveSubresource", dst, src); super::title_textures::note_gpu_write(this as usize, dst); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) @@ -5359,6 +5496,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi Some(c::Op::Copy { kind: "resource", dst: c::buffer(dst, 0), src: c::buffer(src, 0), at: [0; 3], bx: None, bytes: None, refused: false }) }); super::present::note_use(dst, super::present::USE_COPY); + super::present::trace_plane_copy("CopyResource", dst, src); super::placements::note_use(dst); super::placements::note_use(src); super::title_textures::note_gpu_write(this as usize, dst); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 4bfe7c7437..c5e01c8b57 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -17,6 +17,7 @@ pub mod console_heap; pub mod console_list; pub mod clamp; mod ambient; +mod barrier_groups; mod depth_uav; mod format_alias; pub mod device_x; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 4941f9329d..bffbce31dc 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -66,6 +66,12 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl 0 } +/// `XCL_PRESENT_PLANE=`: the one plane shown (None: all of them, composed) +fn present_plane_only() -> Option { + static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); + *ONLY.get_or_init(|| std::env::var("XCL_PRESENT_PLANE").ok().and_then(|v| v.trim().parse().ok())) +} + const PLANE_STRIDE: usize = 0x48; const MAX_PLANES: usize = 8; @@ -145,6 +151,44 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u } } let extracted = extract_planes(plane_count, planes); + { + // which resources the planes show, when a plane shows one it has not shown before + // (the first 24 times) + static SHOWN: Mutex> = Mutex::new(Vec::new()); + let mut shown = SHOWN.lock().unwrap(); + for (i, &(res, rect)) in extracted.iter().enumerate() { + if !shown.contains(&(i, res)) && shown.len() < 24 { + shown.push((i, res)); + let raw = res as *mut c_void; + let desc = ID3D12Resource::from_raw_borrowed(&raw).map(|r| r.GetDesc()); + crate::xlog_info!( + "D3D12.X: PresentX frame {frames}: plane {i} shows {res:#x} for the first time: {:?}, source rect {rect:?}, the title's address {:x?}, words {:x?}", + desc.map(|d| (d.Width, d.Height, d.Format.0, d.Flags.0)), + super::real::title_address(res), + (0..PLANE_STRIDE / 8).map(|k| (planes.add(i * PLANE_STRIDE) as *const u64).add(k).read_unaligned()).collect::>() + ); + } + } + } + if let Some(from) = trace_planes() { + static LAST: Mutex>> = Mutex::new(None); + let now: HashMap = USES.lock().unwrap().clone().unwrap_or_default(); + let mut last = LAST.lock().unwrap(); + if frames >= from && frames < from + 600 { + for (i, &(res, _)) in extracted.iter().enumerate() { + let n = now.get(&res).copied().unwrap_or_default(); + let o = last.as_ref().and_then(|m| m.get(&res).copied()).unwrap_or_default(); + crate::xlog_info!( + "plane trace: frame {frames} plane {i} {res:#x}: since the last present rt binds {}, UAV views {}, copy destination {}, clears {}", + n[0] - o[0], + n[1] - o[1], + n[2] - o[2], + n[3] - o[3] + ); + } + } + *last = Some(now); + } if super::capture::enabled() { super::capture::present(queue as usize, &extracted.iter().map(|e| e.0).collect::>(), frames); } @@ -243,9 +287,43 @@ pub fn trace_frame() -> bool { *ON.get_or_init(|| std::env::var_os("XCL_TRACE_FRAME").is_some()) } +/// `XCL_TRACE_PLANES=`: from that frame on (the next 600), what console code did with +/// each presented plane's resource since the present before. +fn trace_planes() -> Option { + static FROM: std::sync::OnceLock> = std::sync::OnceLock::new(); + *FROM.get_or_init(|| std::env::var("XCL_TRACE_PLANES").ok().and_then(|v| v.trim().parse().ok())) +} + +/// A copy into a presented resource under `XCL_TRACE_PLANES` (the first 60): where from. +pub unsafe fn trace_plane_copy(what: &str, dst: usize, src: usize) { + if trace_planes().is_none() || !is_presented(dst) { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) >= 60 { + return; + } + let d = |r: usize| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|r| r.GetDesc()).map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0, d.Flags.0)); + crate::xlog_info!( + "plane trace: frame {} {what} into {dst:#x} {:?} from {src:#x} {:?} (the title's address {:x?})", + BOUNDARIES.load(Ordering::Relaxed), + d(dst), + if src != 0 { d(src) } else { None }, + super::real::title_address(src) + ); +} + +pub fn trace_planes_from() -> Option { + trace_planes() +} + +pub fn trace_uses() -> bool { + trace_frame() || trace_planes().is_some() +} + /// `res` was used as `what` (USE_*) pub fn note_use(res: usize, what: usize) { - if trace_frame() && res != 0 { + if (trace_frame() || trace_planes().is_some()) && res != 0 { USES.lock().unwrap().get_or_insert_with(HashMap::new).entry(res).or_default()[what] += 1; } } @@ -1081,6 +1159,11 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, Some((r, desc, uv)) }) .collect(); + // `XCL_PRESENT_PLANE=` (diagnostic): only plane `i` of a PresentX is shown, as it is + let resolved = match present_plane_only() { + Some(i) if i < resolved.len() => vec![resolved[i].clone()], + _ => resolved, + }; if resolved.is_empty() { return; } @@ -1302,6 +1385,14 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, for dump in p.dumps.drain(..) { if dump.tag.starts_with("twin") { super::depth_uav::log_values(&dump.buffer, &dump.footprint, &dump.tag); + // and as a picture of its bytes as they are (a 16-bit twin: the low byte red, + // the high byte green; a 32-bit one: its low three bytes; a stencil twin: grey) + let raw = match dump.format { + DXGI_FORMAT_R16_TYPELESS => DXGI_FORMAT_R16_UINT, + DXGI_FORMAT_R32_TYPELESS => DXGI_FORMAT_R32_UINT, + f => f, + }; + write_frame(&dump.buffer, &dump.footprint, raw, &dump.tag.replace(' ', "_")); continue; } if dump.tag.starts_with("lut") { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fcb693eeca..e76efee194 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1961,6 +1961,124 @@ pub(super) fn title_address(res: usize) -> Option { console_buffer(res).map(|b| b.0).or_else(|| TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied())) } +/// GPU address ranges of buffers made and let go (the last 16384 events), for a page fault's +/// report: (when, what, GPU address, bytes, let go). +static VA_LOG: Mutex> = Mutex::new(std::collections::VecDeque::new()); + +pub(super) fn note_va(what: &'static str, va: u64, bytes: u64, gone: bool) { + if va == 0 { + return; + } + let mut g = VA_LOG.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() >= 16384 { + g.pop_front(); + } + g.push_back((std::time::Instant::now(), what, va, bytes, gone)); +} + +/// Buffer views in unified memory that compute dispatches were given through their descriptor +/// tables, as the CPU saw the descriptors at the title's call: (address, bytes, pipeline) → +/// (first time, last time, times). For a crash report: which dispatches could write an address. +static DISPATCH_VIEWS: Mutex>> = Mutex::new(None); + +pub(super) fn note_dispatch_view(base: u64, bytes: u64, pso: usize) { + let now = std::time::Instant::now(); + let mut g = DISPATCH_VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + if m.len() >= 400_000 && !m.contains_key(&(base, bytes, pso)) { + return; + } + let e = m.entry((base, bytes, pso)).or_insert((now, now, 0)); + e.1 = now; + e.2 += 1; +} + +fn compute_label(pso: usize) -> String { + let real = super::pso_async::peek(pso); + match pso_shaders(real) { + Some((cs, 0)) => format!(", cs {cs:016x}"), + _ => super::dred::on().then(|| super::dred::label_of(real)).flatten().map_or(String::new(), |l| format!(", {l}")), + } +} + +/// The buffer views dispatches were given that hold `addr` (within 64 bytes), newest first, up to 6. +pub fn dispatch_views_over(addr: usize) -> String { + let Ok(g) = DISPATCH_VIEWS.try_lock() else { return "(busy)".into() }; + let Some(m) = g.as_ref() else { return String::new() }; + let a = addr as u64; + let now = std::time::Instant::now(); + let mut hit: Vec<(&(u64, u64, usize), &(std::time::Instant, std::time::Instant, u64))> = m.iter().filter(|(k, _)| a + 64 > k.0 && a < k.0 + k.1).collect(); + hit.sort_by_key(|(_, v)| std::cmp::Reverse(v.1)); + let v: Vec = hit + .iter() + .take(6) + .map(|(k, v)| { + format!( + "{:#x} +{:#x} (pipeline {:#x}{}; {} dispatches, first {} ms ago, last {} ms ago)", + k.0, + k.1, + k.2, + compute_label(k.2), + v.2, + now.saturating_duration_since(v.0).as_millis(), + now.saturating_duration_since(v.1).as_millis() + ) + }) + .collect(); + if v.is_empty() { format!("none of {} views", m.len()) } else { format!("{} of {} views: {}", hit.len(), m.len(), v.join("; ")) } +} + +/// Root views XCL bound by GPU address (the last 262144): (list, root slot, address), for a page +/// fault's report – a root view has no size, so a shader reaches up to 4 GiB past its address. +static ROOT_VIEWS: Mutex> = Mutex::new(std::collections::VecDeque::new()); + +pub(super) fn note_root_view(list: usize, slot: u32, va: u64) { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_DIAG_VIEWS").is_ok_and(|v| v.trim() == "1")) { + return; + } + let mut g = ROOT_VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + if g.len() >= 262_144 { + g.pop_front(); + } + g.push_back((list, slot, va)); +} + +/// The root views bound lately from whose address a 32-bit offset reaches `va`: the distinct +/// (slot, address) pairs with how many binds and the list of the newest, newest first (up to 10). +fn root_views_reaching(va: u64) -> String { + let Ok(g) = ROOT_VIEWS.try_lock() else { return "(busy)".into() }; + let mut found: Vec<(u32, u64, usize, usize)> = Vec::new(); + for &(list, slot, at) in g.iter().rev() { + if at <= va && va - at < 1 << 32 { + match found.iter().position(|f| f.0 == slot && f.1 == at) { + Some(i) => found[i].2 += 1, + None if found.len() < 10 => found.push((slot, at, 1, list)), + None => {} + } + } + } + let nulls = g.iter().filter(|e| e.2 == 0).count(); + if found.is_empty() { + return format!("none of {} binds ({nulls} at address 0)", g.len()); + } + found.iter().map(|&(slot, at, n, list)| format!("slot {slot} at {at:#x} (+{:#x}; {n} binds, last on list {list:#x})", va - at)).collect::>().join("; ") + &format!("; {nulls} of {} binds at address 0", g.len()) +} + +/// The last events (up to 6, newest first) of buffers whose GPU range holds `va`. +fn va_history(va: u64) -> String { + let Ok(g) = VA_LOG.try_lock() else { return "(busy)".into() }; + let now = std::time::Instant::now(); + let v: Vec = g + .iter() + .rev() + .filter(|e| va >= e.2 && va < e.2 + e.3) + .take(6) + .map(|e| format!("{} ms ago {} {} at {:#x} ({} KiB)", now.saturating_duration_since(e.0).as_millis(), e.1, if e.4 { "let go" } else { "made" }, e.2, e.3 >> 10)) + .collect(); + if v.is_empty() { format!("none of {} events", g.len()) } else { v.join("; ") } +} + pub(super) fn note_title_address(res: usize, va: usize) { TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, va); } @@ -1989,6 +2107,12 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { // whose Release ends the object cleans up after it, as before.) add(this); let last = f(this) == 1; + if last { + let raw = this; + if let Some(d) = ID3D12Resource::from_raw_borrowed(&raw).map(|r| (r.GetDesc(), r)).filter(|(d, _)| d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { + note_va("a buffer's last release", d.1.GetGPUVirtualAddress(), d.0.Width, true); + } + } let held = last && super::late_release::enabled(); let mut pinned = false; let n = if last { 0 } else { f(this) }; @@ -2022,6 +2146,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::placements::gone(this as usize); } super::depth_uav::forget(this as usize); + super::barrier_groups::forget(this as usize); super::format_alias::forget(this as usize); super::ambient::forget_resource(this as usize); super::title_textures::forget(this as usize); @@ -2288,7 +2413,7 @@ fn note_buffer_view() { /// shaders read buffers through `mem`. One in a GPU view of the title's memory asks for its /// tiles (`view_want`). unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, cpu: u64) { - let Some(slot) = super::console_heap::slot(cpu).filter(|s| !s.sampler) else { + let Some(slot) = super::console_heap::shadow_slot(cpu).filter(|s| !s.sampler) else { let f: unsafe extern "system" fn(*mut c_void, *const D3D12_CONSTANT_BUFFER_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 17)); return f(this, desc, cpu); }; @@ -2298,7 +2423,7 @@ unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12 crate::gpu::desc::cbv_words(0, 0) }); super::view_want::want(super::view_want::Path::Cbv, va, size as u64); - super::console_heap::write(&slot, &words); + super::console_heap::write_shadow(&slot, &words); } /// The V# of a constant buffer view of `size` bytes at `va`, when shaders reach it there: the @@ -2366,7 +2491,7 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 if copy_console_slots(this, n, dst, src, ty) { return; } - if super::console_heap::slot(dst).is_some() || super::console_heap::slot(src).is_some() { + if super::console_heap::contains(dst) || super::console_heap::contains(src) { note_mixed_copy(); return; } @@ -2382,10 +2507,10 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) { let ty = pc_heap_type(ty); note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs }); - use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; - let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && slot(*dsts).is_some(); + use super::console_heap::{contains, SAMPLER_SLOT, SLOT}; + let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && contains(*dsts); if !console { - if !srcs.is_null() && ns > 0 && slot(*srcs).is_some() { + if !srcs.is_null() && ns > 0 && contains(*srcs) { note_mixed_copy(); return; } @@ -2480,7 +2605,8 @@ unsafe extern "system" fn dev_create_uav_checked_x( let raw_fmt = patched.as_ref().map_or(0, |d| d.Format.0 as u32); let res_fmt = rd.Format.0 as u32; let mapped_fmt = super::device_x::pc_uav_linear_format(if raw_fmt == 0 { res_fmt } else { raw_fmt }); - let eff_fmt = super::device_x::pc_shader_view_format(res_fmt, mapped_fmt); + // (an sRGB texture made typeless: its UAV is the linear format of the family) + let eff_fmt = super::device_x::pc_uav_linear_format(super::device_x::pc_shader_view_format(res_fmt, mapped_fmt)); if let Some(c) = patched.as_mut() { if eff_fmt != 0 && (eff_fmt != raw_fmt && (raw_fmt != 0 || eff_fmt != res_fmt)) { c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(eff_fmt as i32); @@ -2579,10 +2705,18 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) let mut out = match v { Some(v) => *v, None => { - // only a typeless depth buffer needs a description of its own - if !matches!(rf, 19 | 39 | 44 | 53) { + // only a typeless depth buffer needs a description of its own, and an sRGB texture + // with unordered access, typeless too (`device_x::pc_resource_desc`) + let srgb = matches!(rf, 27 | 90) && rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0; + if !matches!(rf, 19 | 39 | 44 | 53) && !srgb { return None; } + if srgb && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE3D, ..Default::default() }; + v.Anonymous.Texture3D = D3D12_TEX3D_SRV { MipLevels: u32::MAX, ..Default::default() }; + v.Format = DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, 0) as i32); + return Some(v); + } let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; let slices = u32::from(rd.DepthOrArraySize); // a multisampled depth buffer has only the MS view dimensions @@ -2654,19 +2788,14 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, copy = Some(v); } let desc = copy.as_ref().map_or(desc, |c| c as *const _); - let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): // translated shaders read BVH nodes from UMA (`bvh_intersect`), never from a PC DXR SRV, - // so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC. + // so write the RDNA2 BVH descriptor directly without reserving a page in the shared heap. if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE) { + let Some(slot) = super::console_heap::shadow_slot(cpu) else { return f(this, res, desc, cpu) }; let va = v.Anonymous.RaytracingAccelerationStructure.Location; - // in a GPU view: its tiles are asked for from the root's on (the size is not known; the - // build wrote the nodes through views that asked for theirs, and a buffer placed there - // has all its tiles) let view = super::view_want::want(super::view_want::Path::Bvh, va, 0x1_0000); let in_uma = va != 0 && (view || crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize))); - // `XCL_BVH_EMPTY=1` (a test): every acceleration structure is an empty one – the title's - // rays hit nothing. Tells what its ray tracing shaders do to the picture and the device. static EMPTY: std::sync::OnceLock = std::sync::OnceLock::new(); let empty = *EMPTY.get_or_init(|| { let on = std::env::var("XCL_BVH_EMPTY").is_ok_and(|v| v.trim() == "1"); @@ -2676,25 +2805,44 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, on }); if in_uma && !empty { - // and what rays read past it: the rest of the top level, its bottom levels, the - // parent pointers (`bvh_want`; `XCL_BVH_WALK=0`: the 64 KiB above only) super::bvh_want::view_made(va); crate::gpu::rt_leave_out::note_structure(va); let w = crate::gpu::desc::bvh_words(va, true); - return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); + return super::console_heap::write_shadow(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); } - // (an all-zero descriptor is no empty structure: the shader reads its root at 0x30 of - // window 0) if let Some(at) = empty.then(empty_bvh).flatten() { let w = crate::gpu::desc::bvh_words(at, true); - return super::console_heap::write(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); + return super::console_heap::write_shadow(&slot, &[w[0], w[1], w[2], w[3], 0, 0, 0, 0]); } static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: CreateShaderResourceView(RAYTRACING_ACCELERATION_STRUCTURE) at {va:#x} is not in unified memory – writing empty BVH descriptor"); } - return super::console_heap::write(&slot, &[0; 8]); + return super::console_heap::write_shadow(&slot, &[0; 8]); + } + // Buffer SRVs on pages not yet placed in the shared heap: translated shaders read buffers + // through UMA (`buffer_view`), so write the PC mirror and shadow V# without consuming 512 + // shared-heap descriptors for a buffer-only page. + if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && !res.is_null()) { + if let Some(slot) = super::console_heap::shadow_slot(cpu).filter(|s| !s.sampler && s.index.is_none()) { + if buffer_delta(res as usize) != 0 { + let null_buf = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ..Default::default() + }; + f(this, std::ptr::null_mut(), &null_buf, slot.pc_srv); + } else { + f(this, res, desc, slot.pc_srv); + } + super::ambient::note_descriptor(slot.at, 0, 0, 0, 0, false); + let b = &v.Anonymous.Buffer; + let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; + return super::console_heap::write_shadow(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + } } + let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; // Placed buffers with `buffer_delta != 0` can have unaligned structured offsets on the PC // backing; write a valid null PC buffer SRV so `slot.pc_srv` and `GLOBAL` never keep a stale // descriptor while translated shaders read the exact UMA address via `buffer_view` below. @@ -2840,12 +2988,12 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let va = (view.add(0x28) as *const u64).read_unaligned(); let v = (view as *const D3D12_SHADER_RESOURCE_VIEW_DESC).read_unaligned(); if v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER { - let Some(slot) = super::console_heap::slot(cpu) else { return }; + let Some(slot) = super::console_heap::shadow_slot(cpu) else { return }; let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); super::view_want::want(super::view_want::Path::ViewAt, at, len); - return super::console_heap::write(&slot, &words); + return super::console_heap::write_shadow(&slot, &words); } let placed = super::format_alias::placed_srv_resource(this, rdesc, va, v.Format.0 as u32); let res = placed.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw); @@ -2862,13 +3010,13 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let va = (view.add(0x28) as *const u64).read_unaligned(); let v = (view as *const D3D12_UNORDERED_ACCESS_VIEW_DESC).read_unaligned(); if v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER { - let Some(slot) = super::console_heap::slot(cpu) else { return }; + let Some(slot) = super::console_heap::shadow_slot(cpu) else { return }; note_unaligned_delta_uav(slot.pc_uav as usize, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); super::view_want::want(super::view_want::Path::ViewAt, at, len); - return super::console_heap::write(&slot, &words); + return super::console_heap::write_shadow(&slot, &words); } let placed = super::format_alias::placed_uav_resource(this, rdesc, va, v.Format.0 as u32); let res = placed.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw); @@ -3370,7 +3518,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, if let Some(c) = copy.as_mut() { if let Some(rd) = rd_opt.as_ref() { let rf = rd.Format.0 as u32; - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); + c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_uav_linear_format(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32)) as i32); } else { c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_view_format(c.Format.0 as u32) as i32); if c.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN && view_dim_to_image_type(c.ViewDimension.0).is_some() { @@ -5425,7 +5573,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const (result.0 >= 0).then_some((rs, result)) }); if let Some(plan) = compiled.dispatch_chain.filter(|_| warm.is_none()) { - if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, &dxil, &compiled.samplers, plan) { + if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, cs, wave32_only(this), &compiled.samplers, plan) { 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))]); @@ -6874,11 +7022,33 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const /// A pipeline description that owns what it points to (shader blobs, input layout and its /// semantic names), so a worker can build the pipeline after the title's memory is gone. /// The root signature pointer is kept as is (the translated paths replace it). +/// Shader blobs are interned via weak `Arc<[u8]>` references so thousands of lazy pipelines +/// sharing the same console VS/PS/MS bytecode hold only one copy until built. #[allow(dead_code)] // the vectors only keep the copies alive enum OwnedDesc { - Compute(Box, Vec>), - Graphics(Box, Vec>, Vec, Vec), - Stream(Box<[usize; 2]>, Vec, Vec>), + Compute(Box, Vec>), + Graphics(Box, Vec>, Vec, Vec), + Stream(Box<[usize; 2]>, Vec, Vec>), +} + +/// Share one heap copy of identical console shader bytecodes across all live `OwnedDesc`s. +fn intern_shader_blob(bytes: &[u8]) -> std::sync::Arc<[u8]> { + use std::sync::{Arc, Weak}; + static CACHE: Mutex>>> = Mutex::new(None); + let key = (crate::gpu::shader::fnv64(bytes), bytes.len()); + let mut g = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + if let Some(arc) = m.get(&key).and_then(Weak::upgrade) { + if arc.as_ref() == bytes { + return arc; + } + } + let arc: Arc<[u8]> = Arc::from(bytes); + if m.len() >= 16_384 && m.len().is_power_of_two() { + m.retain(|_, w| w.strong_count() > 0); + } + m.insert(key, Arc::downgrade(&arc)); + arc } unsafe impl Send for OwnedDesc {} @@ -6897,10 +7067,10 @@ pub(crate) fn shader_key_of_hash(hash: u64) -> u64 { ((0xcbf2_9ce4_8422_2325u64 ^ hash).wrapping_mul(0x0000_0100_0000_01b3)) | 1 } -pub(crate) fn shaders_key(blobs: &[Vec]) -> u64 { +pub(crate) fn shaders_key>(blobs: &[B]) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for b in blobs { - h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); + h = (h ^ crate::gpu::shader::fnv64(b.as_ref())).wrapping_mul(0x0000_0100_0000_01b3); } h | 1 } @@ -6922,7 +7092,16 @@ mod shaders_key_tests { assert_ne!(key, super::shaders_key(&[b.clone(), a.clone()])); assert_ne!(key, super::shaders_key(&[a.clone()])); assert_ne!(key, super::shaders_key(&[a, vec![4u8, 6]])); - assert_ne!(super::shaders_key(&[]), 0); + assert_ne!(super::shaders_key::>(&[]), 0); + } + + #[test] + fn interned_shader_blobs_share_one_allocation() { + let a = super::intern_shader_blob(&[0xDE, 0xAD, 0xBE, 0xEF, 1, 2, 3, 4]); + let b = super::intern_shader_blob(&[0xDE, 0xAD, 0xBE, 0xEF, 1, 2, 3, 4]); + assert!(std::sync::Arc::ptr_eq(&a, &b)); + let c = super::intern_shader_blob(&[0xDE, 0xAD, 0xBE, 0xEF, 1, 2, 3, 5]); + assert!(!std::sync::Arc::ptr_eq(&a, &c)); } } @@ -6966,10 +7145,10 @@ impl OwnedDesc { } } -/// Copy a shader blob into `blobs` and point `b` at the copy. -unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) { +/// Intern a shader blob into `blobs` and point `b` at the shared copy. +unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec>) { if let Some(bytes) = shader_bytes(b) { - blobs.push(bytes.to_vec()); + blobs.push(intern_shader_blob(bytes)); let v = blobs.last().unwrap(); *b = bytecode(v); } else { @@ -7022,7 +7201,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { return None; } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); - let mut blobs: Vec> = Vec::new(); + let mut blobs: Vec> = Vec::new(); let mut off = 0usize; while off + 8 <= size { let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?); @@ -7039,7 +7218,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { if p == 0 || n == 0 { buf[at..at + 16].fill(0); } else if crate::gpu::shader::readable(p, n) { - blobs.push(std::slice::from_raw_parts(p as *const u8, n).to_vec()); + blobs.push(intern_shader_blob(std::slice::from_raw_parts(p as *const u8, n))); buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().as_ptr() as u64).to_le_bytes()); } else { return None; @@ -9071,6 +9250,11 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de let rf = ID3D12Resource::from_raw_borrowed(&res).map_or(0, |r| r.GetDesc().Format.0 as u32); c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); } + // an sRGB target with unordered access is typeless on the PC (`device_x::pc_resource_desc`): + // the view the title gave no description is its sRGB one, all of it + if copy.is_none() { + copy = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()).and_then(|rd| typeless_srgb_rtv(&rd)); + } let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); super::present::note_rtv(handle, res); @@ -9090,6 +9274,29 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de } } +/// The render target view of all of a typeless sRGB texture with unordered access (`rd`) that a +/// null description stands for; None: `rd` is not one. +fn typeless_srgb_rtv(rd: &D3D12_RESOURCE_DESC) -> Option { + let rf = rd.Format.0 as u32; + if !matches!(rf, 27 | 90) || rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + return None; + } + let mut v = D3D12_RENDER_TARGET_VIEW_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, 0) as i32), ..Default::default() }; + match rd.Dimension { + D3D12_RESOURCE_DIMENSION_TEXTURE2D if rd.DepthOrArraySize > 1 => { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_RTV { MipSlice: 0, FirstArraySlice: 0, ArraySize: u32::from(rd.DepthOrArraySize), PlaneSlice: 0 }; + } + D3D12_RESOURCE_DIMENSION_TEXTURE2D => v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D, + D3D12_RESOURCE_DIMENSION_TEXTURE3D => { + v.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; + v.Anonymous.Texture3D = D3D12_TEX3D_RTV { MipSlice: 0, FirstWSlice: 0, WSize: u32::MAX }; + } + _ => return None, + } + Some(v) +} + /// ClearRenderTargetView: as on the PC (`XCL_TRACE_FRAME`: the colours logged) unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *const [f32; 4], n: u32, rects: *const c_void) { type F = unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const c_void); @@ -9100,6 +9307,8 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co if N.fetch_add(1, Ordering::Relaxed) < 16 { crate::xlog_info!("frame trace: ClearRenderTargetView {rtv:#x} → {:?} colour {:?}, {n} rects", super::present::rtv_resource(rtv), color.as_ref()); } + } + if super::present::trace_uses() { if let Some(r) = super::present::rtv_resource(rtv) { super::present::note_use(r, super::present::USE_CLEAR); } @@ -9127,7 +9336,7 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt } if n > 0 && !rtvs.is_null() { super::present::note_rt0(this as usize, *rtvs); - if super::present::trace_frame() { + if super::present::trace_uses() { for k in 0..n as usize { let h = if single != 0 { *rtvs + k * 32 } else { *rtvs.add(k) }; if let Some(r) = super::present::rtv_resource(h) { @@ -9731,10 +9940,56 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::title_textures::submitted(&mapped); super::present::note_execute(this, &mapped); stop_if_device_removed(); + gpu_sync_after_submit(this); super::submit_cost::end(t_end.elapsed()); super::submit_cost::done(submit_t0); } +/// `XCL_GPU_SYNC=` (diagnostic, off unless set): a title's submit returns only once its queue +/// has done the work (for `ms` at most: a queue that waits for a value another submit writes is +/// left to it), and what the lists wrote into copied memory is in the CPU's view. With it the +/// title never runs ahead of the GPU: what still goes wrong then is not a matter of timing. +unsafe fn gpu_sync_after_submit(queue: *mut c_void) { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + let ms = *MS.get_or_init(|| std::env::var("XCL_GPU_SYNC").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + if ms == 0 || super::title_textures::is_own_work() { + return; + } + static FENCES: Mutex>> = Mutex::new(None); + static LATE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + static DONE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let (fence, value) = { + let mut g = FENCES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if !m.contains_key(&(queue as usize)) { + let raw = device_raw(); + let Some(dev) = ID3D12Device::from_raw_borrowed(&raw) else { return }; + let Ok(f) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + m.insert(queue as usize, (f, 0)); + } + let e = m.get_mut(&(queue as usize)).unwrap(); + e.1 += 1; + (e.0.clone(), e.1) + }; + if q.Signal(&fence, value).is_err() { + return; + } + let t0 = std::time::Instant::now(); + while fence_completed(&fence) < value { + if t0.elapsed().as_millis() as u64 >= ms { + let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_info!("D3D12.X: XCL_GPU_SYNC: {k} submits so far not done on the GPU after {ms} ms ({} were)", DONE.load(Ordering::Relaxed)); + } + return; + } + std::thread::yield_now(); + } + DONE.fetch_add(1, Ordering::Relaxed); + super::sparse::settle_readbacks(); +} + /// Wait (up to 10 s) until the GPU has finished the work submitted to the queues console code /// used (before the process ends on purpose). pub fn drain_gpu() { @@ -10001,6 +10256,8 @@ pub fn log_device_removed() { let va = pf.PageFaultVA; let window = uma_window_vas().iter().position(|&w| w != 0 && va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); + crate::xlog_error!("DRED page fault: XCL's buffers at that address: {}", va_history(va)); + crate::xlog_error!("DRED page fault: root views a 32-bit offset reaches it from: {}", root_views_reaching(va)); } let breadcrumbs = dred.GetAutoBreadcrumbsOutput(); match &breadcrumbs { @@ -11294,7 +11551,7 @@ mod mesh_stream_tests { let owned = own_stream(d_valid.as_ptr() as *const c_void).expect("valid stream"); let OwnedDesc::Stream(_, buf, blobs) = owned else { panic!("expected Stream") }; assert_eq!(blobs.len(), 1); - assert_eq!(blobs[0], shader); + assert_eq!(&*blobs[0], shader.as_slice()); let rebased = u64::from_le_bytes(buf[8..16].try_into().unwrap()) as usize; assert_eq!(rebased, blobs[0].as_ptr() as usize); assert_ne!(rebased, shader.as_ptr() as usize); @@ -11854,6 +12111,7 @@ void main() { list.SetDescriptorHeaps(&[Some(heap.clone())]); list.SetComputeRootSignature(&rs); list.SetComputeRoot32BitConstants(0, 12, idx_consts.as_ptr() as *const c_void, 0); + note_root_view(list.as_raw() as usize, 1, out_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, out_buf.GetGPUVirtualAddress()); list.Dispatch(1, 1, 1); @@ -12088,11 +12346,12 @@ mod depth_uav_twin_tests { dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R24_UNORM_X8_TYPELESS, 0), slot_cpu(1)); // a second stencil UAV takes the same twin dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R8_UINT, 0), slot_cpu(2)); - let (made2, alive2, redirected2, nulls) = depth_uav::counts(); - assert_eq!((made2 - made, alive2 - alive, redirected2 - redirected), (1, 1, 2), "one twin, two views of it"); - assert_eq!(nulls, ["its depth plane has no twin yet"], "the depth view is a null view, with its reason"); + let (made2, alive2, redirected2, _) = depth_uav::counts(); + assert_eq!((made2 - made, alive2 - alive, redirected2 - redirected), (2, 2, 3), "a stencil twin and a depth twin, three views of them"); let twin = depth_uav::twin_of(raw as usize).expect("a stencil twin"); + let depth_twin = depth_uav::depth_twin_of(raw as usize).expect("a depth twin"); + assert_ne!(twin, depth_twin, "one twin a plane"); let t = ID3D12Resource::from_raw_borrowed(&(twin as *mut c_void)).unwrap().GetDesc(); assert_eq!((t.Format, t.Width, t.Height, t.DepthOrArraySize, t.MipLevels), (DXGI_FORMAT_R8_TYPELESS, 16, 16, 1, 1)); assert!(t.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0); @@ -12106,7 +12365,7 @@ mod depth_uav_twin_tests { assert_eq!((w[0], (w[1] >> 20) & 0x1FF), (s.index, 5), "slot {k}: the T# of an R8_UINT image"); } let s = console_heap::slot(slot_cpu(1)).unwrap(); - assert_eq!(console_heap::names_of(&s).1, 0, "the depth plane's UAV is a null view"); + assert_eq!(console_heap::names_of(&s).1, depth_twin, "the depth plane's UAV is a view of its depth twin"); drop(heap); drop(depth); @@ -12218,13 +12477,14 @@ mod depth_uav_twin_tests { let (done2, not_done2) = depth_uav::clears(); assert_eq!((done2 - done, not_done2 - not_done), (1, 0), "the clear went to the twin"); assert_eq!(GOT.load(Ordering::Relaxed), twin.as_raw() as usize, "the PC clear gets the twin as its resource, not the depth buffer"); - // a depth-plane UAV of the buffer is a null view: its clear is not done, nothing reaches the PC + // a depth-plane UAV of the buffer is a view of its depth twin: the clear goes there let depth_slot = slot + console_heap::SLOT as u64; dev_create_uav_checked_x(d, raw, std::ptr::null_mut(), &uav(DXGI_FORMAT_R24_UNORM_X8_TYPELESS, 0), depth_slot); + let depth_twin = depth_uav::depth_twin_of(raw as usize).expect("a depth twin"); GOT.store(0, Ordering::Relaxed); list_x::clear_uav_uint_x(stand_in.as_ptr() as *mut c_void, depth_slot, depth_slot, raw as usize, [0x11u32; 4].as_ptr(), 0, std::ptr::null()); let (done3, not_done3) = depth_uav::clears(); - assert_eq!((done3 - done2, not_done3 - not_done2, GOT.load(Ordering::Relaxed)), (0, 1, 0), "a clear through the null view is not done"); + assert_eq!((done3 - done2, not_done3 - not_done2, GOT.load(Ordering::Relaxed)), (1, 0, depth_twin), "the clear of the depth view goes to the depth twin"); // the twin to a readback buffer let td = twin.GetDesc(); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 57428482ae..4f8f069e5f 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -64,11 +64,26 @@ impl PipelineBuilder { } } +/// What a chain's whole form is made from: its console program, translated again when the whole +/// form is first wanted (from the translation caches: the same DXIL). Most chains never want it +/// (only an indirect dispatch runs the whole form), and their whole DXIL kept in memory was a +/// retail title's 148 MB for 198 split programs, against 22 KB of console code on average. +struct WholeSource { + console: Vec, + wave32: bool, +} + +impl WholeSource { + fn code(&self) -> Result, String> { + crate::gpu::recomp::pso::console_to_dxil_for(&self.console, pso::Stage::Compute, 0, self.wave32).map(|c| c.dxil) + } +} + struct Chain { builder: Arc, tail: Vec, words: u32, - whole_code: Vec, + whole_source: WholeSource, whole: OnceLock, build_whole: Mutex<()>, /// a thread of its own builds the whole form (`whole_ready`) @@ -87,7 +102,8 @@ impl Chain { let _call = super::super::pso_async::pc_call(); 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 code = self.whole_source.code().map_err(|e| format!("whole compute program: {e}"))?; + let p = self.builder.pipeline(&code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; let _ = self.whole.set(p.clone()); Ok(p) } @@ -96,7 +112,7 @@ impl Chain { static CHAINS: LazyLock>>> = LazyLock::new(Default::default); pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, - iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], samplers: &[pso::StaticSampler], + iid: *const GUID, result: *mut *mut c_void, record: u64, console: &[u8], wave32: bool, samplers: &[pso::StaticSampler], plan: Arc) -> Option { if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } let dev = ID3D12Device::from_raw_borrowed(&this)?; @@ -116,7 +132,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let mut pieces = built.into_iter().collect::>>()?.into_iter(); let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()), whole_sent: Default::default() }); + whole_source: WholeSource { console: console.to_vec(), wave32 }, whole: OnceLock::new(), build_whole: Mutex::new(()), whole_sent: Default::default() }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -316,6 +332,30 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, mod tests { use super::{scratch_bytes, LEAST}; + #[test] + fn the_whole_form_is_made_again_from_the_console_program() { + use crate::gpu::recomp::pso::{console_to_dxil_for, Stage}; + use crate::gpu::xbox::tests::{fssm, sample, CODE}; + // (a compute program of one thread group of 1x1x1, as `pso::compile_time_bench` makes it) + let mut f = fssm(&CODE, &[(6, 0)]); + for offset in [0x13C, 0x140, 0x144] { + f[offset..offset + 4].copy_from_slice(&1u32.to_le_bytes()); + } + let blob = sample(5, &[f]); + let first = match console_to_dxil_for(&blob, Stage::Compute, 0, false) { + Ok(c) => c.dxil, + // (no DXC here) + Err(e) if e.contains("dxcompiler") || e.contains("DXC") => { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + Err(e) => panic!("the console program does not translate: {e}"), + }; + let source = super::WholeSource { console: blob.clone(), wave32: false }; + assert_eq!(source.code().unwrap(), first, "the DXIL the chain was split from"); + assert!(source.console.len() < first.len(), "a chain keeps less than the DXIL: {} against {}", source.console.len(), first.len()); + } + const MB: u64 = 1 << 20; #[test] diff --git a/crates/xcl/src/hle/d3d12x/scatter.rs b/crates/xcl/src/hle/d3d12x/scatter.rs index c36f734716..f0c6ea0c77 100644 --- a/crates/xcl/src/hle/d3d12x/scatter.rs +++ b/crates/xcl/src/hle/d3d12x/scatter.rs @@ -126,8 +126,11 @@ impl Scatter { pub unsafe fn dispatch(&self, list: &ID3D12GraphicsCommandList, chunks: usize, ring_va: u64, to_va: u64) { debug_assert!(chunks > 0 && chunks <= MAX_CHUNKS); list.SetComputeRoot32BitConstant(0, chunks as u32, 0); + super::real::note_root_view(list.as_raw() as usize, 1, ring_va); list.SetComputeRootShaderResourceView(1, ring_va); + super::real::note_root_view(list.as_raw() as usize, 2, ring_va + Self::data_at(chunks) as u64); list.SetComputeRootShaderResourceView(2, ring_va + Self::data_at(chunks) as u64); + super::real::note_root_view(list.as_raw() as usize, 3, to_va); list.SetComputeRootUnorderedAccessView(3, to_va); list.Dispatch(chunks.div_ceil(GROUP) as u32, 1, 1); } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index fbbe766bfd..6b0e8ac807 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1892,6 +1892,9 @@ impl State { let here = entry.cpu(t); if entry.holes & (1u16 << idx) == 0 && entry.gen == gen { let wrote = land_page(&mut entry.sent[idx], here + (pg - t), at - pg, p.add(src_off), step); + if wrote { + crate::hle::kernelx::pagelog::note("GPU copy back landed", here + (at - t), 0, step); + } if wrote && self.own_pages.len() < OWN_PAGES_MAX && super::look_stats::deep() { self.own_pages.push(here + (pg - t)); } @@ -1927,6 +1930,7 @@ impl State { 8 => (*(cpu as *const AtomicU64)).store(value, Ordering::Release), _ => return, } + crate::hle::kernelx::pagelog::note("GPU immediate landed", cpu, 0, (bytes & 0x7f) as usize); if self.own_pages.len() < OWN_PAGES_MAX && super::look_stats::deep() { self.own_pages.push(cpu & !(PAGE - 1)); } diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index 16e06fd028..bf9cc74b63 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -127,6 +127,25 @@ pub(super) fn unknown(known: &Known) { k.forgotten += 1; } +/// `parts` (from, to) of the `size` bytes of a texture at `src` did not go up, whatever their +/// pages were found to hold: that is not taken for what the PC texture holds there, and the next +/// write to those pages goes up. What is known of its other pages stays. +pub(super) fn unknown_parts(known: &Known, src: usize, size: usize, parts: &[(usize, usize)]) { + if parts.is_empty() { + return; + } + let mut k = known.lock().unwrap(); + if k.hashes.len() != pages_of(src, size) { + return; + } + let first = src / PAGE * PAGE; + let n = k.hashes.len(); + for &(from, to) in parts.iter().filter(|r| r.0 < r.1) { + let (a, z) = ((src + from - first) / PAGE, (src + to - first).div_ceil(PAGE)); + k.hashes[a.min(n)..z.min(n)].fill(0); + } +} + /// `parts` of a texture (from, to) are not what its PC texture holds (a mapping changed under /// them): they go up again with its next upload, with no comparison (`take_again`). pub(super) fn stale(known: &Known, parts: Vec<(usize, usize)>) { @@ -374,6 +393,40 @@ impl PageMap { done += n; } } + + /// Whether any byte in `[at, at + len)` is non-zero, skipping unmapped (`0`) pages with no + /// read and stopping at the first non-zero page. + pub unsafe fn any_nonzero(&self, at: usize, len: usize) -> bool { + let mut done = 0; + SCRATCH.with(|s| { + let mut buf = s.borrow_mut(); + if buf.len() < Self::PAGE { + buf.resize(Self::PAGE, 0); + } + while done < len { + let a = at + done; + let (k, off) = (a.wrapping_sub(self.first) / Self::PAGE, a & (Self::PAGE - 1)); + let n = (Self::PAGE - off).min(len - done); + match self.at.get(k).copied().filter(|_| a >= self.first).unwrap_or(0) { + 0 => {} + p if p & 1 != 0 => { + super::title_textures::copy_readable((p & !1) + off, &mut buf[..n]); + if !super::title_textures::all_zero(&buf[..n]) { + return true; + } + } + p => { + super::title_textures::copy_or_zeros(p + off, &mut buf[..n]); + if !super::title_textures::all_zero(&buf[..n]) { + return true; + } + } + } + done += n; + } + false + }) + } } /// `f` with the `len` bytes of the title's memory at `at`: where they are in the window that stays @@ -785,7 +838,21 @@ fn capacity(bytes: u64) -> Option { } } -const FREE_BYTES: u64 = 512 << 20; +/// The most bytes of idle upload buffers kept for the next batches (`XCL_UPLOAD_KEEP_MB`, default +/// 512): memory of the system's (upload heaps), the process's commit and RAM while kept. +fn free_bytes() -> u64 { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| keep_bytes_of(std::env::var("XCL_UPLOAD_KEEP_MB").ok().as_deref())) +} + +fn keep_bytes_of(v: Option<&str>) -> u64 { + v.and_then(|v| v.trim().parse::().ok()).map_or(512, |mb| mb.min(4096)) << 20 +} + +/// Bytes of the upload buffers kept idle now. +pub(super) fn idle_bytes() -> u64 { + FREE.lock().unwrap().iter().map(|j| j.bytes).sum() +} /// A job whose buffer takes `bytes` bytes. unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { @@ -833,7 +900,7 @@ pub(super) fn give_back(job: Job) { let mut g = FREE.lock().unwrap(); g.push(job); // (the biggest goes first: one burst does not keep its buffers for good) - while g.iter().map(|j| j.bytes).sum::() > FREE_BYTES { + while g.iter().map(|j| j.bytes).sum::() > free_bytes() { let Some(i) = g.iter().enumerate().max_by_key(|(_, j)| j.bytes).map(|(i, _)| i) else { break }; g.swap_remove(i); } @@ -875,6 +942,15 @@ pub(super) unsafe fn submit(dev: &ID3D12Device, queue: &ID3D12CommandQueue, item mod tests { use super::*; + #[test] + fn the_idle_upload_buffers_kept_follow_the_switch() { + assert_eq!(keep_bytes_of(None), 512 << 20, "unset: as before"); + assert_eq!(keep_bytes_of(Some(" 64 ")), 64 << 20); + assert_eq!(keep_bytes_of(Some("0")), 0, "none kept"); + assert_eq!(keep_bytes_of(Some("lots")), 512 << 20); + assert_eq!(keep_bytes_of(Some("100000")), 4096 << 20); + } + /// The written pages of a texture are compared one by one: a page never compared has changed, /// one that holds what it held has not, the bytes next to the texture on its first and last /// page are not the texture's, and a texture nothing is known of changed as a whole. @@ -921,6 +997,16 @@ mod tests { assert!(known.lock().unwrap().again.is_some()); assert_eq!(look(&dirty[3..5]).0, vec![Change::All]); known.lock().unwrap().again = None; + // parts that did not go up: their pages' next write has changed, the others' are compared + all_sent(&known, src, size); + assert_eq!(look(&dirty).0, vec![Change::Parts(vec![(0, size)])]); + assert_eq!(look(&dirty).0, vec![Change::None]); + unknown_parts(&known, src, size, &[(PAGE + 0x800, 2 * PAGE + 0x900), (size - 1, size), (5, 5)]); + assert_eq!(look(&dirty).0, vec![Change::Parts(vec![(PAGE + 0x800, 3 * PAGE + 0x800), (6 * PAGE + 0x800, size)])], "the pages those bytes lie on"); + assert_eq!(look(&dirty).0, vec![Change::None]); + forget(&known); + unknown_parts(&known, src, size, &[(0, size)]); + assert_eq!(look(&dirty[2..3]).0, vec![Change::All], "nothing known: nothing to forget"); // several textures at once, many pages: the same as one by one let big = vec![7u8; 600 * PAGE]; let at = (big.as_ptr() as usize).next_multiple_of(PAGE); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 665264cb8d..7eedaca0c6 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1639,6 +1639,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { let _one = look.then(|| ONE_LOOK.lock().unwrap_or_else(|e| e.into_inner())); // (a submit without a look of its own takes these too: they are dirty by XCL's account) take_known(&mut dirty); + crate::hle::kernelx::guards::take_uploads(&mut dirty, page as usize); { let mut found = AHEAD.lock().unwrap(); ahead = found.len(); @@ -2073,6 +2074,13 @@ unsafe impl Send for QueueUploads {} static ON_QUEUE: Mutex> = Mutex::new(BTreeMap::new()); +/// The memory line of the texture upload buffers (`XCL_ACTIVITY`): system memory the process holds +/// for them, idle, and submitted but not yet taken back (`reclaim`: done on the GPU or not). +pub fn upload_line() -> String { + let in_flight: u64 = ON_QUEUE.lock().unwrap().values().map(|q| q.bytes).sum(); + format!("texture upload buffers: {} MB idle, {} MB submitted and not taken back yet", texture_upload::idle_bytes() >> 20, in_flight >> 20) +} + /// upload buffers the GPU has not read yet, before a submit waits for it: a moment past the first, /// in earnest past the second (a title's queue can stand at a wait that another submit ends) const IN_FLIGHT_BYTES: u64 = 512 << 20; @@ -2287,6 +2295,18 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option texture_upload::Change::Parts(p) => Some(p), }; let size = d.tex.size() as usize; + // (a texture with lazy levels: the levels with pages; the queue waits for the mappings + // made here before the copies, `vram::before_execute` below. A level left without pages + // may get its texels before a copy reads them, and a copy to its tiles is dropped: it is + // not read, and nothing is kept of what its pages hold) + let (changed, seen_to) = if super::vram::level_pages() { level_upload(&d, changed) } else { (changed, false) }; + if changed.as_ref().is_some_and(|p| p.is_empty()) { + return None; + } + if !seen_to && changed.is_none() { + // (before its bytes are read: what is written from here on is compared) + texture_upload::all_sent(&d.known, d.src, size); + } // (whole blocks go up, and whole volumes) const BLOCK: usize = 0x1_0000; let volume = d.tex.texels().is_some_and(|s| s.depth > 0); @@ -2297,29 +2317,9 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option while todo.peek().is_some() { let (mut items, mut known): (Vec, Vec) = (Vec::new(), Vec::new()); let (mut bytes, mut device) = (0usize, 0usize); - while let Some((d, mut changed, n)) = todo.next_if(|(d, _, n)| batch_fits(items.len(), bytes, device, d.device, *n)) { + while let Some((d, changed, n)) = todo.next_if(|(d, _, n)| batch_fits(items.len(), bytes, device, d.device, *n)) { device = d.device; bytes += n; - let mut unmapped = false; - if super::vram::level_pages() && super::vram::has_lazy_levels(d.res.as_raw() as usize) { - // (the queue waits for these mappings before the copies: `vram::before_execute` - // below; what a level's fresh pages held is another texture's, so all of it goes up) - if !map_levels_with_texels(&d.res, &subresources_in(d.src, &d.tex, d.pages.as_deref())).is_empty() { - changed = None; - } - unmapped = super::vram::has_unmapped_levels(d.res.as_raw() as usize); - } - if unmapped { - // A level left without pages (zeros when looked at above) may get its texels - // before the copy reads them: the copy to its tiles is dropped, and what it read - // must not be kept as what the PC texture holds – the next write then looks the - // same and the level never goes up. The next write sends all of it, and the level - // gets its pages then. - texture_upload::unknown(&d.known); - } else if changed.is_none() { - // (before its bytes are read: what is written from here on is compared) - texture_upload::all_sent(&d.known, d.src, d.tex.size() as usize); - } if super::present::trace_frame() { note_content(d.src, &d.res, &subresources_in(d.src, &d.tex, d.pages.as_deref())); } @@ -2420,6 +2420,236 @@ pub unsafe fn upload_and_wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue, re failed.into_iter().next().map_or(Ok(()), |(_, e)| Err(e)) } +/// Whether any byte of the title memory range `[va + off, va + end)` is non-zero, without +/// allocating per-texture buffers or detiling. Short-circuits on the first non-zero 64 KiB chunk. +unsafe fn range_any_nonzero(va: usize, off: usize, end: usize, pages: Option<&texture_upload::PageMap>) -> bool { + let Some(len) = end.checked_sub(off).filter(|&n| n > 0) else { + return false; + }; + let at = va + off; + if let Some(m) = pages { + return m.any_nonzero(at, len); + } + static SAFE: std::sync::OnceLock = std::sync::OnceLock::new(); + let safe = *SAFE.get_or_init(|| std::env::var("XCL_TEXTURE_SAFE_READ").is_ok_and(|v| v.trim() == "1")); + if !safe && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { + return !all_zero(std::slice::from_raw_parts(at as *const u8, len)); + } + thread_local! { + static CHUNK: std::cell::RefCell> = std::cell::RefCell::new(Vec::new()); + } + const STEP: usize = 0x1_0000; + CHUNK.with(|c| { + let mut buf = c.borrow_mut(); + if buf.len() < STEP { + buf.resize(STEP, 0); + } + let mut done = 0; + while done < len { + let n = STEP.min(len - done); + copy_readable(at + done, &mut buf[..n]); + if !all_zero(&buf[..n]) { + return true; + } + done += n; + } + false + }) +} + +/// Which mip levels of a 2D single-slice texture at `va` hold non-zero texels (`(present, zero)`). +/// +/// Non-tail levels occupy disjoint tiled byte ranges `[l.offset, next_offset)` in slice 0, and +/// tiling is a byte bijection (zero ↔ zero), so checking their raw bytes skips CPU detiling and +/// multi-MB temporary allocations. Packed tail levels share one `block_bytes` block at offset 0: +/// if that block is all zeros, every tail level is zero; otherwise only those tiny tail levels are +/// detiled from that single block. +unsafe fn levels_with_texels_in(va: usize, tex: &xg::Texture, pages: Option<&texture_upload::PageMap>) -> (Vec, Vec) { + levels_with_texels_where(va, tex, pages, |_| true) +} + +/// `levels_with_texels_in` of the levels `look` names only (the others are in neither list): a +/// level of zeros is read to its end to be found one, and a streamed texture is mostly such +/// levels, so the ones nothing was written to since they were found zeros are not read again. +/// The levels in the mip tail are one block: looked at together, if any of them is. +unsafe fn levels_with_texels_where(va: usize, tex: &xg::Texture, pages: Option<&texture_upload::PageMap>, look: impl Fn(usize) -> bool) -> (Vec, Vec) { + let Some(t) = tex.texels() else { + return (Vec::new(), Vec::new()); + }; + if t.depth > 0 || t.array != 1 { + let subs = subresources_in(va, tex, pages); + let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + let zero: Vec = (0..subs.len() as u32).filter(|l| !present.contains(l)).collect(); + return (present, zero); + } + let c = &t.chain; + let mips = c.levels.len(); + let mut present = Vec::with_capacity(mips); + let mut zero = Vec::with_capacity(mips); + let mut first_tail = mips; + for (i, l) in c.levels.iter().enumerate() { + if l.tail.is_some() { + first_tail = i; + break; + } + if !look(i) { + continue; + } + let end = if i == 0 { c.slice_bytes } else { c.levels[i - 1].offset }; + if range_any_nonzero(va, l.offset, end, pages) { + present.push(i as u32); + } else { + zero.push(i as u32); + } + } + if first_tail < mips && (first_tail..mips).any(&look) { + let tail_len = c.layout.block_bytes.min(c.slice_bytes); + if !range_any_nonzero(va, 0, tail_len, pages) { + for i in first_tail..mips { + zero.push(i as u32); + } + } else { + let tail_buf: std::borrow::Cow<'_, [u8]> = match pages { + Some(m) => { + let mut v = vec![0u8; tail_len]; + m.copy(va, &mut v); + std::borrow::Cow::Owned(v) + } + None => title_bytes(va, tail_len), + }; + for i in first_tail..mips { + if !all_zero(&c.detile_level(&tail_buf, i, 0)) { + present.push(i as u32); + } else { + zero.push(i as u32); + } + } + } + } + (present, zero) +} + +/// The bytes (from, to; sorted and joined) of a one-slice texture that `levels` of `c` take. +fn level_ranges(c: &crate::gpu::tiling::Chain, levels: impl Iterator) -> Vec<(usize, usize)> { + let mut r: Vec<(usize, usize)> = levels.filter(|&i| i < c.levels.len()).map(|i| c.level_bytes(i)).map(|r| (r.start, r.end)).collect(); + r.sort_unstable(); + match texture_upload::join(texture_upload::Change::Parts(Vec::new()), texture_upload::Change::Parts(r)) { + texture_upload::Change::Parts(r) => r, + _ => Vec::new(), + } +} + +/// `ranges` cut to what lies in `keep`, and what of them lies outside it (both sorted and disjoint). +fn split_ranges(ranges: &[(usize, usize)], keep: &[(usize, usize)]) -> (Vec<(usize, usize)>, Vec<(usize, usize)>) { + let (mut inside, mut outside) = (Vec::new(), Vec::new()); + for &(from, to) in ranges { + let mut at = from; + for &(a, z) in &keep[keep.partition_point(|k| k.1 <= from)..] { + if a >= to { + break; + } + if a > at { + outside.push((at, a)); + } + inside.push((a.max(at), z.min(to))); + at = z.min(to); + } + if at < to { + outside.push((at, to)); + } + } + (inside, outside) +} + +/// Uploads cut to the levels that have pages (`level_upload`): how many, their bytes, and the +/// bytes of their textures. +static LEVEL_UPLOADS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// (`vram::level_pages`) Before an upload of `changed` (None: all) of `d`: for a texture placed +/// with lazy levels, the levels that have texels now get their pages and those that lost them +/// give them back (as `map_levels_with_texels`), and what goes up is cut to the levels that have +/// pages – with the levels that got theirs just now as a whole (what a level's fresh pages held +/// is another texture's; the queue waits for these mappings before the copies, +/// `vram::before_execute`). Returns what goes up (None: all of it; nothing: no upload) and +/// whether what is kept of its pages (`texture_upload::Known`) was seen to here. +/// +/// A streamed texture is placed at its full size and has texels for its small levels only, most +/// of the time. Sending all of it at every write – it is not known what the PC texture holds +/// while a level has no pages, a copy to tiles without memory is dropped – detiled 9.5 GB in +/// 1024 submits of a retail title's world, most of them zeros for tiles that are not there, and +/// read each level of zeros to its end every time to find it one. So a level without pages is +/// not sent and nothing is kept of its pages: its next write is found changed, the level is +/// looked at then, and it goes up as a whole once it has texels. A level that had none and was +/// not written since has none now. +unsafe fn level_upload(d: &Due, changed: Option>) -> (Option>, bool) { + let key = d.res.as_raw() as usize; + let Some(had) = super::vram::levels_with_pages(key) else { return (changed, false) }; + let size = d.tex.size() as usize; + // (a texture that goes up as a whole when written, `Entry::target` and `XCL_TEXTURE_PARTS=0`, + // or not the kind that gets lazy levels: as before, all of it and nothing known) + let by_level = !d.target && upload_parts(); + let Some(c) = d.tex.texels().filter(|t| by_level && t.depth == 0 && t.array == 1 && t.chain.levels.len() == had.len()).map(|t| &t.chain) else { + let fresh = map_levels_with_texels_in(&d.res, d.src, &d.tex, d.pages.as_deref()); + let changed = if fresh.is_empty() { changed } else { None }; + if super::vram::has_unmapped_levels(key) { + texture_upload::unknown(&d.known); + return (changed, true); + } + return (changed, false); + }; + let written = |i: usize| { + let r = c.level_bytes(i); + changed.as_ref().is_none_or(|p| p.iter().any(|&(from, to)| from < r.end && to > r.start)) + }; + let (present, zero) = levels_with_texels_where(d.src, &d.tex, d.pages.as_deref(), |i| had[i] || written(i)); + super::vram::unmap_levels(&d.res, &zero); + let fresh = super::vram::map_levels(&d.res, Some(&present)); + let now = super::vram::levels_with_pages(key).unwrap_or_else(|| had.clone()); + if now.iter().all(|&m| m) && (fresh.is_empty() || changed.is_none()) { + return (changed, false); + } + let with_pages = level_ranges(c, (0..now.len()).filter(|&i| now[i])); + // (a level that gave its pages back: the PC texture holds zeros there now, not what its + // pages are known to have held – the same texels coming back are a change) + let lost = level_ranges(c, (0..now.len()).filter(|&i| had[i] && !now[i])); + texture_upload::unknown_parts(&d.known, d.src, size, &split_ranges(&lost, &with_pages).1); + let parts = match &changed { + None => { + // (before its bytes are read: what is written from here on is compared; the pages + // of the levels left out stay unknown) + texture_upload::all_sent(&d.known, d.src, size); + with_pages + } + Some(p) => { + let (inside, outside) = split_ranges(p, &with_pages); + texture_upload::unknown_parts(&d.known, d.src, size, &outside); + let fresh = level_ranges(c, fresh.iter().map(|&l| l as usize)); + match texture_upload::join(texture_upload::Change::Parts(inside), texture_upload::Change::Parts(fresh)) { + texture_upload::Change::Parts(r) => r, + _ => Vec::new(), + } + } + }; + let bytes: usize = parts.iter().map(|r| r.1 - r.0).sum(); + let n = LEVEL_UPLOADS[0].fetch_add(1, Ordering::Relaxed) + 1; + let sent = LEVEL_UPLOADS[1].fetch_add(bytes as u64, Ordering::Relaxed) + bytes as u64; + let of = LEVEL_UPLOADS[2].fetch_add(size as u64, Ordering::Relaxed) + size as u64; + if n >= 1024 && n.is_power_of_two() { + crate::xlog_info!("title textures: {n} uploads of textures with levels that have no pages: {} MB of their {} MB went up (the levels with pages that were written, and levels given pages)", sent >> 20, of >> 20); + } + (Some(parts), true) +} + +/// Fast zero-detile counterpart of `map_levels_with_texels` for the hot `upload_all` path. +unsafe fn map_levels_with_texels_in(r: &ID3D12Resource, va: usize, tex: &xg::Texture, pages: Option<&texture_upload::PageMap>) -> Vec { + if !super::vram::has_lazy_levels(r.as_raw() as usize) { + return Vec::new(); + } + let (present, zero) = levels_with_texels_in(va, tex, pages); + super::vram::unmap_levels(r, &zero); + super::vram::map_levels(r, Some(&present)) +} + /// (`vram::level_pages`) Before an upload of title texture `r`: its levels with texels in `subs` /// (its subresources as they go up) get their video memory pages if they have none, and those /// with pages and no texels now give them back (`vram::unmap_levels`) - a texture placed with @@ -2428,6 +2658,7 @@ pub unsafe fn upload_and_wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue, re /// `read_committed`). It keeps no pages, reads as zeros as it would with them, and its copy goes /// to tiles that are not mapped, which drops it (tiled resources tier 2). Returns the levels that /// got pages now (`vram::map_levels`). +#[cfg(test)] unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> Vec { if !super::vram::has_lazy_levels(r.as_raw() as usize) { return Vec::new(); @@ -2442,7 +2673,7 @@ unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> Ve } /// Whether every byte of `b` is zero (eight at a time: gigabytes a second where it is). -fn all_zero(b: &[u8]) -> bool { +pub(super) fn all_zero(b: &[u8]) -> bool { let mut words = b.chunks_exact(8); words.all(|w| u64::from_ne_bytes(w.try_into().unwrap()) == 0) && words.remainder().iter().all(|&x| x == 0) } @@ -4717,15 +4948,127 @@ pub(super) mod tests { // mip 0's texels come back: its pages too, the ones the other texture holds assert!(!VirtualAlloc((at + top) as *const c_void, size - top, MEM_COMMIT, PAGE_READWRITE).is_null()); std::ptr::copy_nonoverlapping(whole.as_ptr().add(top), (at + top) as *mut u8, size - top); - assert_eq!(map_levels_with_texels(&full, &subresources(at, &tex)), vec![0], "mip 0 got its pages again"); + assert_eq!(map_levels_with_texels_in(&full, at, &tex, None), vec![0], "mip 0 got its pages again via fast raw check"); assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some(all as u64)); assert!(read_sub(&full, 0) == want[0].data, "mip 0 on the pages the other texture kept"); + // The title lets mip 0 go once more and rewrites level 1: the upload of that write + // finds mip 0 zeros (it gives its pages back) and sends level 1 only, not all of it. + assert_ne!(VirtualFree((at + top) as *mut c_void, size - top, MEM_DECOMMIT), 0); + let l1 = chain.level_bytes(1); + let mut other = whole.clone(); + let pat: Vec = (0..chain.levels[1].width * chain.levels[1].height * surface.bpe as usize).map(|k| 3 + ((k * 29) % 250) as u8).collect(); + chain.tile_level(&mut other[..chain.slice_bytes], 1, 0, &pat); + let want1 = subresources(other.as_ptr() as usize, &tex)[1].data.clone(); + assert!(want1 != want[1].data); + std::ptr::copy_nonoverlapping(other.as_ptr().add(l1.start), (at + l1.start) as *mut u8, l1.len()); + note_known_write(at + l1.start, l1.len()); + let cut = |k: usize| LEVEL_UPLOADS[k].load(Ordering::Relaxed); + let (cut0, sent0, uploads0) = (cut(0), cut(1), UPLOADS.load(Ordering::Relaxed)); + refresh(queue.as_raw()); + assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some((all - top_tiles) as u64), "mip 0 gave its pages back at the upload"); + assert_eq!((cut(0) - cut0, cut(1) - sent0), (1, l1.len() as u64), "level 1's bytes went up, no others"); + assert_eq!(UPLOADS.load(Ordering::Relaxed), uploads0 + 1); + assert!(read_sub(&full, 1) == want1, "level 1 as it was rewritten"); + assert!(read_sub(&full, 2) == want[2].data, "level 2 as it was"); + // a write that changes nothing, while mip 0 has no pages: no upload (what the other + // levels' pages hold is still known) + let l2 = chain.level_bytes(2); + note_known_write(at + l2.start, l2.len()); + refresh(queue.as_raw()); + assert_eq!((UPLOADS.load(Ordering::Relaxed), cut(0)), (uploads0 + 1, cut0 + 1), "nothing changed: nothing went up"); + // mip 0's texels come back, the ones it held before: it gets its pages and goes up as + // a whole (what was known of its pages went with them), the other levels stay + assert!(!VirtualAlloc((at + top) as *const c_void, size - top, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::copy_nonoverlapping(whole.as_ptr().add(top), (at + top) as *mut u8, size - top); + note_known_write(at + top, size - top); + refresh(queue.as_raw()); + assert_eq!(super::super::vram::mapped_level_tiles(full_key), Some(all as u64), "mip 0 has its pages again"); + assert_eq!(UPLOADS.load(Ordering::Relaxed), uploads0 + 2); + assert!(read_sub(&full, 0) == want[0].data, "mip 0 went up with its pages"); + assert!(read_sub(&full, 1) == want1 && read_sub(&full, 2) == want[2].data, "the other levels as they were"); super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed); drop((small, full)); VirtualFree(at as *mut c_void, 0, MEM_RELEASE); } } + /// Only the levels asked about are read and reported, and the levels in the mip tail (one + /// block) together; the bytes of levels are their ranges in the slice, joined. + #[test] + fn levels_are_looked_at_one_by_one_and_their_bytes_are_ranges() { + unsafe { + let tex = xg::Texture::new(&console_desc(3, 1024, 1024, 1, 11, 87, 0x109)).unwrap(); + let c = &tex.texels().unwrap().chain; + let tail_i = c.first_tail(); + assert!(tail_i >= 3 && tail_i < 10, "levels of their own and a mip tail: {tail_i}"); + let mut buf = vec![0u8; tex.size() as usize]; + buf[c.levels[2].offset + 128] = 0x5A; + buf[c.levels[tail_i].tail.unwrap()] = 0xA5; + let at = buf.as_ptr() as usize; + assert_eq!(levels_with_texels_where(at, &tex, None, |i| i == 1 || i == 2), (vec![2], vec![1])); + assert_eq!(levels_with_texels_where(at, &tex, None, |_| false), (vec![], vec![])); + // (one level of the tail asked about: all of them are looked at) + let (present, zero) = levels_with_texels_where(at, &tex, None, |i| i == 10); + assert_eq!(present, vec![tail_i as u32]); + assert_eq!(zero, (tail_i as u32 + 1..11).collect::>()); + + let whole = level_ranges(c, 0..11); + assert_eq!(whole, vec![(0, c.slice_bytes)], "all levels: the slice"); + assert_eq!(level_ranges(c, [0, 2].into_iter()), vec![(c.levels[2].offset, c.levels[1].offset), (c.levels[0].offset, c.slice_bytes)]); + assert_eq!(level_ranges(c, tail_i..11), vec![(0, c.layout.block_bytes)], "the tail's levels share its block"); + } + } + + #[test] + fn ranges_are_split_at_what_is_kept() { + let keep = [(10, 20), (30, 40)]; + assert_eq!(split_ranges(&[(0, 5)], &keep), (vec![], vec![(0, 5)])); + assert_eq!(split_ranges(&[(12, 18)], &keep), (vec![(12, 18)], vec![])); + assert_eq!(split_ranges(&[(5, 35), (38, 50)], &keep), (vec![(10, 20), (30, 35), (38, 40)], vec![(5, 10), (20, 30), (40, 50)])); + assert_eq!(split_ranges(&[(20, 30)], &keep), (vec![], vec![(20, 30)]), "between two kept ranges"); + assert_eq!(split_ranges(&[(0, 50)], &[]), (vec![], vec![(0, 50)])); + } + + /// `levels_with_texels_in` agrees with full CPU detiling (`subresources_in`) on non-tail mips, + /// packed mip tails, zeroed top levels, and sparse `PageMap`s with unmapped pages. + #[test] + fn levels_with_texels_in_matches_detiled_subresources() { + unsafe { + // 64 KiB tiled (0x109) 1024x1024 R8G8B8A8 (format 87, 11 mips) with a packed mip tail. + let tex = xg::Texture::new(&console_desc(3, 1024, 1024, 1, 11, 87, 0x109)).unwrap(); + let c = &tex.texels().unwrap().chain; + assert!(c.levels.iter().any(|l| l.tail.is_some()), "test texture must exercise packed mip tail"); + let size = tex.size() as usize; + let mut buf = vec![0u8; size]; + // Populate one non-tail level (mip 2) and one packed tail level, leaving mip 0/1 zero. + let m2_at = c.levels[2].offset + 128; + let tail_i = c.levels.iter().position(|l| l.tail.is_some()).unwrap(); + let tail_at = c.levels[tail_i].tail.unwrap(); + buf[m2_at] = 0x5A; + buf[tail_at] = 0xA5; + let subs = subresources_in(buf.as_ptr() as usize, &tex, None); + let want_present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + let want_zero: Vec = (0..subs.len() as u32).filter(|l| !want_present.contains(l)).collect(); + assert_eq!(want_present, vec![2, tail_i as u32]); + assert_eq!(levels_with_texels_in(buf.as_ptr() as usize, &tex, None), (want_present.clone(), want_zero.clone())); + + // With a PageMap where only the tail page and mip 2's page are mapped (others 0). + const P: usize = 0x1_0000; + let base = 0x4000_0000usize; + let mut page_backing = vec![0u8; size.next_multiple_of(P)]; + page_backing[..size].copy_from_slice(&buf); + let n_pages = page_backing.len() / P; + let mut map = vec![0usize; n_pages]; + map[tail_at / P] = page_backing.as_ptr() as usize + (tail_at / P) * P; + map[m2_at / P] = page_backing.as_ptr() as usize + (m2_at / P) * P; + let pm = texture_upload::PageMap::new(base, map); + let subs_pm = subresources_in(base, &tex, Some(&pm)); + let want_pm: Vec = subs_pm.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + let zero_pm: Vec = (0..subs_pm.len() as u32).filter(|l| !want_pm.contains(l)).collect(); + assert_eq!(levels_with_texels_in(base, &tex, Some(&pm)), (want_pm, zero_pm)); + } + } + /// `read_committed` copies committed pages and leaves uncommitted gaps zeroed, including /// unaligned start/end offsets. #[test] diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 60c8ff49e0..5433d0dbc6 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2321,6 +2321,14 @@ pub(super) fn has_unmapped_levels(resource: usize) -> bool { PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).and_then(|t| t.levels.as_ref()).is_some_and(|l| l.groups.iter().any(|g| !g.3))) } +/// For a texture with lazy levels: whether each of its levels has pages now (the levels of a +/// group have them together). None: `resource` is not such a texture. +pub(super) fn levels_with_pages(resource: usize) -> Option> { + let g = PAGES.lock().unwrap(); + let l = g.values().flatten().find_map(|p| p.targets.get(&resource).and_then(|t| t.levels.as_ref()))?; + Some((0..l.mips).map(|i| l.groups[l.group_of(i)].3).collect()) +} + /// XG and the PC driver pack volume mip tails differently. Keep these textures on the /// detile/upload path rather than mapping title pages directly onto the driver's packed tail. fn console_has_packed_3d_mips(desc: &D3D12_RESOURCE_DESC) -> bool { diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 44546c0d97..7dbcf8aa22 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -861,7 +861,7 @@ fn cpu_range_in(p: usize, n: usize, in_view: impl Fn(usize) -> bool) -> Option bool { let Some(end) = p.checked_add(n) else { return false }; - crate::hle::kernelx::lazy::ensure(p, n); + let _opened = crate::hle::kernelx::lazy::ensure(p, n); if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 01b4c51a78..a7775458f7 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -108,6 +108,9 @@ pub fn exports() -> Vec<(&'static str, usize)> { pub const MEM_GRAPHICS: u32 = 0x1000_0000; mod placeholders; +pub mod alias; +pub mod guards; +mod sections; pub mod lazy; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; @@ -535,6 +538,11 @@ pub mod mirrors { .into_iter() .map(|(g, to)| { let to = to.map(|pool| { + if super::alias::enabled() { + let page = super::alias::page_at(pool).unwrap_or(0); + let (at, home) = super::alias::backing(page).unwrap_or((0, false)); + return (page, at, at != 0 && (home || super::freeing_is_seen(at))); + } let page = away.as_ref().and_then(|a| a.title.get(&pool).copied()).unwrap_or(0); let (at, home) = if page != 0 { super::place_of(away.as_ref(), page) } else { (0, false) }; (page, at, at != 0 && (home || super::freeing_is_seen(at))) @@ -930,6 +938,19 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u.view_release(q); } } + if alias::enabled() && !addr.is_null() && t & 0x1000 != 0 && alias::in_space(addr as usize) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("VirtualAlloc: a commit at {addr:p} in a reservation of 64 KiB pages that holds physical pages (XCL_PAGE_ALIAS) – refused")); + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return std::ptr::null_mut(); + } + if alias::enabled() && addr.is_null() && t & 0x2000 != 0 && t & 0x1000 == 0 && t & MEM_64K_PAGES == MEM_64K_PAGES { + if let Some(q) = alias::reserve_space(size) { + mirrors::reserved(q, size, t, p); + trace_mem("VirtualAlloc (64K pages, physical page space)", 0, size, t as u64, p, q); + return q as *mut c_void; + } + } // the title's own reservations of 64 KiB pages: in a sparse window, so the GPU sees them. // Skip CPU-inaccessible GPU-view mirror reservations (`PAGE_NOACCESS | PAGE_GRAPHICS_NOACCESS`): // their pixels live in the paired CPU view (`mirrors::source`), so putting them in sparse VA @@ -1190,6 +1211,11 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 if let Some(ok) = placeholders::free(addr, size, t) { return ok; } + if alias::enabled() { + if let Some(ok) = alias::free_space(addr as usize, size, t) { + return ok as BOOL; + } + } // the title's reservations in a sparse window: decommit (and on release give the address // space back); their video memory goes with it if let Some(u) = crate::gpu::uma::get().filter(|u| u.is_sparse(addr as usize)) { @@ -1307,7 +1333,7 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si if proc_ == thr::GetCurrentProcess() { let a = addr as usize; // (a graphics reservation's decommits too: one may be a paired CPU view, `source_going`) - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a) || u.is_view(a)) || in_graphics_reservation(a) { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a) || u.is_view(a)) || in_graphics_reservation(a) || alias::in_space(a) { return VirtualFree(addr, size, t); } } @@ -1358,6 +1384,9 @@ unsafe fn aligned_heap_alloc(size: usize, align: usize) -> *mut c_void { fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return std::ptr::null_mut(); } + if crate::heap_count::counting() { + crate::heap_count::title_added(total); + } let aligned = (raw + 16 + align - 1) & !(align - 1); *((aligned - 8) as *mut usize) = raw; aligned as *mut c_void @@ -1368,6 +1397,12 @@ unsafe fn aligned_heap_free(p: *mut c_void) { return; } let raw = *((p as usize - 8) as *const usize); + if crate::heap_count::counting() { + let size = mem::HeapSize(mem::GetProcessHeap(), 0, raw as *const c_void); + if size != usize::MAX { + crate::heap_count::title_removed(size); + } + } mem::HeapFree(mem::GetProcessHeap(), 0, raw as *const c_void); } @@ -1781,6 +1816,71 @@ pub mod pagelog { } } +/// A measurement: the addresses pages were moved away from (`move_away`: a page the title maps +/// at a second address while it is still mapped at the first is copied there, and the first +/// address is given up). On the console both addresses show the page until the title unmaps one. +/// So: how long after a move does the title unmap or map the address the page left – at once (it +/// moves pages), or not at all (it keeps two views of a page, and here the first is gone)? +pub mod given_up { + use std::collections::HashMap; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::Mutex; + use std::time::Instant; + + /// address the page left → (page, where it went, when, in the coherent window) + static LEFT: Mutex>> = Mutex::new(None); + static MOVES: AtomicU64 = AtomicU64::new(0); + /// the title's next call at such an address: unmapped it (page 0) within 1 ms, 100 ms, 10 s, + /// later; mapped another page there within the same steps + static NEXT: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + + pub fn moved(old: usize, at: usize, page: usize) { + let coherent = crate::gpu::uma::get().is_some_and(|u| u.is_committed(old)); + let n = MOVES.fetch_add(1, Ordering::Relaxed) + 1; + let mut g = LEFT.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + m.insert(old, (page, at, Instant::now(), coherent)); + if n.is_power_of_two() || n % 8192 == 0 { + let now = Instant::now(); + let ages: Vec = m.values().map(|v| now.saturating_duration_since(v.2).as_millis()).collect(); + let old_ones = ages.iter().filter(|&&a| a >= 1000).count(); + let in_coherent = m.values().filter(|v| v.3).count(); + let c: Vec = NEXT.iter().map(|c| c.load(Ordering::Relaxed)).collect(); + crate::xlog_info!( + "physical pages: {n} pages moved to a second address so far; the address they left was unmapped by the title {} times (within 1 ms {}, 100 ms {}, 10 s {}, later {}) and given another page {} times (within 1 ms {}, 100 ms {}, 10 s {}, later {}); {} such addresses the title has not touched since ({old_ones} for a second or more, the oldest {} s; {in_coherent} in the coherent window, where the old bytes stay readable)", + c[0] + c[1] + c[2] + c[3], c[0], c[1], c[2], c[3], + c[4] + c[5] + c[6] + c[7], c[4], c[5], c[6], c[7], + m.len(), + ages.iter().max().copied().unwrap_or(0) / 1000 + ); + } + } + + /// The title maps `page` (0: unmaps) at `at`. + pub fn title_maps(at: usize, page: usize) { + let mut g = LEFT.lock().unwrap_or_else(|e| e.into_inner()); + let Some((_, _, when, _)) = g.as_mut().and_then(|m| m.remove(&at)) else { return }; + let ms = when.elapsed().as_millis(); + let step = if ms < 1 { 0 } else if ms < 100 { 1 } else if ms < 10_000 { 2 } else { 3 }; + NEXT[step + if page == 0 { 0 } else { 4 }].fetch_add(1, Ordering::Relaxed); + } + + /// For a crash report: whether `addr` is in a page-sized range a page was moved away from + /// and the title has not mapped or unmapped since. + pub fn describe(addr: usize) -> String { + let Ok(g) = LEFT.try_lock() else { return String::new() }; + let Some(m) = g.as_ref() else { return String::new() }; + match m.get(&(addr & !(super::PHYS_PAGE - 1))) { + Some(&(page, to, when, coherent)) => format!( + "page {page:#x} was moved away from here to {to:#x} {} ms ago, and the title has not unmapped this address since{}", + when.elapsed().as_millis(), + if coherent { " (the coherent window: the old bytes stay readable here)" } else { "" } + ), + None => String::new(), + } + } +} + /// Size of one console physical page (64 KiB). pub const PHYS_PAGE_SIZE: usize = PHYS_PAGE; @@ -1829,6 +1929,7 @@ fn forget_title_mappings(base: usize, len: usize) { /// Whether a physical page is mapped at the page holding `va` away from its home – committed /// or not yet (`lazy`: a page never used is committed at its first access). pub fn physical_page_at(va: usize) -> bool { + if alias::enabled() { return alias::physical_page_at(va); } AWAY.lock().unwrap().as_ref().is_some_and(|a| a.at.contains_key(&(va & !(PHYS_PAGE - 1)))) } @@ -1837,6 +1938,7 @@ pub fn physical_page_at(va: usize) -> bool { /// is at one (`map_pages` moves it), so `d3d12x::vram` asks which page an address had to let /// textures at two addresses of one page share its video memory. pub fn physical_pages(va: usize, n: usize) -> Vec> { + if alias::enabled() { return (0..n).map(|i| va.checked_add(i.checked_mul(PHYS_PAGE)?).and_then(alias::page_at)).collect(); } let g = AWAY.lock().unwrap(); let Some(a) = g.as_ref() else { return vec![None; n] }; (0..n).map(|i| va.checked_add(i * PHYS_PAGE).and_then(|at| a.at.get(&at).copied())).collect() @@ -1916,6 +2018,7 @@ fn page_home(page: usize) -> Option { /// Whether every page of `pages` (at least one) is a physical page allocated now. pub fn physical_pages_live(pages: &[usize]) -> bool { + if alias::enabled() { return !pages.is_empty() && pages.iter().all(|&p| alias::page_live(p)); } !pages.is_empty() && pages.iter().all(|&p| page_home(p).is_some()) } @@ -1952,6 +2055,7 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u /// number from `AllocateTitlePhysicalPages`). Returns `false` if `offset >= PHYS_PAGE_SIZE`, /// `pages` is too short, or any page is not a live allocation. pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8]) -> bool { + if alias::enabled() { return alias::read(pages, offset, dst); } if dst.is_empty() { return offset < PHYS_PAGE; } @@ -1971,6 +2075,7 @@ pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8] /// Copy `src` into `pages` starting at `offset` within the first page. Validates every page /// before writing so the destination gets all bytes or nothing. pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) -> bool { + if alias::enabled() { return alias::write(pages, offset, src); } if src.is_empty() { return offset < PHYS_PAGE; } @@ -2289,6 +2394,7 @@ unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: } away.at.remove(&old); away.page.remove(&page); + given_up::moved(old, at, page); // (before its bytes come, as in `map_pages`) if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); @@ -2341,6 +2447,13 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return 0; }; + if alias::enabled() { + if alias::allocate(n, arr) { + return 1; + } + fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); + return 0; + } let Some(u) = crate::gpu::uma::get() else { fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return 0; @@ -2365,6 +2478,15 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } + if alias::enabled() { + let _serial = AWAY.lock().unwrap(); + let pages = std::slice::from_raw_parts(arr, n); + for &page in pages { + crate::hle::d3d12x::sparse::remapped(&mirrors::page_freed(page)); + } + alias::free(pages); + return 1; + } // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes if let Some(away) = AWAY.lock().unwrap().as_mut() { for i in 0..n { @@ -2413,11 +2535,27 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _ let _cost = super::api_cost::time(super::api_cost::Call::PhysicalPages); let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); + if alias::enabled() { return map_aliased(va, n, arr); } let r = map_pages(away, va, n, arr); give_back_homes(away); r } +/// Map section-backed guest pages while preserving this branch's GPU-view record. +unsafe fn map_aliased(va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { + if va.is_null() || n == 0 || n.checked_mul(PHYS_PAGE).and_then(|len| (va as usize).checked_add(len)).is_none() { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return std::ptr::null_mut(); + } + let empty; + let pages = if arr.is_null() { empty = vec![0; n]; empty.as_slice() } else { std::slice::from_raw_parts(arr, n) }; + if alias::map(va as usize, pages) { + note_mapping_range(va as usize, n * PHYS_PAGE); + return va; + } + std::ptr::null_mut() +} + /// `MapTitlePhysicalPages` with `AWAY` held; the homes it moves away are given back by the /// caller (`give_back_homes`). unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { @@ -2476,6 +2614,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let mut sparse_run = SparseRun::new(crate::hle::d3d12x::sparse::committed); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; + given_up::title_maps(at, p); // what was mapped at `at` goes; the new page is written down once it is in place away.title.remove(&at); if unmap_away(away, at, &(0..0)) { @@ -2587,6 +2726,9 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); + if alias::enabled() { + return (0..n).all(|i| !map_aliased(*addresses.add(i), 1, if pages.is_null() { std::ptr::null_mut() } else { pages.add(i).cast() }).is_null()) as BOOL; + } // no page array: page 0 (unmap) for every address let ok = (0..n).all(|i| { // a part of the call that only unmaps diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs new file mode 100644 index 0000000000..af8debe63e --- /dev/null +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -0,0 +1,672 @@ +//! Physical pages that show at every address they are mapped at (`XCL_PAGE_ALIAS=1`). +//! +//! Without it a physical page is kept at one address at a time and moved (copied) when the +//! title maps it elsewhere. With it a block of physical pages is a section (`sections`): the +//! title's reservations of 64 KiB pages are placeholders ("spaces"), and mapping a page there +//! maps a view of its slice, so every address the title mapped it at shows the same memory. +//! The views are guarded (`guards`): a write through one is uploaded at all of them. +//! +//! Each block also has a view of its own (its home, never given to the title) through which +//! XCL reads and writes pages by number (DirectStorage destinations). A retail title never maps +//! a page at its home, so homes are plain address space, not the GPU-visible sparse windows. +//! +//! A page mapped at an address outside a space (a placeholder region the title made in a +//! sparse window) is moved there as before: its bytes are copied there and back again when it +//! is unmapped. While it is away its views show what it held when it left. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows_sys::Win32::Foundation as fnd; +use windows_sys::Win32::System::Memory as mem; + +use super::sections::{self, Section, PAGE}; +use super::{guards, lazy, page_index, page_number, NEXT_PAGE_INDEX}; + +/// `XCL_PAGE_ALIAS=1` turns physical page aliasing on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PAGE_ALIAS").is_ok_and(|v| v.trim() == "1")) +} + +struct Block { + section: Arc
, + /// XCL's own view of the whole block + home: usize, + /// pages not freed yet + live: usize, + /// one bit a page: committed (asking Windows walked the rest of a block's uncommitted run – + /// a retail title mapping 100 000 fresh pages one at a time waited 20 s for its first frame) + committed: Arc>, +} + +#[derive(Default)] +struct State { + /// first page index → block + blocks: BTreeMap, + /// the title's reservations kept as placeholders: base → size + spaces: BTreeMap, + /// address (64 KiB) in a space → (page number, its section, the page's index in it) + views: BTreeMap, usize)>, + /// pages moved to an address outside the spaces: page → address, and address → page + away: HashMap, + away_at: BTreeMap, +} + +static STATE: Mutex> = Mutex::new(None); +/// Whether any aliased view was ever mapped: `committed_at` sits on the lazy fault path and takes +/// no lock before then. +static ACTIVE: AtomicBool = AtomicBool::new(false); + +fn with(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +impl State { + /// (block's section, the page's index in it, its address in the home view) of page number `page` + fn page(&self, page: usize) -> Option<(Arc
, usize, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + let i = index - first; + (i < b.section.pages()).then(|| (b.section.clone(), i, b.home + i * PAGE)) + } + + /// The commit bits of page number `page`'s block and its index there. + fn bits(&self, page: usize) -> Option<(Arc>, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + (index - first < b.section.pages()).then(|| (b.committed.clone(), index - first)) + } + + fn in_space(&self, at: usize) -> bool { + self.spaces.range(..=at).next_back().is_some_and(|(&b, &n)| at < b + n) + } +} + +/// Whether page number `page` is committed (a page never used is not). +fn committed(page: usize) -> bool { + with(|s| s.bits(page)).is_some_and(|(b, i)| b[i / 64].load(Ordering::Acquire) & (1 << (i % 64)) != 0) +} + +/// Page number `page` is committed now. +fn note_committed(page: usize) { + if let Some((b, i)) = with(|s| s.bits(page)) { + b[i / 64].fetch_or(1 << (i % 64), Ordering::AcqRel); + } +} + +/// The view at `view` was committed by the lazy handler (its page's first use). +pub fn committed_at(view: usize) { + if !ACTIVE.load(Ordering::Acquire) { + return; + } + if let Some(page) = with(|s| s.views.get(&(view & !(PAGE - 1))).map(|v| v.0)) { + note_committed(page); + } +} + +/// A reservation of 64 KiB pages the title will map physical pages into: a space. None if +/// Windows refuses the address space. +pub fn reserve_space(size: usize) -> Option { + let len = size.checked_next_multiple_of(PAGE)?; + // SAFETY: only address space is reserved; `free_space` releases it. + let at = unsafe { sections::reserve(None, len) }?; + with(|s| s.spaces.insert(at, len)); + Some(at) +} + +/// Whether `p` lies in a space. +pub fn in_space(p: usize) -> bool { + enabled() && with(|s| s.in_space(p)) +} + +/// `VirtualFree` of an address in a space: release (the whole space) unmaps its pages and gives +/// the address space back; decommit unmaps the pages of the range. None: not a space. +pub unsafe fn free_space(addr: usize, size: usize, t: u32) -> Option { + let (base, len) = with(|s| s.spaces.range(..=addr).next_back().filter(|(&b, &n)| addr < b + n).map(|(&b, &n)| (b, n)))?; + if t & mem::MEM_RELEASE != 0 { + if addr != base || size != 0 { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return Some(false); + } + let part = super::source_part(base, len); + unmap_range(base, len); + with(|s| s.spaces.remove(&base)); + super::source_part_going(part, true, || { + super::mirrors::released(base); + sections::release_all(base, len); + }); + return Some(true); + } + let end = if size == 0 { base + len } else { addr.saturating_add(size).min(base + len) }; + unmap_range(addr & !(PAGE - 1), end - (addr & !(PAGE - 1))); + Some(true) +} + +unsafe fn unmap_range(at: usize, len: usize) { + let views: Vec = with(|s| { + let keys: Vec = s.views.range(at..at + len).map(|(&a, _)| a).collect(); + for &a in &keys { + s.views.remove(&a); + } + keys + }); + if views.is_empty() { + return; + } + for &a in &views { + guards::forget(a); + lazy::unmark(a); + } + let lo = *views.first().unwrap(); + let hi = *views.last().unwrap() + PAGE; + super::source_going(lo, hi - lo, false, || { + for &a in &views { + sections::unmap(a); + } + }); +} + +/// `count` physical pages for the title; their numbers in `arr`. +pub unsafe fn allocate(n: usize, arr: *mut usize) -> bool { + let Some(section) = Section::new(n) else { + crate::xlog_warn!("physical pages: a section of {n} pages could not be made"); + return false; + }; + let Some(home) = sections::reserve(None, n * PAGE) else { return false }; + if !section.map(0, n, home) { + sections::release(home); + return false; + } + let first = NEXT_PAGE_INDEX.fetch_add(n, Ordering::Relaxed); + for i in 0..n { + *arr.add(i) = page_number(first + i); + } + let committed = Arc::new((0..n.div_ceil(64)).map(|_| AtomicU64::new(0)).collect()); + with(|s| s.blocks.insert(first, Block { section: Arc::new(section), home, live: n, committed })); + true +} + +/// The title frees `pages`. Addresses that show one keep showing it (the title is meant to unmap +/// first); a block whose pages are all freed loses its home. +pub unsafe fn free(pages: &[usize]) { + let mut homes = Vec::new(); + with(|s| { + for &page in pages { + if let Some(at) = s.away.remove(&page) { + s.away_at.remove(&at); + } + let Some(index) = page_index(page) else { continue }; + let Some((&first, b)) = s.blocks.range_mut(..=index).next_back() else { continue }; + if index >= first + b.section.pages() { + continue; + } + b.live = b.live.saturating_sub(1); + if b.live == 0 { + homes.push((b.home, b.section.pages() * PAGE)); + s.blocks.remove(&first); + } + } + }); + for (home, len) in homes { + super::source_going(home, len, true, || { + sections::unmap(home); + sections::release(home); + }); + } +} + +/// Map `n` pages (`pages[i]`, 0: unmap) at `va`. Pages at an address in a space are views of +/// them; elsewhere they are moved there. False with the last error set if a page is not one of +/// the title's or Windows refuses. +pub unsafe fn map(va: usize, pages: &[usize]) -> bool { + if !va.is_multiple_of(PAGE) { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + if pages.is_empty() { + return true; + } + let end = match pages.len().checked_mul(PAGE).and_then(|n| va.checked_add(n)) { + Some(e) => e, + None => { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + }; + // Validate every non-zero page and pull out any existing views in `[va, end)` under one lock + // so unmapping a batch of views takes a single `source_going` / `sparse::STATE` round-trip. + let (valid, old_views) = with(|s| { + if pages.iter().any(|&p| p != 0 && s.page(p).is_none()) { + return (false, Vec::new()); + } + let keys: Vec = s.views.range(va..end).map(|(&a, _)| a).collect(); + for &a in &keys { + s.views.remove(&a); + } + (true, keys) + }); + if !valid { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + if !old_views.is_empty() { + for &a in &old_views { + guards::forget(a); + lazy::unmark(a); + } + let lo = *old_views.first().unwrap(); + let hi = *old_views.last().unwrap() + PAGE; + super::source_going(lo, hi - lo, false, || { + for &a in &old_views { + sections::unmap(a); + } + }); + } + for (i, &page) in pages.iter().enumerate() { + let at = va + i * PAGE; + if !map_one(at, page) { + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return false; + } + } + true +} + +unsafe fn map_one(at: usize, page: usize) -> bool { + // what was at `at` goes first (any prior view in `[va, end)` was already unmapped by `map`) + let (had_away, old_away, info, in_sp) = with(|s| { + let had_away = s.away_at.contains_key(&at); + if page == 0 { + return (had_away, None, None, false); + } + let old_away = s.away.get(&page).copied(); + let info = s.page(page); + let in_sp = s.in_space(at); + (had_away, old_away, info, in_sp) + }); + if had_away { + unmap_away(at); + } + if page == 0 { + return true; + } + // a page moved elsewhere comes home first (it is at one address outside the spaces at most, + // as before): its views then show what it holds + if let Some(old) = old_away { + unmap_away(old); + } + let (section, index, home) = info.unwrap(); + if in_sp { + if !section.map(index, 1, at) { + return false; + } + let is_committed = committed(page); + ACTIVE.store(true, Ordering::Release); + with(|s| s.views.insert(at, (page, section, index))); + guards::watch_with(page, at, is_committed); + if is_committed { + // an already-committed page mapped at a new view: sparse / title_textures must see it + guards::written(page); + } else { + // a page never used: committed at its first touch here (or through its home) + lazy::mark(at); + } + return true; + } + move_to(at, page, home) +} + +/// Page `page` moved to `at`, an address outside the spaces: committed there with its bytes. +unsafe fn move_to(at: usize, page: usize, home: usize) -> bool { + let u = crate::gpu::uma::get(); + let ok = if u.is_some_and(|u| u.is_committed(at)) { + true + } else if u.is_some_and(|u| u.is_sparse(at)) { + !super::commit_sparse(at, PAGE, mem::PAGE_READWRITE).is_null() + } else { + !mem::VirtualAlloc(at as *const c_void, PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() + }; + if !ok { + return false; + } + if committed(page) { + std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PAGE); + } else { + std::ptr::write_bytes(at as *mut u8, 0, PAGE); + } + with(|s| { + s.away.insert(page, at); + s.away_at.insert(at, page); + }); + true +} + +/// The page moved to `at` (if any) goes home with what `at` holds; `at` is decommitted. +unsafe fn unmap_away(at: usize) { + let Some((page, home)) = with(|s| { + let page = s.away_at.remove(&at)?; + s.away.remove(&page); + Some((page, s.page(page)?.2)) + }) else { + return; + }; + if sections::commit(home, PAGE) { + note_committed(page); + std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PAGE); + guards::written(page); + } + let u = crate::gpu::uma::get(); + if u.is_some_and(|u| u.is_committed(at)) { + return; + } + if u.is_some_and(|u| u.is_sparse(at)) { + crate::hle::d3d12x::sparse::decommitted(at, PAGE); + } + super::source_going(at, PAGE, false, || mem::VirtualFree(at as *mut c_void, PAGE, mem::MEM_DECOMMIT)); +} + +/// Whether a physical page is mapped at the page holding `va` (a view, or a page moved there). +pub fn physical_page_at(va: usize) -> bool { + let at = va & !(PAGE - 1); + with(|s| s.views.contains_key(&at) || s.away_at.contains_key(&at)) +} + +/// Whether `page` is a physical page allocated now. +pub fn page_live(page: usize) -> bool { + with(|s| s.page(page).is_some()) +} + +/// The physical page mapped at the page holding `va` (a view, or a page moved there), or None. +pub fn page_at(va: usize) -> Option { + let at = va & !(PAGE - 1); + with(|s| s.views.get(&at).map(|v| v.0).or_else(|| s.away_at.get(&at).copied())) +} + +/// Current storage for a page in the GPU-view mapping record. Section-backed aliases +/// all share the block's home. Ordinary sparse reservations can temporarily own its bytes. +pub(super) fn backing(page: usize) -> Option<(usize, bool)> { + with(|s| s.away.get(&page).map(|&at| (at, false)).or_else(|| s.page(page).map(|(_, _, home)| (home, true)))) +} + +/// The spaces and the blocks' homes as (base, bytes), each by address (`mem_map`). +pub fn ranges() -> (Vec<(usize, usize)>, Vec<(usize, usize)>) { + let (spaces, mut homes): (Vec<_>, Vec<_>) = with(|s| (s.spaces.iter().map(|(&b, &n)| (b, n)).collect(), s.blocks.values().map(|b| (b.home, b.section.pages() * PAGE)).collect())); + homes.sort_unstable(); + (spaces, homes) +} + +/// What one call of the queue's page-mapping method did, in 64 KiB pages. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Applied { + /// destination pages that show a physical page now + pub mapped: u64, + /// destination pages unmapped (by the call, or because nothing was mapped at their pool page) + pub unmapped: u64, + /// of those, pages whose pool page had nothing mapped + pub empty_pool: u64, +} + +/// The queue's page-mapping method (`CopyPageMappingsBatchX`, decoded by +/// `mirrors::decode_batches`): each destination page shows the physical page mapped at its pool +/// page now – on the console the method copies the pool page's mapping – or nothing. +pub unsafe fn apply_page_mappings(changes: &[(usize, Option)]) -> Option { + let mut out = Applied::default(); + for &(dest, pool) in changes { + let page = pool.and_then(page_at); + if !map_one(dest & !(PAGE - 1), page.unwrap_or(0)) { + return None; + } + match (pool, page) { + (_, Some(_)) => out.mapped += 1, + (Some(_), None) => { + out.unmapped += 1; + out.empty_pool += 1; + } + (None, _) => out.unmapped += 1, + } + } + Some(out) +} + +/// Where page `page`'s bytes are now (committing its home if `write`), or None. +unsafe fn bytes_of(page: usize, write: bool) -> Option<(usize, bool)> { + let (away, home) = with(|s| (s.away.get(&page).copied(), s.page(page).map(|p| p.2))); + if let Some(at) = away { + return Some((at, true)); + } + let home = home?; + if committed(page) { + return Some((home, true)); + } + if write { + if !sections::commit(home, PAGE) { + return None; + } + note_committed(page); + return Some((home, true)); + } + Some((home, false)) +} + +/// `read_physical_pages` in alias mode. +pub unsafe fn read(pages: &[usize], offset: usize, dst: &mut [u8]) -> bool { + copy_pages(pages, offset, dst.len(), |addr, done, n| { + match addr { + Some(a) => std::ptr::copy_nonoverlapping(a as *const u8, dst.as_mut_ptr().add(done), n), + None => std::ptr::write_bytes(dst.as_mut_ptr().add(done), 0, n), + } + }, false) +} + +/// `write_physical_pages` in alias mode. +pub unsafe fn write(pages: &[usize], offset: usize, src: &[u8]) -> bool { + copy_pages(pages, offset, src.len(), |addr, done, n| { + if let Some(a) = addr { + std::ptr::copy_nonoverlapping(src.as_ptr().add(done), a as *mut u8, n); + } + }, true) +} + +/// Walk `len` bytes from `offset` in `pages`, calling `f(address or None for a page never used, +/// bytes done, bytes here)`. All pages are checked before any byte is touched. +unsafe fn copy_pages(pages: &[usize], offset: usize, len: usize, mut f: impl FnMut(Option, usize, usize), write: bool) -> bool { + if len == 0 { + return offset < PAGE; + } + let Some(need) = offset.checked_add(len).map(|end| end.div_ceil(PAGE)) else { return false }; + if offset >= PAGE || pages.len() < need { + return false; + } + let mut addrs = Vec::with_capacity(need); + for &p in &pages[..need] { + let Some(a) = bytes_of(p, write) else { return false }; + addrs.push((p, a)); + } + let (mut done, mut off) = (0, offset); + for (page, (addr, used)) in addrs { + let n = (PAGE - off).min(len - done); + f(used.then_some(addr + off), done, n); + if write && with(|s| !s.away.contains_key(&page)) { + guards::written(page); + } + done += n; + off = 0; + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + /// alias state and guards are one per process: these tests run one at a time, and not + /// beside the guards' own + use super::guards::tests::SERIAL; + + unsafe fn read64(at: usize) -> u64 { + std::ptr::read_volatile(at as *const u64) + } + + unsafe fn write64(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + fn pages(n: usize) -> Vec { + let mut arr = vec![0usize; n]; + assert!(unsafe { allocate(n, arr.as_mut_ptr()) }); + arr + } + + fn dirty() -> Vec { + let mut out = Vec::new(); + guards::take_dirty(&mut out, PAGE); + out.sort_unstable(); + out + } + + #[test] + fn a_page_mapped_into_two_spaces_is_one_page_and_writes_reach_both() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(4); + let cpu = reserve_space(8 * PAGE).unwrap(); + let gpu = reserve_space(8 * PAGE).unwrap(); + unsafe { + assert!(map(cpu + 2 * PAGE, &p[1..3])); + assert!(map(gpu + 5 * PAGE, &[p[2]])); + assert!(physical_page_at(gpu + 5 * PAGE + 123)); + write64(cpu + 3 * PAGE + 8, 0xABCD); // page p[2] through the first space + assert_eq!(read64(gpu + 5 * PAGE + 8), 0xABCD, "the other space shows the same page"); + dirty(); + write64(gpu + 5 * PAGE, 1); + let mut want = vec![cpu + 3 * PAGE, gpu + 5 * PAGE]; + want.sort_unstable(); + assert_eq!(dirty(), want, "a write through one view: both are uploaded"); + assert_eq!(free_space(cpu, 0, mem::MEM_RELEASE), Some(true)); + assert_eq!(read64(gpu + 5 * PAGE + 8), 0xABCD, "releasing one space leaves the page at the other"); + assert_eq!(free_space(gpu, 0, mem::MEM_RELEASE), Some(true)); + free(&p); + } + } + + #[test] + fn remapping_an_address_shows_the_new_page_and_keeps_the_old_one() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(2); + let s = reserve_space(2 * PAGE).unwrap(); + unsafe { + assert!(map(s, &[p[0]])); + write64(s, 11); + assert!(map(s, &[p[1]])); + assert_eq!(read64(s), 0, "a page never written reads zeros"); + assert!(map(s, &[0])); + assert!(!physical_page_at(s)); + assert!(map(s + PAGE, &[p[0]])); + assert_eq!(read64(s + PAGE), 11, "the first page kept what was written to it"); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + } + } + + #[test] + fn pages_read_and_written_by_number_are_the_pages_the_title_sees() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(3); + let s = reserve_space(3 * PAGE).unwrap(); + unsafe { + assert!(map(s, &p)); + dirty(); + // a DirectStorage destination: 16 bytes across the boundary of the first two pages + assert!(write(&p, PAGE - 8, &[7u8; 16])); + assert_eq!(read64(s + PAGE - 8), 0x0707_0707_0707_0707); + assert_eq!(read64(s + PAGE), 0x0707_0707_0707_0707); + assert_eq!(dirty(), vec![s, s + PAGE], "pages written by number are uploaded where they are mapped"); + write64(s + 2 * PAGE + 16, 5); + let mut back = [0u8; 8]; + assert!(read(&p[2..], 16, &mut back)); + assert_eq!(u64::from_le_bytes(back), 5); + let mut fresh = [1u8; 4]; + let q = pages(1); + assert!(read(&q, 0, &mut fresh)); + assert_eq!(fresh, [0; 4], "a page never used reads zeros without being committed"); + assert!(!read(&p, PAGE, &mut back), "an offset past the first page is refused"); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + free(&q); + } + } + + #[test] + fn a_page_moved_outside_the_spaces_goes_and_comes_back_with_its_bytes() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(1); + let s = reserve_space(PAGE).unwrap(); + // address space outside the spaces (as a title's own placeholder region would be) + let out = unsafe { mem::VirtualAlloc(std::ptr::null(), PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) } as usize; + unsafe { + assert!(map(s, &p)); + write64(s, 21); + assert!(map(out, &p)); + assert_eq!(read64(out), 21, "moved with its bytes"); + assert!(physical_page_at(out)); + write64(out, 22); + let mut b = [0u8; 8]; + assert!(read(&p, 0, &mut b)); + assert_eq!(u64::from_le_bytes(b), 22, "read by number where it is now"); + assert!(map(out, &[0])); + assert_eq!(read64(s), 22, "back home with what it held there"); + free_space(s, 0, mem::MEM_RELEASE); + mem::VirtualFree(out as *mut c_void, 0, mem::MEM_RELEASE); + free(&p); + } + } + + #[test] + fn the_queue_page_mapping_method_shows_the_pool_pages_physical_page_in_the_gpu_view() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(2); + let pool = reserve_space(4 * PAGE).unwrap(); + let cpu = reserve_space(4 * PAGE).unwrap(); + let gpu = reserve_space(4 * PAGE).unwrap(); + unsafe { + // a streamed page: in the pool and in the CPU view, written through the CPU view + assert!(map(pool + PAGE, &[p[0]])); + assert!(map(cpu + 2 * PAGE, &[p[0]])); + write64(cpu + 2 * PAGE, 0x5EED); + // kind 0 / 1: pool pages at GPU-view pages; pool page 3 holds nothing; kind 2: unmapped + let changes = [(gpu, Some(pool + PAGE)), (gpu + PAGE, Some(pool + PAGE)), (gpu + 2 * PAGE, Some(pool + 3 * PAGE)), (gpu + 3 * PAGE, None)]; + let done = apply_page_mappings(&changes).unwrap(); + assert_eq!(done, Applied { mapped: 2, unmapped: 2, empty_pool: 1 }); + assert_eq!(read64(gpu), 0x5EED, "the GPU view shows the page the CPU view wrote"); + assert_eq!(read64(gpu + PAGE), 0x5EED, "one pool page at two GPU-view pages"); + assert!(!physical_page_at(gpu + 2 * PAGE) && !physical_page_at(gpu + 3 * PAGE)); + dirty(); + write64(gpu + PAGE + 8, 1); + let mut want = vec![pool + PAGE, cpu + 2 * PAGE, gpu, gpu + PAGE]; + want.sort_unstable(); + assert_eq!(dirty(), want, "a write in the GPU view: every view of the page is uploaded"); + // the pool page is given another physical page later: the GPU view keeps the one it was given + assert!(map(pool + PAGE, &[p[1]])); + assert_eq!(read64(gpu), 0x5EED); + assert_eq!(page_at(gpu), Some(p[0])); + for s in [pool, cpu, gpu] { + free_space(s, 0, mem::MEM_RELEASE); + } + free(&p); + } + } + + #[test] + fn a_page_not_from_the_title_is_refused() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let s = reserve_space(PAGE).unwrap(); + unsafe { + assert!(!map(s, &[page_number(1 << 40)])); + assert!(!map(s + 4, &[0]), "an address not on a page boundary is refused"); + free_space(s, 0, mem::MEM_RELEASE); + } + } +} diff --git a/crates/xcl/src/hle/kernelx/guards.rs b/crates/xcl/src/hle/kernelx/guards.rs new file mode 100644 index 0000000000..309adc18df --- /dev/null +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -0,0 +1,480 @@ +//! CPU writes to the views of physical pages, caught page by page. +//! +//! The upload of title memory to video memory (`d3d12x::sparse`) learns what the CPU wrote from +//! the write watch, and a view of a section (`sections`) cannot be write-watched. So the views +//! of a physical page are kept read-only: the first write through any of them faults, the +//! handler makes that view writable again and notes the page, and the write goes on. Before the +//! title's next submit `take_dirty` hands over the pages of every view of each page written – +//! a write through one view is a write to all of them – and guards them again. +//! +//! A kernel call does not fault into the handler: it fails. Memory a kernel call or XCL is about +//! to write goes through `lazy::ensure`, which opens the guards there first (`open`). + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, Once}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_READONLY, PAGE_READWRITE}; + +const PAGE: usize = 0x1_0000; +const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; + +#[derive(Default)] +struct State { + /// view page (64 KiB aligned) → the physical page it shows + at: HashMap, + /// physical page → the view pages that show it + views: HashMap>, + /// physical pages written since the last `take_dirty` + dirty: HashSet, + /// views opened for a write still going on (`Opened`): not guarded again until it ends + pinned: HashMap, + /// overlapped reads into views: (the OVERLAPPED, its views kept open until it is done) + pending: Vec<(usize, Opened)>, +} + +static STATE: Mutex> = Mutex::new(None); + +/// Whether any view was ever watched: `open` and `committed` sit on the file-read and +/// DirectStorage paths and take no lock before then. +static WATCHING: AtomicBool = AtomicBool::new(false); + +fn with(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +fn install() { + static ONCE: Once = Once::new(); + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +unsafe fn protect(view: usize, p: u32) -> bool { + let mut old = 0; + VirtualProtect(view as *const c_void, PAGE, p, &mut old) != 0 +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + // a write (access 1) to a guarded view + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1 { + return EXCEPTION_CONTINUE_SEARCH; + } + let view = r.ExceptionInformation[1] & !(PAGE - 1); + // (a view not committed yet cannot be opened: that fault is `lazy`'s, which commits the page + // and counts it as written – claimed here, the write would fault again for ever) + let ours = with(|s| match s.at.get(&view) { + Some(&page) if unsafe { protect(view, PAGE_READWRITE) } => { + s.dirty.insert(page); + true + } + _ => false, + }); + // (another thread may have opened the view between the fault and here: writable now) + if ours || writable(view) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } +} + +/// Whether `view` is a guarded view that is writable now. +fn writable(view: usize) -> bool { + if !with(|s| s.at.contains_key(&view)) { + return false; + } + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + let n = unsafe { VirtualQuery(view as *const c_void, &mut m, std::mem::size_of_val(&m)) }; + n != 0 && m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE +} + +/// Physical page `page` is shown at `view` (64 KiB aligned): writes there are caught from now on. +/// A view not committed yet cannot be guarded; `committed` notes it when it is. +pub fn watch(page: usize, view: usize) { + watch_with(page, view, true); +} + +/// Like `watch`, but skips the `VirtualProtect` syscall when `already_committed` is false +/// (an uncommitted view cannot be protected yet and will be marked dirty when lazily committed). +pub fn watch_with(page: usize, view: usize, already_committed: bool) { + install(); + WATCHING.store(true, Ordering::Release); + with(|s| { + if let Some(old) = s.at.insert(view, page).filter(|&old| old != page) { + if let Some(v) = s.views.get_mut(&old) { + v.retain(|&a| a != view); + } + } + let v = s.views.entry(page).or_default(); + if !v.contains(&view) { + v.push(view); + } + if already_committed { + unsafe { protect(view, PAGE_READONLY) }; + } + }); +} + +/// `view` no longer shows a physical page (it was unmapped): its writes are not looked for. +pub fn forget(view: usize) { + with(|s| { + if let Some(page) = s.at.remove(&view) { + if let Some(v) = s.views.get_mut(&page) { + v.retain(|&a| a != view); + if v.is_empty() { + s.views.remove(&page); + s.dirty.remove(&page); + } + } + } + }); +} + +/// `view` was committed just now (it reads zeros and is writable): its page counts as written. +pub fn committed(view: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if let Some(&page) = s.at.get(&(view & !(PAGE - 1))) { + s.dirty.insert(page); + } + }); +} + +/// Physical page `page` was written other than through a view (XCL by page number, or the page +/// came back from an address outside the views): every view of it counts as written. +pub fn written(page: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if s.views.contains_key(&page) { + s.dirty.insert(page); + } + }); +} + +/// Views opened by `open` for a write: they stay writable until this is dropped, when the write +/// is over and their pages count as written again. +#[must_use = "the views stay open only while this lives"] +pub struct Opened(Vec); + +impl Drop for Opened { + fn drop(&mut self) { + if self.0.is_empty() { + return; + } + with(|s| { + for view in self.0.drain(..) { + if let Some(n) = s.pinned.get_mut(&view) { + *n -= 1; + if *n == 0 { + s.pinned.remove(&view); + } + } + if let Some(&page) = s.at.get(&view) { + s.dirty.insert(page); + } + } + }); + } +} + +/// `[p, p + len)` is about to be written by a kernel call or XCL: the views there are made +/// writable, stay so while the returned `Opened` lives (a kernel call fails on a view guarded +/// again under it), and their pages count as written. +pub fn open(p: usize, len: usize) -> Opened { + if len == 0 || !WATCHING.load(Ordering::Acquire) { + return Opened(Vec::new()); + } + with(|s| { + let mut opened = Vec::new(); + if s.at.is_empty() { + return Opened(opened); + } + let mut view = p & !(PAGE - 1); + while view < p.saturating_add(len) { + if let Some(&page) = s.at.get(&view) { + s.dirty.insert(page); + unsafe { protect(view, PAGE_READWRITE) }; + *s.pinned.entry(view).or_default() += 1; + opened.push(view); + } + view += PAGE; + } + Opened(opened) + }) +} + +/// An overlapped read (`ov`) writes into the views `opened` holds after its call returned: they +/// stay open until it is done (`take_dirty` looks). +pub fn open_until_done(opened: Opened, ov: usize) { + if !opened.0.is_empty() { + with(|s| s.pending.push((ov, opened))); + } +} + +/// Whether the overlapped I/O at `ov` is still going on (its `Internal` is STATUS_PENDING). The +/// title may have freed the OVERLAPPED once it is done, so it is read without faulting. +fn still_pending(ov: usize) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const STATUS_PENDING: usize = 0x103; + let mut internal = 0usize; + let mut n = 0usize; + // SAFETY: ReadProcessMemory on our own process fails instead of faulting on an unreadable address. + let ok = unsafe { ReadProcessMemory(GetCurrentProcess(), ov as *const c_void, &mut internal as *mut usize as *mut c_void, std::mem::size_of::(), &mut n) } != 0; + ok && n == std::mem::size_of::() && internal == STATUS_PENDING +} + +/// The pages written since the last call, as the `step`-sized pages (4 KiB for the write watch) +/// of every view of each, appended to `out`; those views are guarded again. +pub(super) fn take_dirty(out: &mut Vec, step: usize) { + collect_dirty(out, step, &mut Vec::new()); +} + +/// Also mark the canonical storage used for copies to GPU-view tiles. +pub(crate) fn take_uploads(out: &mut Vec, step: usize) { + let mut pages = Vec::new(); + collect_dirty(out, step, &mut pages); + for page in pages { + if let Some((at, true)) = super::alias::backing(page) { + out.extend((at..at + PAGE).step_by(step)); + } + } +} + +fn collect_dirty(out: &mut Vec, step: usize, pages: &mut Vec) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + // overlapped reads that are done let their views go (dropped outside the lock: it takes it) + let done: Vec<(usize, Opened)> = with(|s| { + let (done, pending) = std::mem::take(&mut s.pending).into_iter().partition(|&(ov, _)| !still_pending(ov)); + s.pending = pending; + done + }); + drop(done); + with(|s| { + for page in std::mem::take(&mut s.dirty) { + pages.push(page); + for &view in s.views.get(&page).map(Vec::as_slice).unwrap_or_default() { + // guarded before its bytes are read for the upload: a write from here on is + // caught again, one before this is in what the upload reads. A view opened for a + // write still going on stays open (`Opened` counts its page as written at the end) + if !s.pinned.contains_key(&view) { + unsafe { protect(view, PAGE_READONLY) }; + } + out.extend((view..view + PAGE).step_by(step)); + } + } + }); +} + +#[cfg(test)] +pub(super) mod tests { + use super::super::sections::{commit, reserve, unmap, Section}; + use super::*; + use std::sync::Mutex as TestLock; + + /// the guard state is one per process: tests that use it (here and in `alias`) run one at a time + pub(in crate::hle::kernelx) static SERIAL: TestLock<()> = TestLock::new(()); + + /// A section of `pages` pages and placeholder space for `views` views; page `i` of the + /// section at view slot `j` is `space + j * PAGE`. + struct Fixture { + section: Section, + space: usize, + mapped: Vec, + } + impl Fixture { + fn new(pages: usize, views: usize) -> Fixture { + Fixture { section: Section::new(pages).unwrap(), space: unsafe { reserve(None, views * PAGE) }.unwrap(), mapped: Vec::new() } + } + /// Section page `page` at view slot `slot`, committed and guarded; its physical page id is `page`. + fn show(&mut self, page: usize, slot: usize) -> usize { + let at = self.space + slot * PAGE; + unsafe { + assert!(self.section.map(page, 1, at)); + assert!(commit(at, PAGE)); + } + watch(page, at); + self.mapped.push(at); + at + } + } + impl Drop for Fixture { + fn drop(&mut self) { + for &at in &self.mapped { + forget(at); + unsafe { unmap(at) }; + } + } + } + + fn dirty() -> Vec { + let mut out = Vec::new(); + take_dirty(&mut out, PAGE); + out.sort_unstable(); + out + } + + unsafe fn write(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + #[test] + fn a_write_through_one_view_reports_every_view_of_the_page() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(4, 8); + let a = f.show(2, 1); + let b = f.show(2, 5); + let c = f.show(3, 6); + dirty(); + unsafe { write(b + 16, 9) }; + assert_eq!(unsafe { std::ptr::read_volatile((a + 16) as *const u64) }, 9); + assert_eq!(dirty(), vec![a, b], "both views of the written page, not the other page's"); + assert_eq!(dirty(), Vec::::new(), "nothing written since"); + unsafe { write(a, 1) }; + unsafe { write(c, 1) }; + assert_eq!(dirty(), vec![a, b, c], "the views are guarded again after a take"); + } + + #[test] + fn steps_of_4_kib_cover_the_view() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 1); + let a = f.show(0, 0); + dirty(); + unsafe { write(a + 0x8000, 1) }; + let mut out = Vec::new(); + take_dirty(&mut out, 0x1000); + assert_eq!(out, (a..a + PAGE).step_by(0x1000).collect::>()); + } + + #[test] + fn open_makes_views_writable_for_a_kernel_call_and_counts_the_write() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(2, 4); + let a = f.show(0, 0); + let b = f.show(1, 1); + dirty(); + let opened = open(a + PAGE - 8, 16); // straddles both views + assert!(writable(a) && writable(b)); + assert_eq!(dirty(), vec![a, b]); + assert!(writable(a) && writable(b), "a take leaves views open while their write goes on"); + drop(opened); + assert_eq!(dirty(), vec![a, b], "the end of the write counts as a write"); + assert!(!writable(a), "guarded again after the take that follows"); + } + + #[test] + fn views_an_overlapped_read_writes_stay_open_until_it_is_done() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 1); + let a = f.show(0, 0); + dirty(); + // an OVERLAPPED whose Internal says pending, then done + let mut ov = [0x103usize, 0, 0, 0]; + open_until_done(open(a, 16), ov.as_mut_ptr() as usize); + assert_eq!(dirty(), vec![a]); + assert!(writable(a), "still open while the read is pending"); + ov[0] = 0; + assert_eq!(dirty(), vec![a], "the end of the read counts as a write"); + assert!(!writable(a), "guarded again once the read is done"); + } + + #[test] + fn a_forgotten_view_is_no_longer_reported() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 2); + let a = f.show(0, 0); + let b = f.show(0, 1); + dirty(); + forget(b); + unsafe { write(a, 3) }; + assert_eq!(dirty(), vec![a]); + } + + #[test] + fn writes_from_many_threads_are_all_caught_and_kept() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + const PAGES: usize = 64; + const THREADS: usize = 8; + let mut f = Fixture::new(PAGES, PAGES); + let views: Vec = (0..PAGES).map(|i| f.show(i, i)).collect(); + dirty(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS)); + let handles: Vec<_> = (0..THREADS) + .map(|t| { + let (views, barrier) = (views.clone(), barrier.clone()); + std::thread::spawn(move || { + barrier.wait(); + for (i, &v) in views.iter().enumerate() { + unsafe { write(v + t * 64, (i * THREADS + t) as u64) }; + } + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + for (i, &v) in views.iter().enumerate() { + for t in 0..THREADS { + assert_eq!(unsafe { std::ptr::read_volatile((v + t * 64) as *const u64) }, (i * THREADS + t) as u64); + } + } + assert_eq!(dirty(), views); + } + + /// A write to a guarded view that is not committed yet is not the guards' to handle (the + /// lazy handler commits it): claimed, it faulted again for ever whenever this handler ran + /// before the lazy one. + #[test] + fn a_write_to_a_view_not_committed_yet_is_left_to_the_next_handler() { + use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, EXCEPTION_RECORD}; + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(2, 2); + // page 0 mapped but never committed; page 1 committed and guarded + let fresh = f.space; + unsafe { assert!(f.section.map(0, 1, fresh)) }; + watch(0, fresh); + f.mapped.push(fresh); + let used = f.show(1, 1); + let fault = |at: usize| unsafe { + let mut rec: EXCEPTION_RECORD = std::mem::zeroed(); + rec.ExceptionCode = EXCEPTION_ACCESS_VIOLATION as NTSTATUS; + rec.NumberParameters = 2; + rec.ExceptionInformation[0] = 1; + rec.ExceptionInformation[1] = at + 8; + let mut ctx: CONTEXT = std::mem::zeroed(); + let mut ptrs = EXCEPTION_POINTERS { ExceptionRecord: &mut rec, ContextRecord: &mut ctx }; + handler(&mut ptrs) + }; + assert_eq!(fault(fresh), EXCEPTION_CONTINUE_SEARCH, "not committed: left to the lazy handler"); + assert_eq!(fault(used), EXCEPTION_CONTINUE_EXECUTION, "committed and guarded: opened here"); + } + + #[test] + fn a_view_committed_later_counts_as_written() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let f = Fixture::new(1, 1); + let at = f.space; + unsafe { assert!(f.section.map(0, 1, at)) }; + watch(0, at); // not committed: cannot be guarded yet + dirty(); + unsafe { assert!(commit(at, PAGE)) }; + committed(at); + assert_eq!(dirty(), vec![at]); + forget(at); + unsafe { unmap(at) }; + } +} diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index 2f858372e7..c30c3f7139 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -41,7 +41,15 @@ unsafe fn commit(page: usize) -> bool { if !g.remove(&page) { return false; } - !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() + if VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() { + g.insert(page); + return false; + } + drop(g); + // (a view of a physical page committed here is writable, not guarded: count it as written) + super::guards::committed(page); + super::alias::committed_at(page); + true } unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { @@ -89,20 +97,22 @@ pub(super) fn is_marked(page: usize) -> bool { } /// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. -pub fn ensure(p: usize, len: usize) { +pub fn ensure(p: usize, len: usize) -> super::guards::Opened { + let opened = super::guards::open(p, len); if len == 0 { - return; + return opened; } let pages: Vec = { let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); if g.is_empty() { - return; + return opened; } g.range(p & !(PAGE - 1)..p.saturating_add(len)).copied().collect() }; for page in pages { unsafe { commit(page) }; } + opened } #[cfg(test)] @@ -122,7 +132,7 @@ mod tests { std::ptr::write_volatile((r + 8) as *mut u32, 7); assert_eq!(std::ptr::read_volatile((r + 8) as *const u32), 7); assert!(!unmark(r), "used: no longer lazy"); - ensure(r + PAGE + 4, 4); + let _open = ensure(r + PAGE + 4, 4); assert!(!LAZY.read().unwrap().contains(&(r + PAGE))); assert!(crate::gpu::shader::readable(r + PAGE, 4)); VirtualFree(r as *mut c_void, 0, MEM_RELEASE); diff --git a/crates/xcl/src/hle/kernelx/sections.rs b/crates/xcl/src/hle/kernelx/sections.rs new file mode 100644 index 0000000000..7af7bc4a02 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/sections.rs @@ -0,0 +1,324 @@ +//! Physical pages that show at every address they are mapped at. +//! +//! On the console a physical page mapped at several addresses is one page: a write through one +//! address is read at all of them. A retail title maps its streamed pages into a pool, into the +//! CPU view of a 24 GB reservation and, through its queue, into that reservation's GPU view. +//! Here a block of physical pages is one pagefile-backed section, and mapping a page puts a view +//! of its 64 KiB slice into a placeholder at the address: every view of the slice is the same +//! memory, with no copy. The section is `SEC_RESERVE`, so a page takes commit only once it is +//! committed through one of its views, and then once for all of them. +//! +//! Address space that may hold such views is reserved as a placeholder (`reserve`). A view +//! replaces the placeholder at its address (`map`); unmapping it leaves a placeholder again +//! (`unmap`), ready for the next view. Ordinary memory can replace part of a placeholder too +//! (`replace_with_reservation`), write-watched if asked – but `GetWriteWatch` refuses a range +//! that holds a view, so the watch must ask about such reservations one by one. + +use std::ffi::c_void; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MapViewOfFile3, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQuery, MEMORY_BASIC_INFORMATION, + MEMORY_MAPPED_VIEW_ADDRESS, MEM_COMMIT, MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, + MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE, VIRTUAL_ALLOCATION_TYPE, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// One console physical page (64 KiB, the Windows allocation granularity too). +pub const PAGE: usize = 0x1_0000; + +const MEM_WRITE_WATCH: VIRTUAL_ALLOCATION_TYPE = 0x20_0000; + +/// A block of physical pages: one pagefile-backed section of `pages` 64 KiB pages. +pub struct Section { + handle: HANDLE, + pages: usize, +} + +// SAFETY: a section handle may be used from any thread; the section itself is kernel state. +unsafe impl Send for Section {} +unsafe impl Sync for Section {} + +impl Section { + /// A section of `pages` pages, none committed. None if Windows refuses it. + pub fn new(pages: usize) -> Option
{ + let bytes = pages.checked_mul(PAGE).filter(|&b| b > 0)?; + // SAFETY: a pagefile-backed mapping with no name and default security. + let handle = unsafe { CreateFileMappingW(INVALID_HANDLE_VALUE, std::ptr::null(), PAGE_READWRITE | SEC_RESERVE, (bytes >> 32) as u32, bytes as u32, std::ptr::null()) }; + (!handle.is_null()).then_some(Section { handle, pages }) + } + + pub fn pages(&self) -> usize { + self.pages + } + + /// Map pages `first..first + n` of the section at `at`, which must be a placeholder or lie in + /// one (`reserve`). The view is one Windows mapping: `unmap` takes all of it at once. + /// + /// # Safety + /// `[at, at + n * PAGE)` must be address space the caller owns as a placeholder. + pub unsafe fn map(&self, first: usize, n: usize, at: usize) -> bool { + if n == 0 || first.checked_add(n).is_none_or(|end| end > self.pages) || !at.is_multiple_of(PAGE) { + return false; + } + let len = n * PAGE; + if !split(at, len) { + return false; + } + let v = MapViewOfFile3(self.handle, GetCurrentProcess(), at as *const c_void, (first * PAGE) as u64, len, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, std::ptr::null_mut(), 0); + v.Value as usize == at + } +} + +impl Drop for Section { + fn drop(&mut self) { + // views still mapped keep the section alive until they are unmapped + // SAFETY: the handle is ours and closed once. + unsafe { CloseHandle(self.handle) }; + } +} + +/// Reserve `len` bytes of placeholder address space, at `at` if given. None if it is taken. +/// +/// # Safety +/// Only reserves address space; the caller releases it with `release`. +pub unsafe fn reserve(at: Option, len: usize) -> Option { + if len == 0 || !len.is_multiple_of(PAGE) { + return None; + } + let want = at.unwrap_or(0); + let p = VirtualAlloc2(GetCurrentProcess(), want as *const c_void, len, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, std::ptr::null_mut(), 0) as usize; + (p != 0 && (at.is_none() || p == want)).then_some(p) +} + +/// The allocation `p` lies in: (base, size, state, type), from one VirtualQuery. +fn allocation_at(p: usize) -> Option<(usize, usize, u32, u32)> { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + Some((m.AllocationBase as usize, m.RegionSize, m.State, m.Type)) +} + +/// Make `[at, at + len)` a placeholder of its own, splitting the placeholder it lies in. True if +/// it is one now (already exactly one, too). +/// +/// # Safety +/// `[at, at + len)` must lie in one placeholder the caller owns. +pub unsafe fn split(at: usize, len: usize) -> bool { + match allocation_at(at) { + // a placeholder is a reservation (MEM_RESERVE) with no protection; one that is already + // exactly this range cannot be split again – it is what was asked for + Some((base, size, MEM_RESERVE, _)) if base == at && size == len => true, + Some((_, _, MEM_RESERVE, _)) => VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0, + _ => false, + } +} + +/// Unmap the view at `at` (all of it) and leave a placeholder in its place. +/// +/// # Safety +/// `at` must be the start of a view made by `Section::map`. +pub unsafe fn unmap(at: usize) -> bool { + UnmapViewOfFile2(GetCurrentProcess(), MEMORY_MAPPED_VIEW_ADDRESS { Value: at as *mut c_void }, MEM_PRESERVE_PLACEHOLDER) != 0 +} + +/// Commit `[at, at + len)` of a view: the section's pages there are committed for every view of +/// them. True if they are committed now. +/// +/// # Safety +/// The range must lie in views made by `Section::map`. +pub unsafe fn commit(at: usize, len: usize) -> bool { + !VirtualAlloc(at as *const c_void, len, MEM_COMMIT, PAGE_READWRITE).is_null() +} + +/// Ordinary reserved memory in place of `[at, at + len)` of a placeholder, write-watched if +/// `write_watch` (commit it with `VirtualAlloc` as usual). +/// +/// # Safety +/// `[at, at + len)` must lie in one placeholder the caller owns. +pub unsafe fn replace_with_reservation(at: usize, len: usize, write_watch: bool) -> bool { + if !split(at, len) { + return false; + } + let t = MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | if write_watch { MEM_WRITE_WATCH } else { 0 }; + VirtualAlloc2(GetCurrentProcess(), at as *const c_void, len, t, PAGE_READWRITE, std::ptr::null_mut(), 0) as usize == at +} + +/// Turn the reservation `replace_with_reservation` made at `[at, at + len)` back into a +/// placeholder (what was committed there is gone). +/// +/// # Safety +/// `[at, at + len)` must be exactly such a reservation. +pub unsafe fn reservation_to_placeholder(at: usize, len: usize) -> bool { + VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0 +} + +/// Release every placeholder in `[at, at + len)`, which splitting may have cut into many (views +/// in it must be unmapped first). True if all of it went. +/// +/// # Safety +/// `[at, at + len)` must be placeholders the caller owns. +pub unsafe fn release_all(at: usize, len: usize) -> bool { + let mut p = at; + while p < at + len { + match allocation_at(p) { + Some((base, size, MEM_RESERVE, _)) if base == p && release(p) => p += size, + _ => return false, + } + } + true +} + +/// Release the placeholder at `at` (its whole extent; views in it must be unmapped first). +/// +/// # Safety +/// `at` must be the start of a placeholder the caller owns. +pub unsafe fn release(at: usize) -> bool { + VirtualFree(at as *mut c_void, 0, MEM_RELEASE) != 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{GetWriteWatch, MEM_MAPPED}; + + /// Placeholder address space for a test, released at the end (views unmapped first by the test). + struct Space(usize, usize); + impl Space { + fn new(pages: usize) -> Space { + let len = pages * PAGE; + Space(unsafe { reserve(None, len) }.expect("placeholder"), len) + } + fn at(&self, i: usize) -> usize { + self.0 + i * PAGE + } + } + impl Drop for Space { + fn drop(&mut self) { + // the test leaves placeholders behind; release each piece + let mut p = self.0; + while p < self.0 + self.1 { + let (base, size, _, _) = allocation_at(p).unwrap(); + assert_eq!(base, p); + unsafe { release(p) }; + p += size; + } + } + } + + unsafe fn read(at: usize) -> u64 { + std::ptr::read_volatile(at as *const u64) + } + + unsafe fn write(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + #[test] + fn a_page_mapped_at_two_addresses_is_one_page() { + let s = Section::new(8).unwrap(); + let space = Space::new(16); + unsafe { + assert!(s.map(5, 1, space.at(2))); + assert!(s.map(5, 1, space.at(11))); + assert!(commit(space.at(2), PAGE)); + write(space.at(2) + 0x40, 0xDEAD_BEEF); + assert_eq!(read(space.at(11) + 0x40), 0xDEAD_BEEF, "a write at one address is read at the other"); + write(space.at(11) + 0x40, 7); + assert_eq!(read(space.at(2) + 0x40), 7); + assert_eq!(allocation_at(space.at(11)).unwrap().3, MEM_MAPPED); + assert!(unmap(space.at(2)) && unmap(space.at(11))); + } + } + + #[test] + fn committing_through_one_view_commits_the_page_for_all() { + let s = Section::new(2).unwrap(); + let space = Space::new(4); + unsafe { + assert!(s.map(1, 1, space.at(0))); + assert!(s.map(1, 1, space.at(3))); + assert_eq!(allocation_at(space.at(3)).unwrap().2, MEM_RESERVE, "a page is not committed before it is used"); + assert!(commit(space.at(0), PAGE)); + assert_eq!(allocation_at(space.at(3)).unwrap().2, MEM_COMMIT); + assert_eq!(read(space.at(3)), 0, "a new page reads zeros"); + assert!(unmap(space.at(0)) && unmap(space.at(3))); + } + } + + #[test] + fn unmapping_leaves_a_placeholder_for_the_next_page() { + let s = Section::new(4).unwrap(); + let space = Space::new(2); + unsafe { + assert!(s.map(0, 1, space.at(1)) && commit(space.at(1), PAGE)); + write(space.at(1), 1); + assert!(unmap(space.at(1))); + let (base, size, state, _) = allocation_at(space.at(1)).unwrap(); + assert_eq!((base, size, state), (space.at(1), PAGE, MEM_RESERVE), "a placeholder of the page's size is left"); + assert!(s.map(3, 1, space.at(1)) && commit(space.at(1), PAGE)); + assert_eq!(read(space.at(1)), 0, "the other page is there now"); + // the first page kept its contents while it was mapped nowhere + assert!(s.map(0, 1, space.at(0))); + assert_eq!(read(space.at(0)), 1); + assert!(unmap(space.at(0)) && unmap(space.at(1))); + } + } + + #[test] + fn a_run_of_pages_is_one_view() { + let s = Section::new(8).unwrap(); + let space = Space::new(8); + unsafe { + assert!(s.map(2, 4, space.at(1))); + assert_eq!(allocation_at(space.at(1)).unwrap().0, space.at(1)); + assert_eq!(allocation_at(space.at(4)).unwrap().0, space.at(1), "one view covers the run"); + assert!(commit(space.at(1), 4 * PAGE)); + assert!(s.map(4, 1, space.at(7))); + write(space.at(3), 42); // page 4 of the section, third of the run + assert_eq!(read(space.at(7)), 42); + assert!(!s.map(6, 4, space.at(0)), "pages past the end of the section are refused"); + assert!(unmap(space.at(1)) && unmap(space.at(7))); + } + } + + #[test] + fn write_watched_memory_lives_beside_views_in_one_placeholder() { + let s = Section::new(1).unwrap(); + let space = Space::new(8); + unsafe { + assert!(replace_with_reservation(space.at(0), 4 * PAGE, true)); + assert!(!VirtualAlloc(space.at(0) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(s.map(0, 1, space.at(6)) && commit(space.at(6), PAGE)); + write(space.at(1), 1); + write(space.at(6), 2); + let mut out = [std::ptr::null_mut::(); 64]; + let (mut n, mut gran) = (out.len(), 0u32); + assert_eq!(GetWriteWatch(1, space.at(0) as *const c_void, 4 * PAGE, out.as_mut_ptr(), &mut n, &mut gran), 0); + assert_eq!((n, out[0] as usize), (1, space.at(1)), "the write-watched reservation reports its write"); + let mut n = out.len(); + assert_ne!(GetWriteWatch(0, space.at(0) as *const c_void, 8 * PAGE, out.as_mut_ptr(), &mut n, &mut gran), 0, "a range with a view in it is refused"); + assert!(reservation_to_placeholder(space.at(0), 4 * PAGE)); + assert_eq!(allocation_at(space.at(0)).unwrap().2, MEM_RESERVE); + assert!(unmap(space.at(6))); + } + } + + #[test] + fn splitting_a_range_that_is_already_a_placeholder_is_a_no_op() { + let space = Space::new(3); + unsafe { + assert!(split(space.at(1), PAGE)); + assert!(split(space.at(1), PAGE)); + assert_eq!(allocation_at(space.at(1)).unwrap().0, space.at(1)); + assert_eq!(allocation_at(space.at(2)).unwrap().0, space.at(2)); + } + } + + #[test] + fn a_section_of_no_pages_is_refused() { + assert!(Section::new(0).is_none()); + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index b355560e51..8e328c157d 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -80,6 +80,7 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + crate::ram_budget::start(); if let Err(e) = crate::hle::d3d12x::present::preparation::before_guest(&boot) { crate::xlog_error!("Shader preparation: {e}"); eprintln!("xcl: {e}"); @@ -104,6 +105,7 @@ pub fn host_main(boot_path: &Path) -> i32 { let mut own_cost = crate::hle::api_cost::submitter_totals(); let mut views = crate::hle::d3d12x::view_want::totals(); let mut tile_calls = crate::hle::d3d12x::sparse::tile_calls(); + let mut heap_tick = 0u32; loop { std::thread::sleep(std::time::Duration::from_secs(2)); let now = snap(); @@ -184,6 +186,17 @@ pub fn host_main(boot_path: &Path) -> i32 { if pages != 0 { crate::xlog_info!("{}", crate::hle::d3d12x::vram::page_owners()); } + // `XCL_HEAP_COUNT=1`: XCL's own part of that commit, every 20 s + heap_tick += 1; + if heap_tick % 10 == 0 { + crate::xlog_info!("{}", crate::hle::d3d12x::title_textures::upload_line()); + for l in crate::heap_count::lines(16).unwrap_or_default() { + crate::xlog_info!("{l}"); + } + for l in crate::mem_map::lines().unwrap_or_default() { + crate::xlog_info!("{l}"); + } + } // past the budget Windows moves the process's video memory off the card and // every frame pays for bringing it back; a run at the card's limit is also // where the driver gave up (the guard script ends a run that stays there) diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index b6bc0d2ec8..308a63686a 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -13,6 +13,9 @@ pub mod config; pub mod disasm; pub mod eh; pub mod gpu; +pub mod heap_count; +pub mod mem_map; +pub mod ram_budget; pub mod hle; pub mod hooks; pub mod host; @@ -36,3 +39,7 @@ pub mod tls; pub mod util; pub mod vfs; pub mod vfs_hooks; + +/// XCL's own allocations go through the counters of `heap_count` (`XCL_HEAP_COUNT=1`). +#[global_allocator] +static HEAP: heap_count::Counting = heap_count::Counting; diff --git a/crates/xcl/src/mem_map.rs b/crates/xcl/src/mem_map.rs new file mode 100644 index 0000000000..1a72abc0d6 --- /dev/null +++ b/crates/xcl/src/mem_map.rs @@ -0,0 +1,401 @@ +//! Where the process's memory is (`XCL_MEM_MAP=1`): every 20 s, with the memory lines of the +//! activity log, a walk of the process's own address space adds up the committed and the resident +//! (working-set) bytes by whose they are: the title's in the UMA windows, the physical pages of +//! `XCL_PAGE_ALIAS`, the images, and the rest by the size of its regions, with the largest +//! allocations of the rest by address. +//! +//! The process's counters (`memory: N MB committed by the process`) hold the title's memory, the +//! driver's, Direct3D's and XCL's own in one number. The walk tells them apart by address and by +//! the type of each region (`VirtualQuery`), and finds the pages that are resident with +//! `K32QueryWorkingSetEx`, `CHUNK` pages a call. It only asks Windows: no page is touched. + +use std::ffi::c_void; +use std::sync::OnceLock; + +use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED}; +use windows_sys::Win32::System::ProcessStatus::{K32GetMappedFileNameW, K32GetProcessMemoryInfo, K32QueryWorkingSetEx, PROCESS_MEMORY_COUNTERS_EX, PSAPI_WORKING_SET_EX_INFORMATION}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// `XCL_MEM_MAP=1` turns the report on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_MEM_MAP").is_ok_and(|v| v.trim() == "1")) +} + +/// the pages the working set is asked about +const PAGE: usize = 4 << 10; +/// pages one `K32QueryWorkingSetEx` call asks about +const CHUNK: usize = 4096; + +// Whose committed memory is, the first that fits: by its address (the UMA windows, the physical +// pages' spaces and homes), then by the type of its region, the private rest by the region's size. +const SPARSE: usize = 0; +const COHERENT: usize = 1; +const VIEW: usize = 2; +const SPACES: usize = 3; +const HOMES: usize = 4; +const IMAGE: usize = 5; +const MAPPED: usize = 6; +const PRIVATE_LARGE: usize = 7; +const PRIVATE_MID: usize = 8; +const PRIVATE_SMALL: usize = 9; +const CLASSES: usize = 10; +const NAMES: [&str; CLASSES] = [ + "title memory in sparse windows", + "title memory in the coherent window", + "GPU-view windows", + "physical pages: views in the title's spaces (views of the same pages as the homes)", + "physical pages: XCL's home views", + "images (exe and DLLs)", + "other mapped (sections, files)", + "other private, regions >= 64 MiB", + "other private, regions 1-64 MiB", + "other private, regions < 1 MiB", +]; + +/// the largest images listed +const TOP_IMAGES: usize = 3; +/// the largest other private allocations listed +const TOP_ALLOCS: usize = 12; + +#[derive(Clone, Copy, Default)] +struct Bytes { + committed: usize, + resident: usize, + /// of `resident`, pages mapped more than once (`ShareCount` > 1) + shared: usize, + /// committed regions + regions: usize, +} + +impl Bytes { + fn resident_page(&mut self, shared: bool) { + self.resident += PAGE; + if shared { + self.shared += PAGE; + } + } +} + +/// One allocation of the walk (its regions' `AllocationBase`): an image, or other private memory. +struct Item { + base: usize, + /// the end of its last region seen, committed or reserved + end: usize, + bytes: Bytes, + /// `Protect` of its first committed region; `mixed`: another one has another + protect: u32, + mixed: bool, + alloc_protect: u32, +} + +/// Whose a page of the walk is: a class, and an item of the class (`NO_ITEM`: none). +#[derive(Clone, Copy)] +struct Tag { + class: usize, + item: usize, +} + +const NO_ITEM: usize = usize::MAX; + +/// What a walk adds up: whose each committed region is, and its pages found resident. +trait Sink { + /// The committed part `[at, at + len)` of the region `m`: whose it is. + fn committed(&mut self, m: &MEMORY_BASIC_INFORMATION, at: usize, len: usize) -> Tag; + /// A page of `tag`'s is in the working set (`shared`: mapped more than once). + fn resident(&mut self, tag: Tag, shared: bool); + /// A region reserved but not committed. + fn reserved(&mut self, _m: &MEMORY_BASIC_INFORMATION) {} +} + +/// The pages of committed regions waiting for one `K32QueryWorkingSetEx` call (one buffer for the +/// whole walk), with whose each one is. +struct Pages { + info: Vec, + tags: Vec, + /// calls Windows refused (their pages are not counted resident) + failed: usize, +} + +impl Pages { + fn new() -> Pages { + Pages { info: Vec::with_capacity(CHUNK), tags: Vec::with_capacity(CHUNK), failed: 0 } + } + + /// The pages of `[at, at + len)`, committed and `tag`'s, asked about `CHUNK` at a time. + fn add(&mut self, at: usize, len: usize, tag: Tag, sink: &mut impl Sink) { + for p in (at..at + len).step_by(PAGE) { + if self.info.len() == CHUNK { + self.flush(sink); + } + self.info.push(PSAPI_WORKING_SET_EX_INFORMATION { VirtualAddress: p as *mut c_void, VirtualAttributes: Default::default() }); + self.tags.push(tag); + } + } + + /// One `K32QueryWorkingSetEx` call for the pages waiting: each resident one goes to `sink`. + fn flush(&mut self, sink: &mut impl Sink) { + if self.info.is_empty() { + return; + } + let bytes = (self.info.len() * std::mem::size_of::()) as u32; + if unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), self.info.as_mut_ptr() as *mut c_void, bytes) } != 0 { + for (i, &tag) in self.info.iter().zip(&self.tags) { + // bit 0: Valid (in the working set), bits 1..=3: ShareCount + let flags = unsafe { i.VirtualAttributes.Flags }; + if flags & 1 != 0 { + sink.resident(tag, (flags >> 1) & 7 > 1); + } + } + } else { + self.failed += 1; + } + self.info.clear(); + self.tags.clear(); + } +} + +/// Walk `[lo, hi)` region by region (`VirtualQuery`): the committed part of each goes to `sink`, +/// and its pages to the working-set queries of `pages`; a region not committed costs its query +/// only. The regions walked. +fn walk(lo: usize, hi: usize, pages: &mut Pages, sink: &mut impl Sink) -> usize { + let mut walked = 0; + let mut p = lo; + while p < hi { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(p as *const c_void, &mut m, std::mem::size_of::()) } == 0 { + // past the user address space + break; + } + walked += 1; + let base = m.BaseAddress as usize; + let end = base.saturating_add(m.RegionSize); + if m.State == MEM_COMMIT { + let (from, to) = (base.max(lo), end.min(hi)); + if to > from { + let tag = sink.committed(&m, from, to - from); + pages.add(from, to - from, tag, sink); + } + } else if m.State != MEM_FREE { + sink.reserved(&m); + } + if end <= p { + break; + } + p = end; + } + pages.flush(sink); + walked +} + +/// Whether `p` lies in one of `ranges` ((base, bytes), by address, not overlapping). +fn within(ranges: &[(usize, usize)], p: usize) -> bool { + let i = ranges.partition_point(|r| r.0 <= p); + i > 0 && p - ranges[i - 1].0 < ranges[i - 1].1 +} + +/// The item of `m`'s allocation in `items` with `len` committed bytes more: the last one, or a new +/// one (the walk goes by address, and the regions of an allocation are side by side). +fn item_of(items: &mut Vec, m: &MEMORY_BASIC_INFORMATION, len: usize) -> usize { + let base = m.AllocationBase as usize; + if items.last().is_none_or(|i| i.base != base) { + items.push(Item { base, end: base, bytes: Bytes::default(), protect: m.Protect, mixed: false, alloc_protect: m.AllocationProtect }); + } + let n = items.len() - 1; + let i = &mut items[n]; + i.bytes.committed += len; + i.bytes.regions += 1; + i.mixed |= i.protect != m.Protect; + i.end = (m.BaseAddress as usize).saturating_add(m.RegionSize); + n +} + +/// The report's sink: the classes, and the images and other private allocations one by one. +#[derive(Default)] +struct Map { + uma: Option<&'static crate::gpu::uma::Uma>, + /// the physical pages' spaces and homes (`alias::ranges`), by address + spaces: Vec<(usize, usize)>, + homes: Vec<(usize, usize)>, + classes: [Bytes; CLASSES], + /// committed bytes by the type of their region: private, mapped, image + by_type: [usize; 3], + /// the images and the other private allocations, by address + images: Vec, + allocs: Vec, +} + +impl Map { + fn class_of(&self, m: &MEMORY_BASIC_INFORMATION, at: usize, len: usize) -> usize { + if let Some(u) = self.uma { + if u.is_sparse(at) { + return SPARSE; + } + if u.is_committed(at) { + return COHERENT; + } + if u.is_view(at) { + return VIEW; + } + } + if within(&self.spaces, at) { + SPACES + } else if within(&self.homes, at) { + HOMES + } else if m.Type == MEM_IMAGE { + IMAGE + } else if m.Type == MEM_MAPPED { + MAPPED + } else if len >= 64 << 20 { + PRIVATE_LARGE + } else if len >= 1 << 20 { + PRIVATE_MID + } else { + PRIVATE_SMALL + } + } + + /// The items kept one by one of `class` (None: the class is only added up). + fn items(&mut self, class: usize) -> Option<&mut Vec> { + match class { + IMAGE => Some(&mut self.images), + PRIVATE_LARGE | PRIVATE_MID | PRIVATE_SMALL => Some(&mut self.allocs), + _ => None, + } + } +} + +impl Sink for Map { + fn committed(&mut self, m: &MEMORY_BASIC_INFORMATION, at: usize, len: usize) -> Tag { + self.by_type[match m.Type { + MEM_MAPPED => 1, + MEM_IMAGE => 2, + _ => 0, + }] += len; + let class = self.class_of(m, at, len); + self.classes[class].committed += len; + self.classes[class].regions += 1; + let item = self.items(class).map_or(NO_ITEM, |items| item_of(items, m, len)); + Tag { class, item } + } + + fn resident(&mut self, tag: Tag, shared: bool) { + self.classes[tag.class].resident_page(shared); + if tag.item != NO_ITEM { + if let Some(items) = self.items(tag.class) { + items[tag.item].bytes.resident_page(shared); + } + } + } + + fn reserved(&mut self, m: &MEMORY_BASIC_INFORMATION) { + // (the reserved rest of an allocation listed: a thread stack, a heap's segment) + if let Some(i) = self.allocs.last_mut().filter(|i| i.base == m.AllocationBase as usize) { + i.end = (m.BaseAddress as usize).saturating_add(m.RegionSize); + } + } +} + +/// The file name of the image at `base` (its mapped file's, without the path). +fn image_name(base: usize) -> String { + let mut buf = [0u16; 512]; + let n = unsafe { K32GetMappedFileNameW(GetCurrentProcess(), base as *const c_void, buf.as_mut_ptr(), buf.len() as u32) } as usize; + let path = String::from_utf16_lossy(&buf[..n.min(buf.len())]); + path.rsplit('\\').next().filter(|s| !s.is_empty()).unwrap_or("?").to_string() +} + +/// The lines of the activity log, each starting `mem map:`: the totals and how long the walk +/// took, each class, the largest images, the largest other private allocations. None: off. +pub fn lines() -> Option> { + if !enabled() { + return None; + } + let t = std::time::Instant::now(); + let (spaces, homes) = crate::hle::kernelx::alias::ranges(); + let mut map = Map { uma: crate::gpu::uma::get(), spaces, homes, ..Map::default() }; + let mut pages = Pages::new(); + let walked = walk(0, usize::MAX, &mut pages, &mut map); + let ms = t.elapsed().as_millis(); + let (private_usage, working_set) = unsafe { + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); + (c.PrivateUsage, c.WorkingSetSize) + }; + let mb = |b: usize| b >> 20; + let [private, mapped, image] = map.by_type; + let resident: usize = map.classes.iter().map(|c| c.resident).sum(); + let failed = if pages.failed != 0 { format!("; {} working-set queries failed (their pages are not counted resident)", pages.failed) } else { String::new() }; + let mut out = vec![format!( + "mem map: walked {walked} regions in {ms} ms: committed {} MB private, {} MB mapped, {} MB image ({} MB in all); {} MB resident; the process's counters: {} MB private commit, {} MB working set{failed}", + mb(private), + mb(mapped), + mb(image), + mb(private + mapped + image), + mb(resident), + mb(private_usage), + mb(working_set) + )]; + for (name, b) in NAMES.iter().zip(&map.classes) { + out.push(format!("mem map: {name}: {} MB committed, {} MB resident, {} regions, {} MB of the resident shared", mb(b.committed), mb(b.resident), b.regions, mb(b.shared))); + } + map.images.sort_by_key(|i| std::cmp::Reverse(i.bytes.committed)); + for i in map.images.iter().take(TOP_IMAGES) { + out.push(format!("mem map: image {} at {:#x}: {} MB committed, {} MB resident", image_name(i.base), i.base, mb(i.bytes.committed), mb(i.bytes.resident))); + } + map.allocs.sort_by_key(|i| std::cmp::Reverse(i.bytes.committed)); + for (k, i) in map.allocs.iter().take(TOP_ALLOCS).enumerate() { + out.push(format!( + "mem map: other private allocation {} at {:#x}: {} MB committed, {} MB resident, {} regions, {} MB reserved, protect {:#x}{} (allocation protect {:#x})", + k + 1, + i.base, + mb(i.bytes.committed), + mb(i.bytes.resident), + i.bytes.regions, + mb(i.end - i.base), + i.protect, + if i.mixed { " and others" } else { "" }, + i.alloc_protect + )); + } + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + /// A private allocation of which the first half is committed, and every other page of that + /// touched: the walk over it counts the committed half in one region of one allocation, the + /// touched pages resident and not the others. + #[test] + fn a_walk_counts_the_committed_bytes_and_the_touched_pages_resident() { + // (more pages than one working-set query asks about) + const SIZE: usize = 20 << 20; + let p = unsafe { VirtualAlloc(std::ptr::null(), 2 * SIZE, MEM_RESERVE, PAGE_READWRITE) } as usize; + assert_ne!(p, 0); + assert_eq!(unsafe { VirtualAlloc(p as *const c_void, SIZE, MEM_COMMIT, PAGE_READWRITE) } as usize, p); + for k in (0..SIZE / PAGE).step_by(2) { + unsafe { std::ptr::write_volatile((p + k * PAGE) as *mut u8, 1) }; + } + let mut map = Map::default(); + let walked = walk(p, p + 2 * SIZE, &mut Pages::new(), &mut map); + // the same memory as one of the physical pages' homes: by its address first + let mut home = Map { homes: vec![(p, 2 * SIZE)], ..Map::default() }; + walk(p, p + 2 * SIZE, &mut Pages::new(), &mut home); + unsafe { VirtualFree(p as *mut c_void, 0, MEM_RELEASE) }; + + assert_eq!(walked, 2, "the committed half and the reserved half"); + let b = map.classes[PRIVATE_MID]; + assert_eq!((b.committed, b.regions), (SIZE, 1)); + assert!(b.resident >= SIZE / 2 && b.resident < SIZE, "{} KiB resident of {} KiB committed, {} KiB touched", b.resident >> 10, SIZE >> 10, SIZE >> 11); + assert_eq!(map.by_type, [SIZE, 0, 0]); + assert_eq!(map.classes.iter().map(|c| c.committed).sum::(), SIZE, "in no other class"); + assert_eq!(map.allocs.len(), 1); + let a = &map.allocs[0]; + assert_eq!((a.base, a.end, a.bytes.committed, a.bytes.resident), (p, p + 2 * SIZE, SIZE, b.resident), "one allocation, with its reserved half"); + assert_eq!(home.classes[HOMES].committed, SIZE); + assert!(home.allocs.is_empty() && home.classes[PRIVATE_MID].committed == 0); + } +} diff --git a/crates/xcl/src/ram_budget.rs b/crates/xcl/src/ram_budget.rs new file mode 100644 index 0000000000..7d6b4f38c0 --- /dev/null +++ b/crates/xcl/src/ram_budget.rs @@ -0,0 +1,174 @@ +//! A budget for the RAM the process holds (`XCL_RAM_MB`). +//! +//! A console title's GPU memory is its only copy of what is in it. Here the title's pages are +//! RAM, and what the GPU reads of them is copied to video memory: a retail title's world held +//! 5 GB of RAM in pages whose copy was on the card (3.1 GB of streamed physical pages, 1.6 GB +//! of GPU heaps, the coherent window), of 13.8 GB in all, and most of those pages are not +//! touched again once they are uploaded. Windows only takes such pages out of a process when +//! RAM is short for the whole system – on a 32 GB PC with 15 GB in use by other programs that +//! was at under 4 GB free, where a guard had ended the run. +//! +//! With a budget the process's working set has a hard maximum: Windows takes the pages used +//! least out of it as it grows past that. They stay in RAM (the standby and modified lists) while +//! nothing else needs it, and a page touched again comes back with a soft fault; what the +//! system then needs is written to the page file. The process's commit is as before. +//! +//! `XCL_RAM_MB=`: that maximum. `XCL_RAM_MB=auto`: the maximum follows the RAM the system +//! has available, a second at a time, so that `XCL_RAM_FREE_MB` (6144 unless given) stay +//! available. Unset: no budget. + +use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; +use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; +use windows_sys::Win32::System::Memory::SetProcessWorkingSetSizeEx; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +const QUOTA_LIMITS_HARDWS_MIN_DISABLE: u32 = 0x2; +const QUOTA_LIMITS_HARDWS_MAX_ENABLE: u32 = 0x4; +const QUOTA_LIMITS_HARDWS_MAX_DISABLE: u32 = 0x8; + +const MB: u64 = 1 << 20; +/// no budget under this: the title's own threads' pages alone are more +const LEAST: u64 = 4096 * MB; +/// the most an automatic budget moves in one step (a second): pages taken out are available +/// only once they are written to the page file, and the next step would take them out again +const STEP: u64 = 512 * MB; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Setting { + Fixed(u64), + /// keep this many bytes available + Auto(u64), +} + +fn setting_of(ram: Option<&str>, free: Option<&str>) -> Option { + let ram = ram?.trim(); + if ram.eq_ignore_ascii_case("auto") { + let free = free.and_then(|v| v.trim().parse::().ok()).unwrap_or(6144); + return Some(Setting::Auto(free * MB)); + } + ram.parse::().ok().filter(|&mb| mb > 0).map(|mb| Setting::Fixed((mb * MB).max(LEAST))) +} + +/// The next maximum of an automatic budget: the working set `ws` may grow by what is available +/// beyond `keep`, and has to shrink by what is missing; `before` (None: no maximum yet) moves +/// by `STEP` at most. None: no maximum is needed (more than `STEP` to spare). +fn next_max(before: Option, ws: u64, available: u64, keep: u64) -> Option { + let want = (ws + available).saturating_sub(keep).max(LEAST); + match before { + None if available > keep + STEP => None, + None => Some(want.max(ws.saturating_sub(STEP))), + Some(b) => Some(want.clamp(b.saturating_sub(STEP), b + STEP).max(LEAST)), + } +} + +fn working_set() -> u64 { + unsafe { + let mut c: PROCESS_MEMORY_COUNTERS = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb); + c.WorkingSetSize as u64 + } +} + +fn available() -> u64 { + unsafe { + let mut m: MEMORYSTATUSEX = std::mem::zeroed(); + m.dwLength = std::mem::size_of_val(&m) as u32; + GlobalMemoryStatusEx(&mut m); + m.ullAvailPhys + } +} + +/// The hard maximum of the working set is `max` (None: none). False if Windows refuses. +fn set_max(max: Option) -> bool { + let (bytes, flags) = match max { + Some(m) => (m as usize, QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_ENABLE), + None => (usize::MAX >> 1, QUOTA_LIMITS_HARDWS_MIN_DISABLE | QUOTA_LIMITS_HARDWS_MAX_DISABLE), + }; + // (the minimum is not a hard one: a number below the maximum) + unsafe { SetProcessWorkingSetSizeEx(GetCurrentProcess(), 64 << 20, bytes.max(128 << 20), flags) != 0 } +} + +/// Start the budget `XCL_RAM_MB` asks for (nothing without it). +pub fn start() { + let Some(setting) = setting_of(std::env::var("XCL_RAM_MB").ok().as_deref(), std::env::var("XCL_RAM_FREE_MB").ok().as_deref()) else { return }; + match setting { + Setting::Fixed(max) => { + let ok = set_max(Some(max)); + crate::xlog_info!("RAM budget: XCL_RAM_MB – the process's working set is kept under {} MB{}", max / MB, if ok { "" } else { " (Windows refused)" }); + } + Setting::Auto(keep) => { + crate::xlog_info!("RAM budget: XCL_RAM_MB=auto – the process's working set is kept so that {} MB of RAM stay available", keep / MB); + let _ = std::thread::Builder::new().name("xcl-ram-budget".into()).spawn(move || { + let mut max: Option = None; + let mut ticks = 0u32; + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + let (ws, avail) = (working_set(), available()); + let next = next_max(max, ws, avail, keep); + if next != max { + if !set_max(next) { + crate::xlog_warn!("RAM budget: Windows refused a working set maximum of {:?} MB", next.map(|m| m / MB)); + return; + } + if max.is_none() || next.is_none() { + crate::xlog_info!( + "RAM budget: {} MB of RAM available with a working set of {} MB: {}", + avail / MB, + ws / MB, + next.map_or("no maximum".to_string(), |m| format!("a maximum of {} MB from here on", m / MB)) + ); + } + max = next; + } + ticks += 1; + if ticks % 20 == 0 { + if let Some(m) = max { + crate::xlog_info!("RAM budget: working set {} MB under a maximum of {} MB, {} MB of RAM available", ws / MB, m / MB, avail / MB); + } + } + } + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_setting_is_a_number_of_megabytes_or_auto() { + assert_eq!(setting_of(None, None), None); + assert_eq!(setting_of(Some("0"), None), None); + assert_eq!(setting_of(Some("lots"), None), None); + assert_eq!(setting_of(Some(" 10000 "), None), Some(Setting::Fixed(10000 * MB))); + assert_eq!(setting_of(Some("100"), None), Some(Setting::Fixed(LEAST)), "not under the least"); + assert_eq!(setting_of(Some("auto"), None), Some(Setting::Auto(6144 * MB))); + assert_eq!(setting_of(Some("AUTO"), Some("8000")), Some(Setting::Auto(8000 * MB))); + } + + #[test] + fn an_automatic_maximum_follows_the_ram_available() { + let keep = 6144 * MB; + // plenty available: no maximum + assert_eq!(next_max(None, 5000 * MB, 12000 * MB, keep), None); + // what is available comes near what is kept: the working set may grow by the difference + assert_eq!(next_max(None, 9000 * MB, 6500 * MB, keep), Some(9356 * MB)); + // less available than kept: the working set has to shrink by what is missing, a step at most + assert_eq!(next_max(Some(12000 * MB), 12000 * MB, 5944 * MB, keep), Some(11800 * MB)); + assert_eq!(next_max(Some(12000 * MB), 12000 * MB, 4000 * MB, keep), Some(12000 * MB - STEP)); + assert_eq!(next_max(None, 12000 * MB, 4000 * MB, keep), Some(12000 * MB - STEP)); + // RAM comes back: the maximum goes up again, a step at a time + assert_eq!(next_max(Some(10000 * MB), 10000 * MB, 9000 * MB, keep), Some(10000 * MB + STEP)); + // never under the least + assert_eq!(next_max(Some(LEAST), 4096 * MB, 1000 * MB, keep), Some(LEAST)); + } + + /// Windows takes a hard maximum for this process's working set, and lifts it again. + #[test] + fn windows_takes_a_working_set_maximum_and_lifts_it() { + assert!(set_max(Some(working_set() + 4096 * MB))); + assert!(set_max(None)); + } +} diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 437951d401..c6a87a9101 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -532,11 +532,12 @@ unsafe extern "system" fn hk_remove_dir_w(n: *const u16) -> i32 { unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, read: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_READ_FILE as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); - } + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); let r = orig(h, buf, n, read, ov); let error = windows_sys::Win32::Foundation::GetLastError(); + if !ov.is_null() && r == 0 && error == windows_sys::Win32::Foundation::ERROR_IO_PENDING { + if let Some(opened) = opened { crate::hle::kernelx::guards::open_until_done(opened, ov as usize); } + } crate::hle::d3d12x::file_reads::returned(r != 0, error, buf, n, read, ov); SetLastError(error); r From f9fd4bfbc7a30fd5a18ef13ff7dabb4d72368f09 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:04:41 +0100 Subject: [PATCH 013/175] Recompiler: add BVH box-grow ULP, ray NaN/Inf inactivation, and triangle mode 0 --- crates/xcl/src/gpu/desc.rs | 7 +- crates/xcl/src/gpu/dxil/lower_image.rs | 146 +++++++++++++++----- crates/xcl/src/gpu/recomp/emit.rs | 45 +++++-- crates/xcl/src/gpu/recomp/tests.rs | 176 ++++++++++++++++++++++++- 4 files changed, 324 insertions(+), 50 deletions(-) diff --git a/crates/xcl/src/gpu/desc.rs b/crates/xcl/src/gpu/desc.rs index 0097c70e9b..3eecc10c99 100644 --- a/crates/xcl/src/gpu/desc.rs +++ b/crates/xcl/src/gpu/desc.rs @@ -703,8 +703,9 @@ pub fn buffer_words(address: u64, stride: u32, num_records: u32, format: u32) -> /// An RDNA2 BVH resource descriptor (SRSRC, 4 dwords) for `image_bvh(64)_intersect_ray`: /// word 0 = base address bits 39:8 (256-byte units), word 1 = bits 47:40 | box_sort << 31, -/// word 2 = size / max bounds, word 3 = 0 (type bits 31:28 < 8 so descriptor copies leave it -/// verbatim instead of treating it as a T# image). +/// word 2 = size / max bounds, word 3 = 1 << 24 (triangle return mode 1 = barycentrics; +/// type bits 31:28 remain 0 < 8 so descriptor copies leave it verbatim instead of treating it +/// as a T# image). pub fn bvh_words(address: u64, box_sort: bool) -> [u32; 4] { - [(address >> 8) as u32, ((address >> 40) as u32 & 0xFF) | (u32::from(box_sort) << 31), u32::MAX, 0] + [(address >> 8) as u32, ((address >> 40) as u32 & 0xFF) | (u32::from(box_sort) << 31), u32::MAX, 1 << 24] } diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index 12d3a4bb36..fbdb618c7b 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -78,15 +78,82 @@ impl Lw { self.s.op(55, "dot3", Some(f32), f32, &[a[0], a[1], a[2], b[0], b[1], b[2]], super::module::FnAttrs::ReadNone) } + /// Move a finite float32 upward toward +inf by `g` ULPs (leaving NaN/Inf/g=0 unchanged). + fn bvh_grow_hi(&mut self, x: Value, g: Value) -> Value { + let u = self.bits(x); + let mag = self.andc(u, 0x7FFF_FFFF); + let g_nz = self.nz(g); + let finite = self.cmpc(Pred::ULt, mag, 0x7F80_0000); + let active = self.land(g_nz, finite); + let sign = self.andc(u, 0x8000_0000); + let is_neg_sign = self.nz(sign); + let mag_nz = self.nz(mag); + let neg = self.land(is_neg_sign, mag_nz); + let pos_sum = self.add(mag, g); + let pinf_u = self.c(0x7F80_0000); + let pos_clamped = self.umin(pos_sum, pinf_u); + let gt = self.cmp(Pred::UGt, mag, g); + let m_sub_g = self.sub(mag, g); + let neg_stay = self.orc(m_sub_g, 0x8000_0000); + let g_sub_m = self.sub(g, mag); + let neg_res = self.sel(gt, neg_stay, g_sub_m); + let grown = self.sel(neg, neg_res, pos_clamped); + let res = self.sel(active, grown, u); + self.f(res) + } + + /// Move a finite float32 downward toward -inf by `g` ULPs (leaving NaN/Inf/g=0 unchanged). + fn bvh_grow_lo(&mut self, x: Value, g: Value) -> Value { + let u = self.bits(x); + let sign_bit = self.c(0x8000_0000); + let neg_u = self.xor(u, sign_bit); + let neg_x = self.f(neg_u); + let grown = self.bvh_grow_hi(neg_x, g); + let grown_u = self.bits(grown); + let back_u = self.xor(grown_u, sign_bit); + let g_nz = self.nz(g); + let res = self.sel(g_nz, back_u, u); + self.f(res) + } + /// `bvh_intersect`: one BVH node → 4 result dwords (written to temporaries). #[allow(clippy::too_many_arguments)] - fn bvh_intersect(&mut self, ty: Value, at: Value, tmax: Value, o: [Value; 3], dir: [Value; 3], inv: [Value; 3], sort: Value, out: [u32; 4]) -> LResult<()> { + fn bvh_intersect( + &mut self, + ty: Value, + at: Value, + tmax: Value, + o: [Value; 3], + dir: [Value; 3], + inv: [Value; 3], + sort: Value, + grow: Value, + tri_ret: Value, + out: [u32; 4], + ) -> LResult<()> { let ones = self.c(u32::MAX); - for &t in &out { - self.wr(t, ones); + let is_tri = self.cmpc(Pred::ULe, ty, 3); + for (&t, bits) in out.iter().zip([0x7F80_0000u32, 0x3F80_0000, 0, 0]) { + let tri_miss = self.c(bits); + let miss = self.sel(is_tri, tri_miss, ones); + self.wr(t, miss); } + // NaN in origin/dir/inv/tmax or Inf in origin inactivates the ray (clean miss). + let mut bad_ray = self.isnan(tmax); + for c in 0..3 { + let onan = self.isnan(o[c]); + let oinf = self.isinf(o[c]); + let dnan = self.isnan(dir[c]); + let inan = self.isnan(inv[c]); + let b0 = self.lor(onan, oinf); + let b1 = self.lor(dnan, inan); + let bc = self.lor(b0, b1); + bad_ray = self.lor(bad_ray, bc); + } + let ray_ok = self.lnot(bad_ray); for box32 in [true, false] { - let is = self.cmpc(Pred::Eq, ty, if box32 { 5 } else { 4 }); + let is_ty = self.cmpc(Pred::Eq, ty, if box32 { 5 } else { 4 }); + let is = self.land(ray_ok, is_ty); self.guarded(is, &mut |lw| { // Box32 is 28 contiguous dwords (4 children + 4×6 box floats); // Box16 is 16 contiguous dwords (4 children + 4×3 packed f16 pairs). @@ -123,28 +190,6 @@ impl Lw { let mx = [lw.s.f16_to_f32(hy16), lw.s.f16_to_f32(h[2]), lw.s.f16_to_f32(hz16)]; (mn, mx) }; - let d1 = lw.f3(mn, o, Lw::fsub); - let t1 = lw.f3(d1, inv, Lw::fmul); - let d2 = lw.f3(mx, o, Lw::fsub); - let t2 = lw.f3(d2, inv, Lw::fmul); - let mut lo = [pinf; 3]; - let mut hi = [pinf; 3]; - for c in 0..3 { - let ge = lw.fcmp(Pred::FOGe, o[c], mn[c]); - let le = lw.fcmp(Pred::FOLe, o[c], mx[c]); - let slab = lw.land(ge, le); - let ii = lw.isinf(inv[c]); - let l0 = lw.sel(slab, ninf, pinf); - let h0 = lw.sel(slab, pinf, ninf); - let mn_t = lw.fmin(t1[c], t2[c]); - let mx_t = lw.fmax(t1[c], t2[c]); - lo[c] = lw.sel(ii, l0, mn_t); - hi[c] = lw.sel(ii, h0, mx_t); - } - let a = lw.fmax(lo[0], lo[1]); - let a = lw.fmax(a, lo[2]); - let b = lw.fmin(hi[0], hi[1]); - let b = lw.fmin(b, hi[2]); let cv = lw.cmpc(Pred::Ne, child[k], u32::MAX); // Reject all-zero unmapped-page / Box32 page-straddle entries where // `child == 0` AND all box bounds are 0 (prevents infinite BVH traversal @@ -170,6 +215,30 @@ impl Lw { let le = lw.fcmp(Pred::FOLe, mn[c], mx[c]); all = lw.land(all, le); } + let gmn = [lw.bvh_grow_lo(mn[0], grow), lw.bvh_grow_lo(mn[1], grow), lw.bvh_grow_lo(mn[2], grow)]; + let gmx = [lw.bvh_grow_hi(mx[0], grow), lw.bvh_grow_hi(mx[1], grow), lw.bvh_grow_hi(mx[2], grow)]; + let d1 = lw.f3(gmn, o, Lw::fsub); + let t1 = lw.f3(d1, inv, Lw::fmul); + let d2 = lw.f3(gmx, o, Lw::fsub); + let t2 = lw.f3(d2, inv, Lw::fmul); + let mut lo = [pinf; 3]; + let mut hi = [pinf; 3]; + for c in 0..3 { + let ge = lw.fcmp(Pred::FOGe, o[c], gmn[c]); + let le = lw.fcmp(Pred::FOLe, o[c], gmx[c]); + let slab = lw.land(ge, le); + let ii = lw.isinf(inv[c]); + let l0 = lw.sel(slab, ninf, pinf); + let h0 = lw.sel(slab, pinf, ninf); + let mn_t = lw.fmin(t1[c], t2[c]); + let mx_t = lw.fmax(t1[c], t2[c]); + lo[c] = lw.sel(ii, l0, mn_t); + hi[c] = lw.sel(ii, h0, mx_t); + } + let a = lw.fmax(lo[0], lo[1]); + let a = lw.fmax(a, lo[2]); + let b = lw.fmin(hi[0], hi[1]); + let b = lw.fmin(b, hi[2]); let ab = lw.fcmp(Pred::FOLe, a, b); let z = lw.fc(0.0); let b0 = lw.fcmp(Pred::FOGe, b, z); @@ -196,7 +265,7 @@ impl Lw { Ok(()) })?; } - let tri = self.cmpc(Pred::ULe, ty, 3); + let tri = self.land(ray_ok, is_tri); self.guarded(tri, &mut |lw| { let t0 = lw.cmpc(Pred::Eq, ty, 0); let t1 = lw.cmpc(Pred::Eq, ty, 1); @@ -266,7 +335,13 @@ impl Lw { let s1 = lw.andc(s1, 3); let bci = lw.pick4f(&bc, s0); let bcj = lw.pick4f(&bc, s1); - let res = [lw.bits(t), lw.bits(det), lw.bits(bci), lw.bits(bcj)]; + let tri_id = lw.add(tw, ty); + let one = lw.c(1); + let bci_bits = lw.bits(bci); + let bcj_bits = lw.bits(bcj); + let w2 = lw.sel(tri_ret, bci_bits, tri_id); + let w3 = lw.sel(tri_ret, bcj_bits, one); + let res = [lw.bits(t), lw.bits(det), w2, w3]; let miss = [lw.c(0x7F80_0000), lw.c(0x3F80_0000), lw.c(0), lw.c(0)]; for k in 0..4 { let v = lw.sel(hit, res[k], miss[k]); @@ -939,7 +1014,7 @@ impl Lw { } else { ([fl(self, k + 4), fl(self, k + 5), fl(self, k + 6)], [fl(self, k + 7), fl(self, k + 8), fl(self, k + 9)]) }; - let (d0, d1) = (self.sreg(srsrc), self.sreg(srsrc + 1)); + let (d0, d1, d3) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 3)); // address: ((d1 & 0xFF) << 32 | d0) << 8 + node offset (8-byte units); low 32 bits let nlo = self.andc(node, !7); let base_lo = self.shlc(d0, 8); @@ -984,6 +1059,15 @@ impl Lw { let s = self.lshrc(d1, 31); self.nz(s) }; + let grow = { + let g = self.lshrc(d1, 23); + self.andc(g, 0xFF) + }; + let tri_ret = { + let m = self.lshrc(d3, 24); + let m = self.andc(m, 1); + self.nz(m) + }; let act = self.act(); let out = [self.tmp_var(), self.tmp_var(), self.tmp_var(), self.tmp_var()]; self.guarded(act, &mut |lw| { @@ -1000,9 +1084,9 @@ impl Lw { let miss = lw.sel(tri, triangle, box_miss); lw.wr(t, miss); } - lw.guarded(valid, &mut |lw| lw.bvh_intersect(ty, a, extent, origin, dir, inv, sort, out))?; + lw.guarded(valid, &mut |lw| lw.bvh_intersect(ty, a, extent, origin, dir, inv, sort, grow, tri_ret, out))?; } else { - lw.bvh_intersect(ty, a, extent, origin, dir, inv, sort, out)?; + lw.bvh_intersect(ty, a, extent, origin, dir, inv, sort, grow, tri_ret, out)?; } for (c, &t) in out.iter().enumerate() { let v = lw.rd(t); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 766558a9c7..938b6e60ad 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2623,19 +2623,20 @@ impl Em { format!("float3({}, {}, {})", fl(self, k + 7), fl(self, k + 8), fl(self, k + 9)), ) }; - let (d0, d1) = (self.sreg(srsrc), self.sreg(srsrc + 1)); + let (d0, d1, d3) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 3)); let a = self.t(); let t = self.t(); let act = self.act(); // descriptor: 48-bit base address in 256-byte units (word 0 + word 1 [7:0]), - // box sorting = word 1 bit 31; node offset is 32-bit (bvh) or 64-bit (bvh64) in 8-byte units + // box grow ULPs = word 1 [30:23], box sorting = word 1 bit 31, + // triangle return mode = word 3 bit 24 (bit 120); node offset is 32-bit (bvh) or 64-bit (bvh64) in 8-byte units let off = match node_hi { Some(hi) => format!("((((uint64_t){hi} << 32) | (uint64_t)({node} & ~7u)) << 3)"), None => format!("((uint64_t)({node} & ~7u) << 3)"), }; self.line(&format!("uint64_t {a} = ((((uint64_t)({d1} & 0xFFu) << 32) | (uint64_t){d0}) << 8) + {off};")); self.window_read(&format!("(uint)({a} >> 32)")); - let intersect = format!("bvh_intersect({node} & 7u, (uint){a}, {extent}, {origin}, {dir}, {inv}, ({d1} >> 31) != 0u)"); + let intersect = format!("bvh_intersect({node} & 7u, (uint){a}, {extent}, {origin}, {dir}, {inv}, ({d1} >> 31) != 0u, ({d1} >> 23) & 0xFFu, (({d3} >> 24) & 1u) != 0u)"); if self.opt.mem_windows > 1 { self.line(&format!("uint4 {t}; if (xcl_w < {}u) {{ {t} = {intersect}; }} else if (({node} & 7u) < 4u) {{ {t} = uint4(0x7f800000u, 0x3f800000u, 0u, 0u); }} else {{ {t} = 0xffffffffu; }}", self.opt.mem_windows)); } else { @@ -6202,10 +6203,27 @@ uint fmt_comp(uint4 r, uint info, uint c) { return select(c >= n, select(c == 3u, select(isint, 1u, 0x3F800000u), 0u), res); } // image_bvh(64)_intersect_ray: type = node & 7, at = low 32 bits of base + (node & ~7) * 8. -// box32 (5) / box16 (4): 4 child ids + boxes → hit children (closest first when sorting), -// misses 0xFFFFFFFF; triangle (0..3): (t numerator, denominator, i, j numerators), miss t = inf; +// box32 (5) / box16 (4): 4 child ids + boxes (expanded by `grow` ULPs) → hit children (closest first when sorting), +// misses 0xFFFFFFFF; triangle (0..3): mode 1 = (t numerator, denominator, i, j numerators), +// mode 0 = (t numerator, denominator, triangle_id + type, hit_status), miss t = inf; +// NaN in origin/dir/inv/tmax or Inf in origin inactivates the ray; // instance / AABB nodes are left to the shader (all 0xFFFFFFFF). -uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 inv, bool sort) { +float bvh_grow_hi(float x, uint g) { + uint u = asuint(x); + uint mag = u & 0x7FFFFFFFu; + if (g == 0u || mag >= 0x7F800000u) return x; + bool neg = (u & 0x80000000u) != 0u && mag != 0u; + uint res = neg ? (mag > g ? (0x80000000u | (mag - g)) : (g - mag)) : min(mag + g, 0x7F800000u); + return asfloat(res); +} +float bvh_grow_lo(float x, uint g) { + return g == 0u ? x : -bvh_grow_hi(-x, g); +} +uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 inv, bool sort, uint grow, bool tri_ret) { + bool bad_ray = any(isnan(o)) || any(isinf(o)) || any(isnan(d)) || any(isnan(inv)) || isnan(tmax); + if (bad_ray) { + return type <= 3u ? uint4(0x7F800000u, asuint(1.0f), 0u, 0u) : uint4(0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu); + } if (type == 4u || type == 5u) { uint4 child = mem.Load4(at); float tn[4]; uint id[4]; @@ -6214,13 +6232,15 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i float3 mn, mx; if (type == 5u) { mn = asfloat(mem.Load3(at + 16u + 24u * k)); mx = asfloat(mem.Load3(at + 28u + 24u * k)); } else { uint3 h = mem.Load3(at + 16u + 12u * k); mn = float3(f16tof32(h.x), f16tof32(h.x >> 16), f16tof32(h.y)); mx = float3(f16tof32(h.y >> 16), f16tof32(h.z), f16tof32(h.z >> 16)); } - float3 t1 = (mn - o) * inv, t2 = (mx - o) * inv; - bool3 in_slab = and(o >= mn, o <= mx); + bool valid = and(child[k] != 0xFFFFFFFFu, all(mn <= mx)); + float3 gmn = float3(bvh_grow_lo(mn.x, grow), bvh_grow_lo(mn.y, grow), bvh_grow_lo(mn.z, grow)); + float3 gmx = float3(bvh_grow_hi(mx.x, grow), bvh_grow_hi(mx.y, grow), bvh_grow_hi(mx.z, grow)); + float3 t1 = (gmn - o) * inv, t2 = (gmx - o) * inv; + bool3 in_slab = and(o >= gmn, o <= gmx); float3 lo = select(isinf(inv), select(in_slab, ninf, pinf), min(t1, t2)); float3 hi = select(isinf(inv), select(in_slab, pinf, ninf), max(t1, t2)); float a = max(max(lo.x, lo.y), lo.z); float b = min(min(hi.x, hi.y), hi.z); - bool valid = and(child[k] != 0xFFFFFFFFu, all(mn <= mx)); bool hit = and(and(valid, a <= b), and(b >= 0.0f, a <= tmax)); tn[k] = hit ? a : asfloat(0x7F800000u); id[k] = hit ? child[k] : 0xFFFFFFFFu; @@ -6249,8 +6269,11 @@ uint4 bvh_intersect(uint type, uint at, float tmax, float3 o, float3 d, float3 i bool hit = det > 0.0f ? (i >= 0.0f && j >= 0.0f && i + j <= det) : (det < 0.0f && i <= 0.0f && j <= 0.0f && i + j >= det); // barycentrics back to the original vertex order: triangle id @60, per triangle I / J source uint4 bc = asuint(float4(det - i - j, i, j, 0.0f)); - uint tid = mem.Load(at + 60u) >> (8u * type); - return hit ? uint4(asuint(t), asuint(det), pick4(bc, tid & 3u), pick4(bc, (tid >> 2) & 3u)) : uint4(0x7F800000u, asuint(1.0f), 0u, 0u); + uint tw = mem.Load(at + 60u); + uint tid = tw >> (8u * type); + uint w2 = tri_ret ? pick4(bc, tid & 3u) : (tw + type); + uint w3 = tri_ret ? pick4(bc, (tid >> 2) & 3u) : 1u; + return hit ? uint4(asuint(t), asuint(det), w2, w3) : uint4(0x7F800000u, asuint(1.0f), 0u, 0u); } return uint4(0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 77fef9258a..f63767557d 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5422,8 +5422,8 @@ fn gpu_bvh_intersect_ray() { code.extend(mimg("IMAGE_BVH64_INTERSECT_RAY", 116, 60, 2)); // triangle A, 64-bit node id code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let mut st = KernelState::default(); - st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 0]); - st.sgpr[12..16].copy_from_slice(&[(base >> 8) as u32, 0, u32::MAX, 0]); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 1 << 24]); + st.sgpr[12..16].copy_from_slice(&[(base >> 8) as u32, 0, u32::MAX, 1 << 24]); // lane 0: ray along +z from the origin; lane 1: the same with t max 3.5; lane 2: from (5, 5) let ray = |l: usize| -> ([f32; 3], f32) { match l % 3 { @@ -5694,7 +5694,7 @@ fn gpu_built_bvh_nodes_match_the_cpu_node_test() { let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap(); code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let mut st = KernelState::default(); - st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 0]); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 1 << 24]); let mut r = bvh::tests::rng(17); let mut rays = vec![]; for (l, v) in st.vgpr.iter_mut().enumerate() { @@ -5762,7 +5762,7 @@ fn gpu_triangle_pair_and_box16_nodes() { let mut code = encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", 100), ("VADDR", 0), ("SRSRC", 2), ("DMASK", 15)], None).unwrap(); code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let mut st = KernelState::default(); - st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 0]); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 1 << 24]); let mut r = bvh::tests::rng(5); let nodes = [root, t0, t1]; let mut rays = vec![]; @@ -5927,6 +5927,172 @@ fn gpu_bvh_node_in_an_unmapped_window_returns_a_miss() { } } +/// `image_bvh_intersect_ray` descriptor options and ray validation across both HLSL and Direct DXIL: +/// - box-grow ULP expansion (word 1 bits [30:23]) expands valid box32/box16 bounds without +/// activating inverted or NaN-disabled boxes; +/// - NaN in origin/dir/inv/tmax or Inf in origin produces a clean miss for boxes and triangles; +/// - triangle return mode 0 (word 3 bit 24 == 0) returns `(t_num, t_denom, triangle_id + type, hit_status)` +/// while mode 1 (bit 24 == 1) returns `(t_num, t_denom, i_num, j_num)`. +#[test] +fn gpu_bvh_box_grow_nan_inactivation_and_tri_mode0() { + if !gpu_ready() { + return; + } + let base = 0x1000usize; + let mut mem = vec![0u32; 0x2000 / 4]; + let w = |mem: &mut Vec, at: usize, vals: &[u32]| mem[(base + at) / 4..(base + at) / 4 + vals.len()].copy_from_slice(vals); + let ff = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + + // Box32 at 0: child 0 = [1.0..2.0, -1.0..1.0, 5.0..6.0], child 1 = inverted (mn > mx by 1 ULP), + // child 2 = NaN-disabled box, child 3 = invalid. + let c0 = 0x100u32 >> 3; + let c1 = 0x140u32 >> 3; + let c2 = 0x180u32 >> 3; + let inv_lo = f32::from_bits(1.0f32.to_bits() + 1); + w(&mut mem, 0, &[c0, c1, c2, u32::MAX]); + w(&mut mem, 16, &ff(&[1.0, -1.0, 5.0, 2.0, 1.0, 6.0])); + w(&mut mem, 40, &ff(&[inv_lo, -1.0, 5.0, 1.0, 1.0, 6.0])); + w(&mut mem, 64, &ff(&[f32::NAN, -1.0, 5.0, 2.0, 1.0, 6.0])); + + // Box16 at 0x80: child 0 = [1.0..2.0, -1.0..1.0, 5.0..6.0]. + let h = |x: f32| half_bits(x); + w(&mut mem, 0x80, &[c0, u32::MAX, u32::MAX, u32::MAX]); + w(&mut mem, 0x90, &[h(1.0) | (h(-1.0) << 16), h(5.0) | (h(2.0) << 16), h(1.0) | (h(6.0) << 16)]); + + // Triangle node at 0xC0: type 0 = (v0, v1, v2) and type 1 = (v1, v3, v2) in z = 5. + // triangle_id dword @60 = 0x0909_0909 (plain vertex order for all 4 slots). + w(&mut mem, 0xC0, &ff(&[-1.0, -1.0, 5.0, 1.0, -1.0, 5.0, -1.0, 1.0, 5.0, 1.0, 1.0, 5.0])); + let tri_id_word = 0x0909_0909u32; + w(&mut mem, 0xC0 + 60, &[tri_id_word]); + + let root32 = 5u32; + let root16 = (0x80u32 >> 3) | 4; + let tri0 = 0xC0u32 >> 3; + let tri1 = tri0 | 1; + + let mimg = |vdata: u64, vaddr: u64, srsrc: u64| encode("IMAGE_BVH_INTERSECT_RAY", "ENC_MIMG", &[("VDATA", vdata), ("VADDR", vaddr), ("SRSRC", srsrc), ("DMASK", 15)], None).unwrap(); + let mut code = Vec::new(); + // srsrc 2 (s[8:11]): grow = 0, mode 0 (d3 = 0) + // srsrc 3 (s[12:15]): grow = 4 ULPs, mode 1 (d3 = 1 << 24) + code.extend(mimg(100, 0, 2)); // box32, grow=0 + code.extend(mimg(104, 0, 3)); // box32, grow=4 + code.extend(mimg(108, 20, 2)); // box16, grow=0 + code.extend(mimg(112, 20, 3)); // box16, grow=4 + code.extend(mimg(116, 40, 2)); // tri, mode 0 + code.extend(mimg(120, 40, 3)); // tri, mode 1 + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let mut st = KernelState::default(); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 1 << 31, u32::MAX, 0]); + st.sgpr[12..16].copy_from_slice(&[(base >> 8) as u32, (1 << 31) | (4 << 23), u32::MAX, 1 << 24]); + + let x_miss_3ulp = f32::from_bits(1.0f32.to_bits() - 3); + let x_miss_6ulp = f32::from_bits(1.0f32.to_bits() - 6); + let x_hi_3ulp = f32::from_bits(2.0f32.to_bits() + 3); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let (box_ray, tri_node, tri_ray) = match l % 10 { + // 0: 3 ULPs below mn.x -> misses grow=0, hits grow=4 + 0 => ([100.0, x_miss_3ulp, 0.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0], tri0, [100.0, -0.25, -0.25, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0]), + // 1: 6 ULPs below mn.x -> misses both grow=0 and grow=4 + 1 => ([100.0, x_miss_6ulp, 0.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0], tri1, [100.0, 0.25, 0.25, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0]), + // 2: 3 ULPs above mx.x -> misses grow=0, hits grow=4 + 2 => ([100.0, x_hi_3ulp, 0.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0], tri0, [100.0, 5.0, 5.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0]), + // 3: NaN origin -> clean miss on both box and triangle + 3 => ([100.0, f32::NAN, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], tri0, [100.0, f32::NAN, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]), + // 4: +Inf origin -> clean miss + 4 => ([100.0, f32::INFINITY, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], tri0, [100.0, f32::INFINITY, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]), + // 5: -Inf origin -> clean miss + 5 => ([100.0, f32::NEG_INFINITY, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], tri0, [100.0, f32::NEG_INFINITY, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]), + // 6: NaN dir -> clean miss + 6 => ([100.0, 1.5, 0.0, 0.0, f32::NAN, 0.0, 1.0, 1.0, 1.0, 1.0], tri0, [100.0, 0.0, 0.0, 0.0, f32::NAN, 0.0, 1.0, 1.0, 1.0, 1.0]), + // 7: NaN inv_dir -> clean miss + 7 => ([100.0, 1.5, 0.0, 0.0, 0.0, 0.0, 1.0, f32::NAN, f32::INFINITY, 1.0], tri0, [100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, f32::NAN, f32::INFINITY, 1.0]), + // 8: NaN tmax -> clean miss + 8 => ([f32::NAN, 1.5, 0.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0], tri0, [f32::NAN, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0]), + // 9: normal hit with finite origin and +inf inv on zero-dir axes + _ => ([100.0, 1.5, 0.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0], tri0, [100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0]), + }; + let put = |r: &mut Vec, at: usize, node: u32, ray: [f32; 10]| { + r[at] = node; + for (k, x) in ray.into_iter().enumerate() { + r[at + 1 + k] = x.to_bits(); + } + }; + put(r, 0, root32, box_ray); + put(r, 20, root16, box_ray); + put(r, 40, tri_node, tri_ray); + } + + let opt = on_gpu(Options::default()); + let hlsl = translate(&code, &opt).unwrap(); + let hlsl_dxil = super::dxc::compile(&hlsl.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", hlsl.hlsl)).unwrap(); + let direct_dxil = crate::gpu::dxil::kernel::translate( + &code, + crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: opt.split_wave64, mem_windows: 1, sampler_base: 0 }, + ) + .unwrap(); + + const F: u32 = u32::MAX; + const TRI_MISS: [u32; 4] = [0x7F80_0000, 0x3F80_0000, 0, 0]; + for (backend, dxil) in [("hlsl", hlsl_dxil), ("direct-dxil", direct_dxil)] { + let res = runner::run(&dxil, &st, &mem).unwrap(); + for l in 0..64usize { + let v = &res.vgpr[l]; + let q = |at: usize| [v[at], v[at + 1], v[at + 2], v[at + 3]]; + match l % 10 { + 0 | 2 => { + assert_eq!(q(100), [F, F, F, F], "{backend} lane {l}: box32 grow=0 misses by 3 ULPs"); + assert_eq!(q(104), [c0, F, F, F], "{backend} lane {l}: box32 grow=4 hits c0 only (inverted/NaN stay invalid)"); + assert_eq!(q(108), [F, F, F, F], "{backend} lane {l}: box16 grow=0 misses by 3 ULPs"); + assert_eq!(q(112), [c0, F, F, F], "{backend} lane {l}: box16 grow=4 hits c0"); + } + 1 => { + assert_eq!(q(100), [F, F, F, F], "{backend} lane {l}: box32 grow=0 misses by 6 ULPs"); + assert_eq!(q(104), [F, F, F, F], "{backend} lane {l}: box32 grow=4 still misses by 6 ULPs"); + assert_eq!(q(108), [F, F, F, F], "{backend} lane {l}: box16 grow=0 misses by 6 ULPs"); + assert_eq!(q(112), [F, F, F, F], "{backend} lane {l}: box16 grow=4 still misses by 6 ULPs"); + } + 3..=8 => { + assert_eq!(q(100), [F, F, F, F], "{backend} lane {l}: invalid ray misses box32 (grow=0)"); + assert_eq!(q(104), [F, F, F, F], "{backend} lane {l}: invalid ray misses box32 (grow=4)"); + assert_eq!(q(108), [F, F, F, F], "{backend} lane {l}: invalid ray misses box16 (grow=0)"); + assert_eq!(q(112), [F, F, F, F], "{backend} lane {l}: invalid ray misses box16 (grow=4)"); + assert_eq!(q(116), TRI_MISS, "{backend} lane {l}: invalid ray misses triangle (mode 0)"); + assert_eq!(q(120), TRI_MISS, "{backend} lane {l}: invalid ray misses triangle (mode 1)"); + } + _ => { + assert_eq!(q(100), [c0, F, F, F], "{backend} lane {l}: valid ray hits box32"); + assert_eq!(q(108), [c0, F, F, F], "{backend} lane {l}: valid ray hits box16"); + } + } + match l % 10 { + 0 | 9 => { + let m0 = q(116); + let m1 = q(120); + assert_eq!(m0[0], m1[0], "{backend} lane {l}: mode 0 & 1 share t_num"); + assert_eq!(m0[1], m1[1], "{backend} lane {l}: mode 0 & 1 share t_denom"); + assert!(((f32::from_bits(m0[0]) / f32::from_bits(m0[1])) - 5.0).abs() < 1e-4); + assert_eq!(m0[2], tri_id_word, "{backend} lane {l}: mode 0 type 0 returns triangle_id + 0"); + assert_eq!(m0[3], 1, "{backend} lane {l}: mode 0 hit_status == 1"); + } + 1 => { + let m0 = q(116); + let m1 = q(120); + assert_eq!(m0[0], m1[0], "{backend} lane {l}: mode 0 & 1 share t_num (tri1)"); + assert_eq!(m0[1], m1[1], "{backend} lane {l}: mode 0 & 1 share t_denom (tri1)"); + assert_eq!(m0[2], tri_id_word + 1, "{backend} lane {l}: mode 0 type 1 returns triangle_id + 1"); + assert_eq!(m0[3], 1, "{backend} lane {l}: mode 0 tri1 hit_status == 1"); + } + 2 => { + assert_eq!(q(116), TRI_MISS, "{backend} lane {l}: mode 0 geometric miss"); + assert_eq!(q(120), TRI_MISS, "{backend} lane {l}: mode 1 geometric miss"); + } + _ => {} + } + } + } +} + /// Instructions first met in XboxBvhBuilder.dll's shaders: global atomics (float min / max by /// a CAS loop), 8 / 16-bit buffer loads / stores and 8 / 16-bit LDS accesses – neighbouring /// lanes share dwords, so a non-atomic read-modify-write would lose writes. @@ -10643,7 +10809,7 @@ fn gpu_bvh_triangle_types_2_and_3() { code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let mut st = KernelState::default(); - st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 0, u32::MAX, 0]); + st.sgpr[8..12].copy_from_slice(&[(base >> 8) as u32, 0, u32::MAX, 1 << 24]); let set_ray = |r: &mut Vec, at: usize, node: u32, ox: f32, oy: f32| { r[at] = node; let v = [100.0f32, ox, oy, 0.0, 0.0, 0.0, 1.0, f32::INFINITY, f32::INFINITY, 1.0]; From 081da4b91556af2cd862b477f1bebc5a93ebe0d7 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:06:26 +0100 Subject: [PATCH 014/175] DirectStorage: implement CPU unshuffle/interleave for BCn swizzle modes --- crates/xcl/src/hle/dstorage.rs | 217 +++++++++++++++++++++++++++++++-- 1 file changed, 209 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 7dbcf8aa22..b3b1bc10f3 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -28,7 +28,7 @@ //! VFS like the title's own, memory copies, zlib, BCPack where `hle::bcpack` rebuilds the //! blocks of the mode), a status entry gets the first failure of the requests since the //! previous one, a signal sets the fence from the CPU. Methods not listed are logged and -//! answer E_NOTIMPL; BCPack BC2 and modes above 7, and the hardware swizzle, are refused. +//! answer E_NOTIMPL; BCPack BC2 and modes above 7, and swizzle modes above 4, are refused. #![allow(non_snake_case)] @@ -252,6 +252,57 @@ pub struct BcpackUnpackStats { pub failed: u64, } +/// Per-group stream chunk lengths (bytes) for each supported `DSTORAGE_SWIZZLE_MODE`. +/// Modes 1..=4 interleave whole-buffer per-stream arrays into 16 KiB or 32 KiB groups so a +/// title's compute shader can reconstruct the final BCn blocks in place: +/// - 1 (`4K_4K_8K`, 16 KiB): BC1 endpoints and indices +/// - 2 (`4K_4K_24K`, 32 KiB): BC4 endpoints and indices +/// - 3 (`4K_12K_4K_4K_8K`, 32 KiB): BC3 alpha and colour streams +/// - 4 (`4K_12K_4K_12K`, 32 KiB): BC5 two-channel streams +fn swizzle_chunks(mode: u16) -> Option<&'static [usize]> { + const K: usize = 1024; + match mode { + 1 => Some(&[4 * K, 4 * K, 8 * K]), + 2 => Some(&[4 * K, 4 * K, 24 * K]), + 3 => Some(&[4 * K, 12 * K, 4 * K, 4 * K, 8 * K]), + 4 => Some(&[4 * K, 12 * K, 4 * K, 12 * K]), + _ => None, + } +} + +/// Group alignment (bytes) required by `mode` (0 = none; None = unsupported mode). +fn swizzle_group_size(mode: u16) -> Option { + if mode == 0 { + return Some(0); + } + swizzle_chunks(mode).map(|chunks| chunks.iter().sum()) +} + +/// Rearrange stream-grouped bytes `src` into interleaved 16 KiB / 32 KiB groups for `mode` (1..=4). +fn swizzle_interleave(mode: u16, src: &[u8]) -> Result, HRESULT> { + let Some(chunks) = swizzle_chunks(mode) else { + return Err(E_DECOMPRESSION); + }; + let group_size: usize = chunks.iter().sum(); + if src.is_empty() || src.len() % group_size != 0 { + return Err(E_DESTINATION_SIZE); + } + let groups = src.len() / group_size; + let mut dst = vec![0u8; src.len()]; + let mut stream_base = 0usize; + let mut group_off = 0usize; + for &chunk_len in chunks { + for g in 0..groups { + let s = stream_base + g * chunk_len; + let d = g * group_size + group_off; + dst[d..d + chunk_len].copy_from_slice(&src[s..s + chunk_len]); + } + stream_base += groups * chunk_len; + group_off += chunk_len; + } + Ok(dst) +} + /// The BCPack stage of a request: `packed` to the `n` bytes of blocks of its mode. fn bcpack_unpack(r: &Request, packed: &[u8], n: usize) -> Result, HRESULT> { let bc = r.bcpack(); @@ -733,9 +784,13 @@ impl Request { if self.options & !KNOWN_OPTIONS_MASK != 0 { warn_once("DSTORAGE_REQUEST_OPTIONS", format_args!("unknown high option bits {:#x}", self.options & !KNOWN_OPTIONS_MASK)); } - if self.swizzle() != 0 { - warn_once("SwizzleMode", format_args!("hardware swizzle mode {} unsupported", self.swizzle())); + let swiz = self.swizzle(); + let Some(swiz_group) = swizzle_group_size(swiz) else { + warn_once("SwizzleMode", format_args!("swizzle mode {swiz} unsupported")); return Err(E_DECOMPRESSION); + }; + if swiz_group != 0 && (self.destination_size == 0 || self.destination_size as usize % swiz_group != 0) { + return Err(E_DESTINATION_SIZE); } match (self.zlib(), self.bcpack()) { // Uncompressed copy: source and destination sizes must match. @@ -969,11 +1024,12 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us }; let bc = r.bcpack(); - if r.swizzle() != 0 || (bc != 0 && !super::bcpack::can_decode(bc)) { + let swiz = r.swizzle(); + if (swiz != 0 && swizzle_chunks(swiz).is_none()) || (bc != 0 && !super::bcpack::can_decode(bc)) { return Err(E_DECOMPRESSION); } - // the stages in the console's order: zlib, then BCPack + // the stages in the console's order: zlib, BCPack, then swizzle interleave let stage1: Vec = if r.zlib() { let stage1_len = if r.intermediate_size != 0 { r.intermediate_size as usize } else { n }; let mut d = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(&src, stage1_len).map_err(|_| E_ZLIB_DATA)?; @@ -992,7 +1048,8 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us } else { src }; - let payload = if bc != 0 { bcpack_unpack(r, &stage1, n)? } else { stage1 }; + let unpacked = if bc != 0 { bcpack_unpack(r, &stage1, n)? } else { stage1 }; + let payload = if swiz != 0 { swizzle_interleave(swiz, &unpacked[..n])? } else { unpacked }; if r.dest_physical_pages() { let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; @@ -2179,8 +2236,11 @@ mod tests { assert_eq!(Request::parse(&request_ex(bc2, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Err(E_DECOMPRESSION)); assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 0, 0)).check(false), Ok(())); assert_eq!(Request::parse(&request_ex(bc1, 0x1000, 0, 256, 0x2000, 0, 20, 64, 0)).check(false), Err(E_DESTINATION_SIZE)); - // Hardware swizzle mode unsupported - assert_eq!(Request::parse(&request_ex(swiz, 0x1000, 0, 64, 0x2000, 0, 64, 0, 0)).check(false), Err(E_DECOMPRESSION)); + // Swizzle modes 1..=4 validate group alignment (16 KiB / 32 KiB); modes > 4 are refused + let swiz_bad = 5u64 << SWIZZLE_SHIFT; + assert_eq!(Request::parse(&request_ex(swiz, 0x1000, 0, 64, 0x2000, 0, 64, 0, 0)).check(false), Err(E_DESTINATION_SIZE)); + assert_eq!(Request::parse(&request_ex(swiz, 0x1000, 0, 16 * 1024, 0x2000, 0, 16 * 1024, 0, 0)).check(false), Ok(())); + assert_eq!(Request::parse(&request_ex(swiz_bad, 0x1000, 0, 32 * 1024, 0x2000, 0, 32 * 1024, 0, 0)).check(false), Err(E_DECOMPRESSION)); // SourceIsPhysicalPages requires memory source assert_eq!(Request::parse(&request_ex(SOURCE_PHYS_PAGES_BIT, 0x1000, 0, 64, 0x2000, 0, 64, 0, 0)).check(false), Err(E_SOURCE_TYPE)); @@ -3130,4 +3190,145 @@ mod tests { status_release(s); } } + + #[test] + fn swizzle_interleave_all_four_modes_and_validation() { + const K: usize = 1024; + let cases: [(u16, &[usize]); 4] = [ + (1, &[4 * K, 4 * K, 8 * K]), + (2, &[4 * K, 4 * K, 24 * K]), + (3, &[4 * K, 12 * K, 4 * K, 4 * K, 8 * K]), + (4, &[4 * K, 12 * K, 4 * K, 12 * K]), + ]; + assert_eq!(swizzle_interleave(0, &[0u8; 16 * K]), Err(E_DECOMPRESSION)); + assert_eq!(swizzle_interleave(5, &[0u8; 32 * K]), Err(E_DECOMPRESSION)); + for (mode, chunks) in cases { + let group_size: usize = chunks.iter().sum(); + assert_eq!(swizzle_group_size(mode), Some(group_size)); + assert_eq!(swizzle_interleave(mode, &[]), Err(E_DESTINATION_SIZE)); + assert_eq!(swizzle_interleave(mode, &vec![0u8; group_size - 1]), Err(E_DESTINATION_SIZE)); + assert_eq!(swizzle_interleave(mode, &vec![0u8; group_size + 4096]), Err(E_DESTINATION_SIZE)); + + // 3 groups: fill each (stream, group) chunk with a unique deterministic pattern. + let groups = 3usize; + let total = groups * group_size; + let mut src = vec![0u8; total]; + let mut stream_base = 0usize; + for (si, &clen) in chunks.iter().enumerate() { + for g in 0..groups { + let slice = &mut src[stream_base + g * clen..stream_base + (g + 1) * clen]; + for (i, b) in slice.iter_mut().enumerate() { + *b = ((si as u8).wrapping_mul(53)) + ^ ((g as u8).wrapping_mul(17)) + ^ ((i & 0xFF) as u8) + ^ (((i >> 8) & 0xFF) as u8); + } + } + stream_base += groups * clen; + } + let out = swizzle_interleave(mode, &src).unwrap(); + assert_eq!(out.len(), total); + for g in 0..groups { + let mut off = g * group_size; + for (si, &clen) in chunks.iter().enumerate() { + let slice = &out[off..off + clen]; + for (i, &b) in slice.iter().enumerate() { + let expected = ((si as u8).wrapping_mul(53)) + ^ ((g as u8).wrapping_mul(17)) + ^ ((i & 0xFF) as u8) + ^ (((i >> 8) & 0xFF) as u8); + assert_eq!(b, expected, "mode {mode} group {g} stream {si} byte {i}"); + } + off += clen; + } + } + } + } + + #[test] + fn swizzle_end_to_end_single_stage_and_zlib() { + // Test mode 1 (4K/4K/8K, 2 groups = 32 KiB) both single-stage and two-stage (zlib + swizzle) + // on a memory queue, reconstructing original BC1 blocks from each 16 KiB group. + let total = 32 * 1024usize; + let blocks = total / 8; + let mut orig = vec![0u8; total]; + for b in 0..blocks { + let p = b * 8; + orig[p] = (b & 0xFF) as u8; + orig[p + 1] = ((b >> 8) & 0xFF) as u8; + orig[p + 2] = (b.wrapping_mul(3) & 0xFF) as u8; + orig[p + 3] = (b.wrapping_mul(7) & 0xFF) as u8; + orig[p + 4..p + 8].copy_from_slice(&(b as u32).wrapping_mul(0x9E37_79B9).to_le_bytes()); + } + // Group BC1 streams across the whole buffer (e0, e1, indices). + let mut grouped = vec![0u8; total]; + let (mut o0, mut o1, mut o2) = (0usize, total / 4, total / 2); + for b in 0..blocks { + let p = b * 8; + grouped[o0..o0 + 2].copy_from_slice(&orig[p..p + 2]); + grouped[o1..o1 + 2].copy_from_slice(&orig[p + 2..p + 4]); + grouped[o2..o2 + 4].copy_from_slice(&orig[p + 4..p + 8]); + o0 += 2; + o1 += 2; + o2 += 4; + } + let zlib_grouped = miniz_oxide::deflate::compress_to_vec_zlib(&grouped, 6); + assert!(zlib_grouped.len() < grouped.len()); + + unsafe { + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&8u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + + let mut dst_raw = vec![0u8; total]; + let mut dst_zlib = vec![0u8; total]; + let r0 = request(SOURCE_MEMORY_BIT | (1u64 << SWIZZLE_SHIFT), dst_raw.as_mut_ptr() as u64, total as u32, grouped.as_ptr() as u64, 0, grouped.len() as u32); + let r1 = request(SOURCE_MEMORY_BIT | ZLIB_BIT | (1u64 << SWIZZLE_SHIFT), dst_zlib.as_mut_ptr() as u64, total as u32, zlib_grouped.as_ptr() as u64, 0, zlib_grouped.len() as u32); + enqueue(q, r0.as_ptr()); + status(q, s, 0); + enqueue(q, r1.as_ptr()); + status(q, s, 1); + submit(q); + let t = std::time::Instant::now(); + while (!complete(s, 0) || !complete(s, 1)) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!(hresult(s, 0), S_OK); + assert_eq!(hresult(s, 1), S_OK); + assert_eq!(dst_raw, dst_zlib); + + // Reconstruct original BC1 blocks from each 16 KiB group in place and verify exact equality. + let mut rebuilt = vec![0u8; total]; + for g in 0..2 { + let grp = &dst_zlib[g * 16384..(g + 1) * 16384]; + for k in 0..2048 { + let out = (g * 2048 + k) * 8; + rebuilt[out..out + 2].copy_from_slice(&grp[k * 2..k * 2 + 2]); + rebuilt[out + 2..out + 4].copy_from_slice(&grp[4096 + k * 2..4096 + k * 2 + 2]); + rebuilt[out + 4..out + 8].copy_from_slice(&grp[8192 + k * 4..8192 + k * 4 + 4]); + } + } + assert_eq!(rebuilt, orig); + queue_close(q); + queue_release(q); + status_release(s); + } + } } From 108cbafa8957bfa5b4fcebee904f1affcc295563 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:08:02 +0100 Subject: [PATCH 015/175] kernelx: decode XMemVirtualAlloc XMemFlags and refine graphics protection handling --- crates/xcl/src/hle/kernelx.rs | 77 +++++++++++++++++++++++++---------- 1 file changed, 55 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index a7775458f7..4ca45d807f 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -114,7 +114,10 @@ mod sections; pub mod lazy; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; -const STD_PROTECT_MASK: u32 = 0xFF | 0x100 | 0x200 | 0x400; +/// Standard Win32 page access + PAGE_GUARD (0x100). Strips console PAGE_GRAPHICS_* bits as well +/// as PAGE_NOCACHE (0x200) and PAGE_WRITECOMBINE (0x400) so CPU-side texture/buffer upload scans +/// do not read uncached host memory on PC. +const STD_PROTECT_MASK: u32 = 0xFF | 0x100; static WARNED_FLAGS: AtomicU32 = AtomicU32::new(0); @@ -1011,12 +1014,12 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: return q; } } - // the title's GPU heaps (committed with a PAGE_GRAPHICS_* protection, write-combined: memory - // the CPU writes and the GPU reads, as a PC game's upload heaps): in the coherent window, which - // the GPU reads where it is – one copy (a retail game's 4.4 GB; as plain memory its shaders - // read zeros, in the sparse windows video memory would have doubled them). The window is as - // large as what the title put in it last time with this setting (`uma::coherent_hint`). - if addr.is_null() && t & 0x1000 != 0 && p & PAGE_GRAPHICS_ANY != 0 && size <= crate::gpu::uma::MAX_SIZE && std::env::var("XCL_COHERENT_HEAPS").map_or(true, |v| v != "0") { + // the title's GPU heaps (committed with a GPU-accessible PAGE_GRAPHICS_* protection, + // excluding PAGE_GRAPHICS_NOACCESS): in the coherent window, which the GPU reads where it is – + // one copy (a retail game's 4.4 GB; as plain memory its shaders read zeros, in the sparse + // windows video memory would have doubled them). The window is as large as what the title put + // in it last time with this setting (`uma::coherent_hint`). + if addr.is_null() && t & 0x1000 != 0 && p & PAGE_GRAPHICS_GPU_ACCESS != 0 && size <= crate::gpu::uma::MAX_SIZE && std::env::var("XCL_COHERENT_HEAPS").map_or(true, |v| v != "0") { let align = if t & 0x2000_0000 != 0 && t & 0x0040_0000 == 0 { 2 << 20 } else { crate::gpu::uma::GRAIN }; static ASKED: AtomicUsize = AtomicUsize::new(0); // `XCL_COHERENT_HEAPS=sparse[:N]`: heaps of at least N MB (all with no N) go to the @@ -1113,10 +1116,11 @@ fn parse_sparse_heaps(v: &str) -> Option { } /// Whether a VirtualAlloc that reached the plain-memory fallback is GPU-visible title memory -/// (a reservation with MEM_GRAPHICS, MEM_LARGE_PAGES / MEM_64K_PAGES or a PAGE_GRAPHICS_* -/// protection, at no fixed address), which is reserved write-watched (`reserve_watched`). +/// (a reservation with MEM_GRAPHICS, MEM_LARGE_PAGES / MEM_64K_PAGES or a GPU-accessible +/// PAGE_GRAPHICS_* protection, at no fixed address), which is reserved write-watched +/// (`reserve_watched`). fn gpu_visible_fallback(addr: *const c_void, t: u32, p: u32) -> bool { - addr.is_null() && t & 0x2000 != 0 && (t & (MEM_GRAPHICS | 0x2000_0000) != 0 || p & PAGE_GRAPHICS_ANY != 0) + addr.is_null() && t & 0x2000 != 0 && (t & (MEM_GRAPHICS | 0x2000_0000) != 0 || p & PAGE_GRAPHICS_GPU_ACCESS != 0) } /// Plain memory for GPU-visible title memory, write-watched and recorded with the graphics @@ -1131,9 +1135,9 @@ unsafe fn reserve_watched(size: usize, t: u32, p: u32) -> *mut c_void { q } -/// PAGE_GRAPHICS_NOACCESS … PAGE_GRAPHICS_NOCACHE (0x800 – 0x40000): the console's protection of -/// GPU-visible memory -const PAGE_GRAPHICS_ANY: u32 = 0x7_F800; +/// GPU-accessible console page protections: PAGE_GRAPHICS_READONLY (0x1000) through +/// PAGE_GRAPHICS_NOCACHE (0x40000), excluding PAGE_GRAPHICS_NOACCESS (0x800). +const PAGE_GRAPHICS_GPU_ACCESS: u32 = 0x7_F000; /// `XCL_TRACE_MEM=1`: the title's allocations of 64 KiB or more (the first 60; `XCL_TRACE_MEM=n`: /// the first n when n > 1) @@ -1516,16 +1520,24 @@ pub unsafe fn runtime_free(p: usize, attrs: u64) { } } -/// `void* XMemVirtualAlloc(void* address, SIZE_T size, DWORD type, XALLOC_ATTRIBUTES attributes, -/// DWORD protect)`: VirtualAlloc with an allocator's attributes – a graphics memory type is -/// GPU-visible memory (as MEM_GRAPHICS: sparse VRAM pool). -pub unsafe extern "system" fn XMemVirtualAlloc(addr: *const c_void, size: usize, t: u32, attrs: u64, p: u32) -> *mut c_void { - let a = XAllocAttrs::decode(attrs); - let mut t = if a.memory_type != 0 { t | MEM_GRAPHICS } else { t }; - if a.memory_type != 0 && a.page_size == 2 { - t |= 0x8000_0000; +/// Map `XMemVirtualAlloc`'s `XMemFlags` (bit 1 marks graphics memory: `XMEM_GRAPHICS = 0x3`, +/// `XMEM_GRAPHICS_32BIT_ADDRESS = 0x7`; also tolerating legacy `XALLOC_ATTRIBUTES` with +/// `memory_type != 0` in bits 29..=32) into `VirtualAlloc` allocation flags. +fn xmem_virtual_alloc_flags(t: u32, xmem_flags: u64) -> u32 { + let legacy = XAllocAttrs::decode(xmem_flags); + let is_graphics = (xmem_flags & 0x2 != 0) || legacy.memory_type != 0; + let mut out = if is_graphics { t | MEM_GRAPHICS } else { t }; + if legacy.memory_type != 0 && legacy.page_size == 2 { + out |= 0x8000_0000; } - VirtualAlloc(addr, size, t, p) + out +} + +/// `void* XMemVirtualAlloc(void* address, SIZE_T size, DWORD type, ULONGLONG xmem_flags, +/// DWORD protect)`: VirtualAlloc with Xbox memory flags – graphics flags route to GPU-visible +/// memory (`MEM_GRAPHICS`). +pub unsafe extern "system" fn XMemVirtualAlloc(addr: *const c_void, size: usize, t: u32, attrs: u64, p: u32) -> *mut c_void { + VirtualAlloc(addr, size, xmem_virtual_alloc_flags(t, attrs), p) } /// Fast-path `VirtualQuery` / `VirtualQueryEx` / `XMemVirtualQuery` for a committed coherent @@ -3588,6 +3600,27 @@ mod tests { assert_eq!(sanitize_alloc_type(MEM_TITLE), 0x3000); assert_eq!(sanitize_protect(0x1000_0004), 0x04); assert_eq!(sanitize_protect(0x2000_0000), mem::PAGE_READWRITE); + // Strip PAGE_NOCACHE (0x200), PAGE_WRITECOMBINE (0x400), and PAGE_GRAPHICS_* bits; keep PAGE_GUARD (0x100) + assert_eq!(sanitize_protect(0x2404), mem::PAGE_READWRITE); + assert_eq!(sanitize_protect(0x1204), mem::PAGE_READWRITE); + assert_eq!(sanitize_protect(mem::PAGE_READWRITE | mem::PAGE_GUARD), mem::PAGE_READWRITE | mem::PAGE_GUARD); + // XMemVirtualAlloc XMemFlags decoding: XMEM_CPU (0x1) stays CPU-only, XMEM_GRAPHICS (0x3) / 32BIT (0x7) set MEM_GRAPHICS + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x1), 0x3000); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x11), 0x3000); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x3), 0x3000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x7), 0x3000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x2040_6000, 0x27), 0x2040_6000 | MEM_GRAPHICS); + // PAGE_GRAPHICS_NOACCESS alone is not GPU-accessible, whereas READONLY/READWRITE/COHERENT are + let null = std::ptr::null(); + assert!(!gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x800)); + assert!(gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x1000)); + assert!(gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x2000)); + assert!(gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x20000)); + // Device memory budgets for Anaconda (Series X) and Lockhart (Series S) + let mut cfg = crate::config::Config::default(); + assert_eq!(cfg.title_memory_budget_mb(), 13_824); + assert_eq!(cfg.apply_device_type_override("lockhart"), Some("lockhart")); + assert_eq!(cfg.title_memory_budget_mb(), 8_192); unsafe { let p = VirtualAlloc(std::ptr::null(), 0x10000, MEM_GRAPHICS | MEM_TITLE | 0x3000, 0x0400_0004); assert!(!p.is_null()); From fdd1ac2dcf67465655e7fc260d2e9347a638ac8c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:11:48 +0100 Subject: [PATCH 016/175] D3D12.X: track depth/stencil planes in barrier groups and keep legacy barriers with console flags --- crates/xcl/src/hle/d3d12x/barrier_groups.rs | 223 ++++++++++++++++---- crates/xcl/src/hle/d3d12x/list_x.rs | 22 +- 2 files changed, 205 insertions(+), 40 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/barrier_groups.rs b/crates/xcl/src/hle/d3d12x/barrier_groups.rs index 1911754577..91a4010c2f 100644 --- a/crates/xcl/src/hle/d3d12x/barrier_groups.rs +++ b/crates/xcl/src/hle/d3d12x/barrier_groups.rs @@ -130,46 +130,128 @@ pub(super) struct Texture { /// What a texture is like for `transitions_of`: (depth buffer, levels, slices, planes). pub(super) type Shape = (bool, u32, u32, u32); +/// Per-plane tracked states: `[plane 0 (colour or depth), plane 1 (stencil)]`. +pub(super) type PlaneStates = [Option; 2]; + +/// Which planes (up to 2) a barrier's subresource range covers. +fn touched_planes(range: [u32; 6], mips: u32, array: u32, planes: u32) -> [bool; 2] { + let [first_mip, n_mips, _, _, first_plane, n_planes] = range; + let (mips, array, planes) = (mips.max(1), array.max(1), planes.clamp(1, 2)); + if n_mips == 0 { + if first_mip == u32::MAX { + return [true, planes > 1]; + } + let plane = first_mip / (mips * array); + return [plane == 0, plane == 1 && planes > 1]; + } + let p_end = first_plane.saturating_add(n_planes.max(1)).min(planes); + [first_plane == 0 && p_end > 0, first_plane <= 1 && p_end > 1 && planes > 1] +} + +/// Restrict `range` to a single plane `plane` (0 or 1) of a multi-plane texture. +fn range_for_plane(range: [u32; 6], mips: u32, array: u32, plane: u32) -> [u32; 6] { + let [first_mip, n_mips, first_slice, n_slices, _, _] = range; + if n_mips == 0 { + if first_mip == u32::MAX { + return [0, mips.max(1), 0, array.max(1), plane, 1]; + } + return range; + } + [first_mip, n_mips, first_slice, n_slices, plane, 1] +} + /// The transitions (PC D3D12_RESOURCE_BARRIERs as words) of the title's texture barriers `b`: -/// `shape` gives a texture's shape (None: not a texture XCL can ask), `last` the state a -/// texture was last moved to here, and `moved` notes the one it is in after a barrier. -pub(super) fn transitions_of(b: &[Texture], shape: &mut dyn FnMut(usize) -> Option, last: &mut dyn FnMut(usize) -> Option, moved: &mut dyn FnMut(usize, u32)) -> Vec<[u32; 8]> { +/// `shape` gives a texture's shape (None: not a texture XCL can ask), `last` the per-plane states +/// a texture was last moved to here, and `moved` notes the per-plane state after a barrier. +pub(super) fn transitions_of( + b: &[Texture], + shape: &mut dyn FnMut(usize) -> Option, + last: &mut dyn FnMut(usize) -> PlaneStates, + moved: &mut dyn FnMut(usize, usize, u32, u32), +) -> Vec<[u32; 8]> { let mut out = Vec::with_capacity(b.len()); for t in b { if t.res == 0 { continue; } let Some((depth, mips, array, planes)) = shape(t.res) else { continue }; + let stride = mips.max(1) * array.max(1); let after = state_of(t.layout.1, t.access.1, depth); - let before = match t.layout.0 { - UNDEFINED => last(t.res), + let explicit_before = match t.layout.0 { + UNDEFINED => None, l => state_of(l, t.access.0, depth), }; - if t.layout.1 != UNDEFINED && after.is_none() || t.layout.0 != UNDEFINED && before.is_none() { + if t.layout.1 != UNDEFINED && after.is_none() || t.layout.0 != UNDEFINED && explicit_before.is_none() { unknown_layout(t.layout); continue; } - let (before, after) = match (before, after) { - (Some(b), Some(a)) => (b, a), - // to the undefined layout: the texture stays where it is; from it, never moved - // here: where it goes is where it is taken to be - (b, a) => { - if let Some(s) = b.or(a) { - moved(t.res, s); - } - continue; + let touched = touched_planes(t.range, mips, array, planes); + // a barrier split over two lists: its first half ends in SYNC_SPLIT, its second starts there + let flags = if t.sync.1 == SYNC_SPLIT { BEGIN_ONLY } else if t.sync.0 == SYNC_SPLIT { END_ONLY } else { 0 }; + let push_range = |out: &mut Vec<[u32; 8]>, range: [u32; 6], before: u32, after: u32| { + if before == after { + return; + } + let word = |sub: u32| [0, flags, t.res as u32, (t.res as u64 >> 32) as u32, sub, before, after, 0]; + match subresources(range, mips, array, planes) { + None => out.push(word(D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES)), + Some(subs) => out.extend(subs.into_iter().map(word)), } }; - moved(t.res, after); - if before == after { + if t.layout.0 != UNDEFINED { + let before = explicit_before.unwrap(); + match after { + Some(a) => { + for p in 0..2 { + if touched[p] { + moved(t.res, p, a, stride); + } + } + push_range(&mut out, t.range, before, a); + } + // to the undefined layout: the texture stays where it is + None => { + for p in 0..2 { + if touched[p] { + moved(t.res, p, before, stride); + } + } + } + } continue; } - // a barrier split over two lists: its first half ends in SYNC_SPLIT, its second starts there - let flags = if t.sync.1 == SYNC_SPLIT { BEGIN_ONLY } else if t.sync.0 == SYNC_SPLIT { END_ONLY } else { 0 }; - let word = |sub: u32| [0, flags, t.res as u32, (t.res as u64 >> 32) as u32, sub, before, after, 0]; - match subresources(t.range, mips, array, planes) { - None => out.push(word(D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES)), - Some(subs) => out.extend(subs.into_iter().map(word)), + // from the undefined layout: start from the last tracked state of each touched plane + let Some(a) = after else { continue }; + let prev = last(t.res); + for p in 0..2 { + if touched[p] { + moved(t.res, p, a, stride); + } + } + match (touched[0], touched[1]) { + (true, true) if prev[0] == prev[1] => { + if let Some(before) = prev[0] { + push_range(&mut out, t.range, before, a); + } + } + (true, true) => { + for p in 0..2 { + if let Some(before) = prev[p] { + push_range(&mut out, range_for_plane(t.range, mips, array, p as u32), before, a); + } + } + } + (true, false) => { + if let Some(before) = prev[0] { + push_range(&mut out, t.range, before, a); + } + } + (false, true) => { + if let Some(before) = prev[1] { + push_range(&mut out, t.range, before, a); + } + } + (false, false) => {} } } out @@ -183,11 +265,39 @@ fn unknown_layout(layout: (u32, u32)) { } } -/// The state each texture was last moved to by a barrier group (the title's recording order). -static LAST: Sharded = Sharded::new(); +/// Per-resource tracked states (plane 0 = colour/depth, plane 1 = stencil) and plane subresource stride. +#[derive(Clone, Copy, Default)] +struct Tracked { + states: PlaneStates, + plane_stride: u32, +} + +/// The per-plane state each texture was last moved to by a barrier group (the title's recording order). +static LAST: Sharded = Sharded::new(); /// Texture barriers read, and transitions made of them. static COUNTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +/// Keep `LAST` in sync when a legacy `ResourceBarrier` transitions a tracked texture (e.g. to +/// `COMMON` before returning to enhanced barriers). No-op if the resource is not tracked. +pub(super) fn note_legacy_state(res: usize, sub: u32, after: u32) { + if COUNTS[0].load(Ordering::Relaxed) == 0 { + return; + } + let Some(mut cur) = LAST.get(res) else { return }; + if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { + cur.states[0] = Some(after); + if cur.states[1].is_some() { + cur.states[1] = Some(after); + } + } else if cur.plane_stride > 0 { + let p = (sub / cur.plane_stride) as usize; + if p < 2 { + cur.states[p] = Some(after); + } + } + LAST.insert(res, cur); +} + /// The last reference of `res` goes (`real::res_release`). pub(super) fn forget(res: usize) { if COUNTS[0].load(Ordering::Relaxed) != 0 { @@ -285,9 +395,12 @@ pub(super) unsafe fn transitions(n: u32, groups: *const c_void, direct: bool) -> } Some((depth, d.MipLevels as u32, array, planes)) }, - &mut |res| LAST.get(res), - &mut |res, state| { - LAST.insert(res, state); + &mut |res| LAST.get(res).map_or([None, None], |t| t.states), + &mut |res, plane, state, stride| { + let mut cur = LAST.get(res).unwrap_or_default(); + cur.states[plane] = Some(state); + cur.plane_stride = stride; + LAST.insert(res, cur); }, ); out.retain_mut(|w| { @@ -416,11 +529,17 @@ mod tests { Texture { sync: (0, 0), access, layout, res, range: [u32::MAX, 0, 0, 0, 0, 0] } } - fn run(b: &[Texture], last: &mut std::collections::HashMap) -> Vec<(usize, u32, u32, u32, u32)> { - let known = last.clone(); - let mut moved = Vec::new(); - let out = transitions_of(b, &mut |res| (res != 0xBAD).then_some((res == 0xD, 1, 1, if res == 0xD { 2 } else { 1 })), &mut |res| known.get(&res).copied(), &mut |res, s| moved.push((res, s))); - last.extend(moved); + fn run(b: &[Texture], last: &mut std::collections::HashMap) -> Vec<(usize, u32, u32, u32, u32)> { + let state = std::cell::RefCell::new(std::mem::take(last)); + let out = transitions_of( + b, + &mut |res| (res != 0xBAD).then_some((res == 0xD, 1, 1, if res == 0xD { 2 } else { 1 })), + &mut |res| state.borrow().get(&res).copied().unwrap_or([None, None]), + &mut |res, plane, s, _| { + state.borrow_mut().entry(res).or_insert([None, None])[plane] = Some(s); + }, + ); + *last = state.into_inner(); out.iter().map(|w| ((w[2] as u64 | (w[3] as u64) << 32) as usize, w[4], w[5], w[6], w[1])).collect() } @@ -443,17 +562,17 @@ mod tests { let mut last = Default::default(); // never moved here: where it goes is noted, nothing is sent assert_eq!(run(&[t(0xB, (UNDEFINED, 2), (NO_ACCESS, 0x8))], &mut last), []); - assert_eq!(last.get(&0xB), Some(&RENDER_TARGET)); + assert_eq!(last.get(&0xB), Some(&[Some(RENDER_TARGET), None])); // to the undefined layout: it stays a render target assert_eq!(run(&[t(0xB, (2, UNDEFINED), (0x8, NO_ACCESS))], &mut last), []); - assert_eq!(last.get(&0xB), Some(&RENDER_TARGET)); + assert_eq!(last.get(&0xB), Some(&[Some(RENDER_TARGET), None])); // from it into unordered access: from the render target it still is assert_eq!(run(&[t(0xB, (UNDEFINED, 3), (NO_ACCESS, 0x10))], &mut last), [(0xB, ALL, RENDER_TARGET, UNORDERED_ACCESS, 0)]); // and where it already is: nothing assert_eq!(run(&[t(0xB, (UNDEFINED, 3), (NO_ACCESS, 0x10))], &mut last), []); // a texture first seen leaving for the undefined layout is where it says it was assert_eq!(run(&[t(0xC, (6, UNDEFINED), (0x80, NO_ACCESS))], &mut last), []); - assert_eq!(last.get(&0xC), Some(&SHADER_RESOURCE)); + assert_eq!(last.get(&0xC), Some(&[Some(SHADER_RESOURCE), None])); } #[test] @@ -474,4 +593,36 @@ mod tests { b.range = [0, 1, 0, 1, 1, 1]; assert_eq!(run(&[b], &mut last), [(0xD, 1, DEPTH_WRITE, SHADER_RESOURCE, 0)], "the stencil plane of a one-level depth buffer"); } + + #[test] + fn depth_and_stencil_planes_track_independent_states() { + let mut last = Default::default(); + // Put both planes into DEPTH_WRITE, then move only stencil (plane 1) to SHADER_RESOURCE. + assert_eq!(run(&[t(0xD, (UNDEFINED, 4), (NO_ACCESS, 0x20))], &mut last), []); + let mut stencil_srv = t(0xD, (4, 6), (0x20, 0x80)); + stencil_srv.range = [0, 1, 0, 1, 1, 1]; + assert_eq!(run(&[stencil_srv], &mut last), [(0xD, 1, DEPTH_WRITE, SHADER_RESOURCE, 0)]); + assert_eq!(last.get(&0xD), Some(&[Some(DEPTH_WRITE), Some(SHADER_RESOURCE)])); + + // Moving plane 0 from UNDEFINED -> SHADER_RESOURCE must still emit DEPTH_WRITE -> SHADER_RESOURCE + // rather than thinking plane 0 is already SHADER_RESOURCE. + let mut depth_from_undef = t(0xD, (UNDEFINED, 6), (NO_ACCESS, 0x80)); + depth_from_undef.range = [0, 1, 0, 1, 0, 1]; + assert_eq!(run(&[depth_from_undef], &mut last), [(0xD, 0, DEPTH_WRITE, SHADER_RESOURCE, 0)]); + + // Now diverge planes again (plane 0 -> DEPTH_WRITE, plane 1 stays SHADER_RESOURCE) and + // transition ALL subresources from UNDEFINED -> COPY_SOURCE: emits one per-plane transition each. + let mut depth_write = t(0xD, (6, 4), (0x80, 0x20)); + depth_write.range = [0, 1, 0, 1, 0, 1]; + assert_eq!(run(&[depth_write], &mut last), [(0xD, 0, SHADER_RESOURCE, DEPTH_WRITE, 0)]); + assert_eq!( + run(&[t(0xD, (UNDEFINED, 7), (NO_ACCESS, 0x200))], &mut last), + [(0xD, 0, DEPTH_WRITE, COPY_SOURCE, 0), (0xD, 1, SHADER_RESOURCE, COPY_SOURCE, 0)] + ); + // Once both planes agree (COPY_SOURCE), an ALL-subresource UNDEFINED transition emits ALL. + assert_eq!( + run(&[t(0xD, (UNDEFINED, 4), (NO_ACCESS, 0x20))], &mut last), + [(0xD, ALL, COPY_SOURCE, DEPTH_WRITE, 0)] + ); + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index fcc773e722..343fe5cf27 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4907,6 +4907,12 @@ const PC_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 /// #26 ResourceBarrier(count, barriers): console barriers (D3D12_RESOURCE_BARRIER, 32 bytes) as /// PC ones – state bits the PC does not know are dropped (logged: the console's own), a +/// Strip console-only `D3D12_RESOURCE_BARRIER_FLAGS` bits, keeping standard PC +/// `BEGIN_ONLY` (1) / `END_ONLY` (2). Returns `(pc_flags, stripped_console_bits)`. +fn sanitize_barrier_flags(flags: u32) -> (u32, u32) { + (flags & 3, flags & !3) +} + /// transition left with nothing to do goes, aliasing barriers name placed textures pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers: *const [u32; 8]) { static N: AtomicU64 = AtomicU64::new(0); @@ -4922,22 +4928,29 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 let mut uav_global = false; for k in 0..n as usize { let mut b = barriers.add(k).read_unaligned(); - let (ty, flags) = (b[0], b[1]); + let (ty, raw_flags) = (b[0], b[1]); if super::present::trace_frame() && ty == 0 { let r = (b[2] as u64 | (b[3] as u64) << 32) as usize; if super::present::is_watched(r) { static W: AtomicU64 = AtomicU64::new(0); if W.fetch_add(1, Ordering::Relaxed) < 24 { - crate::xlog_info!("frame trace: ResourceBarrier on a watched target {r:#x}: subresource {:#x}, {:#x} → {:#x}, flags {flags:#x}", b[4], b[5], b[6]); + crate::xlog_info!("frame trace: ResourceBarrier on a watched target {r:#x}: subresource {:#x}, {:#x} → {:#x}, flags {raw_flags:#x}", b[4], b[5], b[6]); } } } - if ty > 2 || flags > 3 { + if ty > 2 { if N.fetch_add(1, Ordering::Relaxed) < 16 { - crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier type {ty} flags {flags:#x} dropped ({:x?})", b); + crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier type {ty} flags {raw_flags:#x} dropped ({:x?})", b); } continue; } + let (flags, dropped_flags) = sanitize_barrier_flags(raw_flags); + if dropped_flags != 0 { + if N.fetch_add(1, Ordering::Relaxed) < 16 { + crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier flag bits {dropped_flags:#x} stripped (kept {flags:#x})"); + } + b[1] = flags; + } if ty == 1 { // Keep the identity of textures that really share placed GPU memory. // Committed resources still need the wildcard form on the PC. @@ -4987,6 +5000,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 uav_transition |= (b[5] | b[6]) & UNORDERED_ACCESS != 0; let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; super::format_alias::note_title_transition(res, b[4], b[5], b[6], flags, &mut alias_writers); + super::barrier_groups::note_legacy_state(res, b[4], b[6]); } out.push(b); } From 48cf7139bd93f7eeebf472360a0380142afa8b03 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:14:44 +0100 Subject: [PATCH 017/175] D3D12.X: honor single-plane PresentX source rects, lock-free shader capture, and retained base PSO shaders --- crates/xcl/src/gpu/shader.rs | 37 ++++++----- crates/xcl/src/hle/d3d12x/device_x.rs | 91 +++++++++++++++++++-------- crates/xcl/src/hle/d3d12x/frame.rs | 11 +++- crates/xcl/src/hle/d3d12x/present.rs | 9 ++- 4 files changed, 106 insertions(+), 42 deletions(-) diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 006ced121d..0d510f18d3 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -290,29 +290,38 @@ pub fn capture(stage: &str, ptr: usize, len: usize) { if ptr == 0 && len == 0 { return; // unused stage } - let mut g = STATE.lock().unwrap(); - let st = g.get_or_insert_with(|| State { seen: HashSet::new(), stats: ShaderStats::default(), insts: xbox::InstStats::default() }); - st.stats.submitted += 1; if !readable(ptr, len) { + let mut g = STATE.lock().unwrap(); + let st = g.get_or_insert_with(|| State { seen: HashSet::new(), stats: ShaderStats::default(), insts: xbox::InstStats::default() }); + st.stats.submitted += 1; st.stats.rejected_pointers += 1; if st.stats.rejected_pointers <= 5 { crate::xlog_warn!("[SHADER] {stage}: invalid pointer/size ({ptr:#x}, {len}) – different struct layout on the console?"); } return; } - let blob = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) }.to_vec(); - let h = fnv64(&blob); - *st.stats.by_stage.entry(stage.to_string()).or_default() += 1; - if !st.seen.insert(h) { - return; - } - st.stats.unique += 1; + let slice = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) }; + let h = fnv64(slice); + let blob = { + let mut g = STATE.lock().unwrap(); + let st = g.get_or_insert_with(|| State { seen: HashSet::new(), stats: ShaderStats::default(), insts: xbox::InstStats::default() }); + st.stats.submitted += 1; + *st.stats.by_stage.entry(stage.to_string()).or_default() += 1; + if !st.seen.insert(h) { + return; + } + st.stats.unique += 1; + slice.to_vec() + }; let (kind, parts) = classify(&blob); - *st.stats.by_kind.entry(kind.label().to_string()).or_default() += 1; - for p in parts.iter().filter(|p| !KNOWN_PARTS.contains(&p.fourcc.as_str())) { - *st.stats.unknown_parts.entry(p.fourcc.clone()).or_default() += 1; + { + let mut g = STATE.lock().unwrap(); + let st = g.as_mut().unwrap(); + *st.stats.by_kind.entry(kind.label().to_string()).or_default() += 1; + for p in parts.iter().filter(|p| !KNOWN_PARTS.contains(&p.fourcc.as_str())) { + *st.stats.unknown_parts.entry(p.fourcc.clone()).or_default() += 1; + } } - drop(g); if !dumps_enabled(stage, h) { let names: Vec<&str> = parts.iter().map(|p| p.fourcc.as_str()).collect(); crate::xlog_info!("[SHADER] {stage} {h:016x}: {} B, format {}, parts [{}]", blob.len(), kind.label(), names.join(",")); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 8354827920..25c5d5c0b6 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -315,11 +315,11 @@ fn clear_dynamic_depth_bias(d: &mut [u8; GFX_DESC]) { struct GfxDesc([u8; GFX_DESC]); /// A title graphics pipeline's description, kept for CreateDerivedPipelineStateX and the -/// patched-PSO fallback of RSSetDepthBiasX. The input layout is copied; the shaders stay the -/// title's and are checked by hash when a pipeline is derived from it. +/// patched-PSO fallback of RSSetDepthBiasX. Both input layout and stage shader bytecodes are +/// owned copies so deriving succeeds even after the title frees or reuses its shader buffers. struct Base { desc: GfxDesc, - shaders: [u64; 5], + shader_blobs: [Option>; 5], /// Whether this PSO was created with `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS`. dynamic_depth_bias: bool, /// Original static `RasterizerState.{DepthBias, DepthBiasClamp, SlopeScaledDepthBias}`. @@ -328,10 +328,28 @@ struct Base { _names: Vec, } -// the desc points into `_elems` / `_names` and the title's shaders; nothing is mutated +// the desc points into `_elems` / `_names` and `shader_blobs` owns the bytecode; nothing is mutated unsafe impl Send for Base {} unsafe impl Sync for Base {} +impl Base { + /// Clone the pipeline description with stage shader pointers bound to `self.shader_blobs` + /// (valid for the lifetime of `&self`). + fn desc_with_owned_shaders(&self) -> GfxDesc { + let mut d = self.desc; + for (k, &o) in STAGES.iter().enumerate() { + match &self.shader_blobs[k] { + Some(blob) => { + d.0[o..o + 8].copy_from_slice(&(blob.as_ptr() as u64).to_le_bytes()); + d.0[o + 8..o + 16].copy_from_slice(&(blob.len() as u64).to_le_bytes()); + } + None => d.0[o..o + 16].fill(0), + } + } + d + } +} + static BASES: Mutex>>> = Mutex::new(None); /// Cached derived PSOs for `RSSetDepthBiasX`: (base PSO, override) → owned derived PSO. /// Released when the base PSO is released in `forget_base`. @@ -345,19 +363,19 @@ fn rd64(d: &[u8], o: usize) -> u64 { u64::from_le_bytes(d[o..o + 8].try_into().unwrap()) } -/// hash of each stage's bytecode (0: none); None when one is not readable -unsafe fn stage_hashes(d: &[u8; GFX_DESC]) -> Option<[u64; 5]> { - let mut h = [0; 5]; +/// Copy each non-empty stage's shader bytecode into an owned buffer; None when one is not readable. +unsafe fn stage_blobs(d: &[u8; GFX_DESC]) -> Option<[Option>; 5]> { + let mut blobs: [Option>; 5] = Default::default(); for (k, &o) in STAGES.iter().enumerate() { let (p, n) = (rd64(d, o) as usize, rd64(d, o + 8) as usize); if p != 0 && n != 0 { if !crate::gpu::shader::readable(p, n) { return None; } - h[k] = crate::gpu::shader::fnv64(std::slice::from_raw_parts(p as *const u8, n)); + blobs[k] = Some(std::slice::from_raw_parts(p as *const u8, n).to_vec().into_boxed_slice()); } } - Some(h) + Some(blobs) } /// Remember a title graphics pipeline's description (not with stream output). @@ -369,7 +387,10 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b if rd32(&d.0, SO_ENTRIES) != 0 { return; } - let Some(shaders) = stage_hashes(&d.0) else { return }; + let Some(shader_blobs) = stage_blobs(&d.0) else { return }; + for &o in &STAGES { + d.0[o..o + 16].fill(0); + } let static_bias = DepthBias::from_desc(&d.0); let (p, n) = (rd64(&d.0, INPUT_LAYOUT) as usize, rd32(&d.0, INPUT_LAYOUT + 8) as usize); let (mut elems, mut names) = (Vec::new(), Vec::new()); @@ -390,7 +411,7 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b let at = if elems.is_empty() { 0 } else { elems.as_ptr() as u64 }; d.0[INPUT_LAYOUT..INPUT_LAYOUT + 8].copy_from_slice(&at.to_le_bytes()); d.0[CACHED_PSO..CACHED_PSO + 16].fill(0); - let base = Arc::new(Base { desc: d, shaders, dynamic_depth_bias, static_bias, _elems: elems, _names: names }); + let base = Arc::new(Base { desc: d, shader_blobs, dynamic_depth_bias, static_bias, _elems: elems, _names: names }); BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, base); } @@ -411,7 +432,7 @@ pub(super) fn depth_bias_cache_len() -> usize { pub(super) fn register_test_base(pso: usize, dynamic_depth_bias: bool, static_bias: DepthBias) { let base = Arc::new(Base { desc: GfxDesc([0u8; GFX_DESC]), - shaders: [0; 5], + shader_blobs: Default::default(), dynamic_depth_bias, static_bias, _elems: Vec::new(), @@ -461,13 +482,7 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi return Some(cached); } let b = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&base).cloned())?; - if stage_hashes(&b.desc.0) != Some(b.shaders) { - if once(&N, 4) { - crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – shaders of base pipeline {base:#x} are gone"); - } - return None; - } - let mut d = b.desc; + let mut d = b.desc_with_owned_shaders(); clear_dynamic_depth_bias(&mut d.0); bias.patch_desc(&mut d.0); let mut out: *mut c_void = std::ptr::null_mut(); @@ -541,17 +556,11 @@ pub(super) unsafe extern "system" fn create_derived_pso_x(this: *mut c_void, bas } return E_FAIL; }; - if stage_hashes(&b.desc.0) != Some(b.shaders) { - if once(&N, 4) { - crate::xlog_warn!("D3D12.X: CreateDerivedPipelineStateX – the shaders of base pipeline {base:?} are gone"); - } - return E_FAIL; - } let n = count as usize; if n > 64 || (n > 0 && (patches.is_null() || !crate::gpu::shader::readable(patches as usize, n * PATCH))) { return E_INVALIDARG; } - let mut d = b.desc; + let mut d = b.desc_with_owned_shaders(); for i in 0..n { let patch = &*(patches.add(i * PATCH) as *const [u8; PATCH]); match apply_patch(&mut d.0, patch) { @@ -1833,4 +1842,34 @@ mod tests { m.remove(&((luid.LowPart, luid.HighPart), 24)); } } + + #[test] + fn base_pso_retains_shader_bytecode_after_title_buffer_changes() { + let mut vs = vec![0x44u8, 0x58, 0x42, 0x43, 1, 2, 3, 4]; + let mut ps = vec![0x44u8, 0x58, 0x42, 0x43, 9, 8, 7, 6, 5]; + let orig_vs = vs.clone(); + let orig_ps = ps.clone(); + let mut raw = GfxDesc([0u8; GFX_DESC]); + raw.0[STAGES[0]..STAGES[0] + 8].copy_from_slice(&(vs.as_ptr() as u64).to_le_bytes()); + raw.0[STAGES[0] + 8..STAGES[0] + 16].copy_from_slice(&(vs.len() as u64).to_le_bytes()); + raw.0[STAGES[1]..STAGES[1] + 8].copy_from_slice(&(ps.as_ptr() as u64).to_le_bytes()); + raw.0[STAGES[1] + 8..STAGES[1] + 16].copy_from_slice(&(ps.len() as u64).to_le_bytes()); + let pso_key = 0xDEAD_BEEF_0001usize; + unsafe { + note_base(pso_key as *mut c_void, raw.0.as_ptr() as *const c_void, false); + } + // Overwrite and drop the title's original shader buffers. + vs.fill(0xAA); + ps.fill(0xBB); + drop(vs); + drop(ps); + let base = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&pso_key).cloned()).expect("base PSO recorded"); + let derived = base.desc_with_owned_shaders(); + let (vp, vn) = (rd64(&derived.0, STAGES[0]) as *const u8, rd64(&derived.0, STAGES[0] + 8) as usize); + let (pp, pn) = (rd64(&derived.0, STAGES[1]) as *const u8, rd64(&derived.0, STAGES[1] + 8) as usize); + assert_eq!(unsafe { std::slice::from_raw_parts(vp, vn) }, orig_vs.as_slice()); + assert_eq!(unsafe { std::slice::from_raw_parts(pp, pn) }, orig_ps.as_slice()); + assert_eq!(rd64(&derived.0, STAGES[2]), 0); + forget_base(pso_key); + } } diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index 61fbd6033a..eaba05ae23 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -84,7 +84,7 @@ pub fn interval_valid(len_us: u32, high_refresh: bool) -> bool { if near(8333, 9) || near(25000, 25) { return high_refresh; } - near(16667, 16) || near(33333, 34) || near(50000, 49) || near(66667, 67) + near(16667, 16) || near(33333, 34) || near(41667, 42) || near(50000, 49) || near(66667, 67) } /// The first deadline `base + offset + k·interval` after `after`. @@ -721,5 +721,14 @@ mod tests { assert_eq!(set_frame_interval_x(dev, std::ptr::null_mut(), 0, 0, 0), S_FALSE, "stops the clock"); } } + + #[test] + fn interval_valid_accepts_24hz() { + assert!(interval_valid(41667, false)); + assert!(interval_valid(41666, false)); + assert!(interval_valid(16667, false)); + assert!(!interval_valid(8333, false)); + assert!(interval_valid(8333, true)); + } } diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index bffbce31dc..932f853adf 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1126,6 +1126,11 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D } } +/// True when `uv` covers a strict sub-rectangle of the source plane (e.g. dynamic resolution). +fn uv_is_subrect(uv: [f32; 4]) -> bool { + uv != [0.0, 0.0, 1.0, 1.0] +} + unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, Option<[i32; 4]>)>)>) { if IN_PRESENT.with(|c| c.replace(true)) { return; @@ -1257,7 +1262,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, } } let mut composited = false; - if resolved.len() > 1 { + if resolved.len() > 1 || uv_is_subrect(resolved[0].2) { if p.compositor.is_none() { p.compositor = Compositor::new(&p.dev); } @@ -1888,7 +1893,9 @@ mod tests { let got = unsafe { extract_planes(2, buf.as_ptr()) }; assert_eq!(got, vec![(res0, Some(rect0)), (res1, None)]); assert_eq!(source_uv_rect(got[0].1, 1600, 900), [0.1, 0.1, 0.5, 0.5]); + assert!(uv_is_subrect(source_uv_rect(got[0].1, 1600, 900))); assert_eq!(source_uv_rect(got[1].1, 3840, 2160), [0.0, 0.0, 1.0, 1.0]); + assert!(!uv_is_subrect(source_uv_rect(got[1].1, 3840, 2160))); assert_eq!(source_uv_rect(Some([0, 0, 4000, 900]), 1920, 1080), [0.0, 0.0, 1.0, 1.0]); } } From a46703b61ce7530930429f582b49906a47cf4cc4 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:21:59 +0100 Subject: [PATCH 018/175] D3D12.X: avoid depth_uav stencil subresource underflow and align bvh_words test --- crates/xcl/src/gpu/desc.rs | 2 +- crates/xcl/src/hle/d3d12x/depth_uav.rs | 2 +- tests/testtitle/src/gpu.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/desc.rs b/crates/xcl/src/gpu/desc.rs index 3eecc10c99..b0c2202dc8 100644 --- a/crates/xcl/src/gpu/desc.rs +++ b/crates/xcl/src/gpu/desc.rs @@ -665,7 +665,7 @@ mod view_tests { assert_eq!((v.address, v.stride, v.num_records, v.format, v.dst_sel), (0x5_1234_5670, 16, 100, 77, [4, 5, 6, 7])); assert_eq!((format_bytes(22), format_bytes(29), format_bytes(71), format_bytes(77)), (4, 4, 8, 16)); let b = bvh_words(0x12_3456_789A_00, true); - assert_eq!(b, [0x3456_789A, 0x8000_0012, u32::MAX, 0]); + assert_eq!(b, [0x3456_789A, 0x8000_0012, u32::MAX, 1 << 24]); assert!(b[3] >> 28 < 8, "BVH descriptor must not look like a T# image to CopyDescriptors"); assert_eq!(bvh_words(0x12_3456_789A_00, false)[1], 0x12); } diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index f3b6100532..88fca6a5e1 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -562,7 +562,7 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, // given one: what they store there (a title's masks for its lighting) reaches the plane // on the way out of UNORDERED_ACCESS, and what was drawn into the plane reaches the twin // on the way in - let stencil_subs: Vec = if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { (0..n).collect() } else { (sub >= n && sub < 2 * n).then_some(sub - n).into_iter().collect() }; + let stencil_subs: Vec = if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { (0..n).collect() } else { (sub >= n && sub < 2 * n).then(|| sub - n).into_iter().collect() }; let stencil = (direct && !stencil_subs.is_empty() && matches!(key.format, 19 | 44)).then(|| stencil_twin_if_made(&o)).flatten().map(|(twin, through)| StencilCopy { depth: res, subs: stencil_subs, diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index 238ed482cf..59c87c3d36 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -628,7 +628,7 @@ pub fn raytracing_surface() -> Result<(), String> { }; dev.CreateShaderResourceView(None, Some(&srv), cpu); let words = std::slice::from_raw_parts(cpu.ptr as *const u32, 4); - let expected = [(tlas_va >> 8) as u32, (((tlas_va >> 40) as u32) & 0xFF) | (1 << 31), u32::MAX, 0]; + let expected = [(tlas_va >> 8) as u32, (((tlas_va >> 40) as u32) & 0xFF) | (1 << 31), u32::MAX, 1 << 24]; ensure!(words == expected, "AS SRV slot {words:x?} != expected {expected:x?}"); crate::XMemFree(tlas, graphics); From 60345c9707565437aea8fb83d8e2948100f18452 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:37:55 +0100 Subject: [PATCH 019/175] D3D12.X: deduplicate retained base PSO shader bytecodes with a shared Arc pool --- crates/xcl/src/hle/d3d12x/device_x.rs | 69 +++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 25c5d5c0b6..e8bb4f54a7 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -315,11 +315,13 @@ fn clear_dynamic_depth_bias(d: &mut [u8; GFX_DESC]) { struct GfxDesc([u8; GFX_DESC]); /// A title graphics pipeline's description, kept for CreateDerivedPipelineStateX and the -/// patched-PSO fallback of RSSetDepthBiasX. Both input layout and stage shader bytecodes are -/// owned copies so deriving succeeds even after the title frees or reuses its shader buffers. +/// patched-PSO fallback of RSSetDepthBiasX. Input layout is copied and stage shader bytecodes are +/// interned into a shared pool (`Arc<[u8]>`) so tens of thousands of PSOs sharing a few thousand +/// unique shaders hold only one copy per unique shader and stay valid after the title frees its +/// original bytecode buffers. struct Base { desc: GfxDesc, - shader_blobs: [Option>; 5], + shader_blobs: [Option>; 5], /// Whether this PSO was created with `D3D12_PIPELINE_STATE_FLAG_DYNAMIC_DEPTH_BIAS`. dynamic_depth_bias: bool, /// Original static `RasterizerState.{DepthBias, DepthBiasClamp, SlopeScaledDepthBias}`. @@ -328,7 +330,7 @@ struct Base { _names: Vec, } -// the desc points into `_elems` / `_names` and `shader_blobs` owns the bytecode; nothing is mutated +// the desc points into `_elems` / `_names` and `shader_blobs` owns shared bytecode; nothing is mutated unsafe impl Send for Base {} unsafe impl Sync for Base {} @@ -350,7 +352,14 @@ impl Base { } } +struct ShaderPool { + map: HashMap<(u64, usize), std::sync::Weak<[u8]>>, + next_sweep: usize, +} + static BASES: Mutex>>> = Mutex::new(None); +/// Deduplicated shader bytecode pool shared across tracked `Base` graphics PSOs. +static BASE_SHADERS: Mutex> = Mutex::new(None); /// Cached derived PSOs for `RSSetDepthBiasX`: (base PSO, override) → owned derived PSO. /// Released when the base PSO is released in `forget_base`. static DEPTH_BIAS_PSOS: Mutex>> = Mutex::new(None); @@ -363,16 +372,44 @@ fn rd64(d: &[u8], o: usize) -> u64 { u64::from_le_bytes(d[o..o + 8].try_into().unwrap()) } -/// Copy each non-empty stage's shader bytecode into an owned buffer; None when one is not readable. -unsafe fn stage_blobs(d: &[u8; GFX_DESC]) -> Option<[Option>; 5]> { - let mut blobs: [Option>; 5] = Default::default(); +/// Intern `bytes` into `BASE_SHADERS` by `(fnv64, len)`, avoiding duplicate copies across PSOs. +fn intern_shader_blob(bytes: &[u8]) -> Arc<[u8]> { + let key = (crate::gpu::shader::fnv64(bytes), bytes.len()); + let candidate = { + let g = BASE_SHADERS.lock().unwrap(); + g.as_ref().and_then(|p| p.map.get(&key)).and_then(std::sync::Weak::upgrade) + }; + if let Some(existing) = candidate { + if &*existing == bytes { + return existing; + } + } + let arc: Arc<[u8]> = Arc::from(bytes); + let mut g = BASE_SHADERS.lock().unwrap(); + let pool = g.get_or_insert_with(|| ShaderPool { map: HashMap::new(), next_sweep: 8192 }); + if let Some(existing) = pool.map.get(&key).and_then(std::sync::Weak::upgrade) { + if &*existing == bytes { + return existing; + } + } + if pool.map.len() >= pool.next_sweep { + pool.map.retain(|_, w| w.strong_count() > 0); + pool.next_sweep = (pool.map.len().saturating_mul(2)).max(8192); + } + pool.map.insert(key, Arc::downgrade(&arc)); + arc +} + +/// Intern each non-empty stage's shader bytecode; None when one is not readable. +unsafe fn stage_blobs(d: &[u8; GFX_DESC]) -> Option<[Option>; 5]> { + let mut blobs: [Option>; 5] = Default::default(); for (k, &o) in STAGES.iter().enumerate() { let (p, n) = (rd64(d, o) as usize, rd64(d, o + 8) as usize); if p != 0 && n != 0 { if !crate::gpu::shader::readable(p, n) { return None; } - blobs[k] = Some(std::slice::from_raw_parts(p as *const u8, n).to_vec().into_boxed_slice()); + blobs[k] = Some(intern_shader_blob(std::slice::from_raw_parts(p as *const u8, n))); } } Some(blobs) @@ -1855,21 +1892,35 @@ mod tests { raw.0[STAGES[1]..STAGES[1] + 8].copy_from_slice(&(ps.as_ptr() as u64).to_le_bytes()); raw.0[STAGES[1] + 8..STAGES[1] + 16].copy_from_slice(&(ps.len() as u64).to_le_bytes()); let pso_key = 0xDEAD_BEEF_0001usize; + let pso_key2 = 0xDEAD_BEEF_0002usize; unsafe { note_base(pso_key as *mut c_void, raw.0.as_ptr() as *const c_void, false); + note_base(pso_key2 as *mut c_void, raw.0.as_ptr() as *const c_void, false); } // Overwrite and drop the title's original shader buffers. vs.fill(0xAA); ps.fill(0xBB); drop(vs); drop(ps); - let base = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&pso_key).cloned()).expect("base PSO recorded"); + let (base, base2) = { + let g = BASES.lock().unwrap(); + let m = g.as_ref().expect("base map"); + (m.get(&pso_key).cloned().expect("base PSO recorded"), m.get(&pso_key2).cloned().expect("second base PSO recorded")) + }; + assert!(Arc::ptr_eq(base.shader_blobs[0].as_ref().unwrap(), base2.shader_blobs[0].as_ref().unwrap())); + assert!(Arc::ptr_eq(base.shader_blobs[1].as_ref().unwrap(), base2.shader_blobs[1].as_ref().unwrap())); let derived = base.desc_with_owned_shaders(); let (vp, vn) = (rd64(&derived.0, STAGES[0]) as *const u8, rd64(&derived.0, STAGES[0] + 8) as usize); let (pp, pn) = (rd64(&derived.0, STAGES[1]) as *const u8, rd64(&derived.0, STAGES[1] + 8) as usize); assert_eq!(unsafe { std::slice::from_raw_parts(vp, vn) }, orig_vs.as_slice()); assert_eq!(unsafe { std::slice::from_raw_parts(pp, pn) }, orig_ps.as_slice()); assert_eq!(rd64(&derived.0, STAGES[2]), 0); + let weak_vs = Arc::downgrade(base.shader_blobs[0].as_ref().unwrap()); + drop(base); + drop(base2); forget_base(pso_key); + assert!(weak_vs.upgrade().is_some(), "shared blob stays alive while second PSO holds it"); + forget_base(pso_key2); + assert!(weak_vs.upgrade().is_none(), "shared blob drops once all owning PSOs are released"); } } From f2962ee182d3df19ad28e5696a6967dc7e38bd98 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:15:49 -0500 Subject: [PATCH 020/175] D3D12.X: segments parked as spares stop holding their PC allocator A title list's extra segments (mid-list splits) are parked as spares at the list's next Reset, and the segments KickoffX takes back become spares too. A spare records again only after its own later Reset, but alloc_pool still counted it as a user of the PC allocator it last recorded on, so that allocator was never free: each later Reset of the title's allocator while those were "in use" put another PC allocator aside, and none was ever reused or released. The previous recording a stand-in replaces at Reset pinned its allocator the same way. alloc_pool::park_list drops the list from its allocator's users (its submit marks stay, so the allocator is reused only once the GPU is past them). title_list::reset parks the moved segments and the replaced recording; KickoffX parks its reclaimed segments after both submits. Measured on the title (RTX 5070 Ti, Series X profile, 240 s untimed runs, object counts from 100 to 240 s): PC allocators 1,137 -> 1,928 without, 728-753 -> 862-897 with; non-local video memory 6.2 -> 9.6 GB without, 5.0 -> 5.4-5.5 GB with (about 4 GB less at 240 s). Timed pairs showed no frame-rate cost (late window 11.99 / 10.76 fps without, 10.76 / 11.76 with; run-to-run spread ~10 %). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit bf42a6ee003cca247c436b8e7e730cba27e934b8) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 31 +++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/list_x.rs | 3 +++ crates/xcl/src/hle/d3d12x/title_list.rs | 7 ++++++ 3 files changed, 41 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 5ade3d8775..1a074ded1b 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -126,6 +126,19 @@ fn unpin(s: &mut State, list: usize) { } } +/// `list` (a closed segment) is parked as a spare: its recording is over and it is reset before +/// it records again, so it no longer holds its allocator. Its last submit stays (`in_flight`) +/// and the allocator's own submit marks still keep it until the GPU is past them. +pub(super) fn park_list(list: usize) { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if let Some(backing) = s.of_list.remove(&list) { + if let Some(b) = s.backings.get_mut(&backing) { + b.users.remove(&list); + } + } +} + /// Reset `list` on the title's allocator `alloc`, committing its new recording association /// only after native Reset succeeds. No pool lock is held across the driver call. pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { @@ -700,6 +713,24 @@ mod tests { assert!(s.backings[&other].users.contains(&elsewhere)); } + /// A parked spare stops holding its allocator: once nothing else records on it and no submit + /// is pending, the allocator is free again. + #[test] + fn a_parked_spare_no_longer_holds_its_allocator() { + let mut ids = Box::new([0u8; 2]); + let alloc = ids.as_mut_ptr() as usize; + let spare = alloc + 1; + created_on(spare, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let held = |l: usize| STATE.lock().unwrap().as_ref().unwrap().backings[&alloc].users.contains(&l); + assert!(held(spare), "the new list records on the allocator"); + park_list(spare); + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.of_list.contains_key(&spare) && unsafe { s.backings[&alloc].free() }, "a parked spare must not pin the allocator"); + drop(g); + ids[0] = 0; + } + #[test] fn a_spare_whose_reset_fails_stays_available_for_retry() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 343fe5cf27..1116f8383d 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4083,6 +4083,9 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { for seg in reclaimed { super::bind::reset(seg as *mut c_void, 0, 0); clear_segment_state(seg); + // a spare now: it does not hold its allocator until it records again (after both + // submits above, so the allocator keeps their marks) + super::alloc_pool::park_list(seg); } if let Some(s) = recording(primary as usize).lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { s.allocator = alloc; diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 2eef4403a4..28f7b84d74 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -196,6 +196,13 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); super::list_x::clear_segment_state(seg); + // a spare records again only after its next Reset: it does not hold its + // allocator meanwhile + super::alloc_pool::park_list(seg); + } + // nor does the previous recording a stand-in now replaces: it is not reset here either + if stand_in.is_some() { + super::alloc_pool::park_list(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; From e91a788f65a786d085339ca9fc01a04bd2d35ce0 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:26:31 -0500 Subject: [PATCH 021/175] D3D12.X: XCL_SMALL_TEXTURES=1 puts small sampled textures on 4 KiB placements A sampled texture the shared 64 KiB pages do not take (vram::place_pages refuses it; a 1D texture cannot be a reserved resource) was a committed resource, which takes at least 64 KiB of video memory. On the title the committed fallback held 8,361 x 64 KiB = 523 MiB (XCL_COMMITTED_AUDIT), mostly ~5k Texture1D RGBA8_SRGB textures of 4 KiB or less. With the switch, such a texture goes on a 4 KiB placement in a 4 MiB DEFAULT heap of XCL's own (ALLOW_ONLY_NON_RT_DS_TEXTURES), made through the adopting CreatePlacedResource. Only when the PC allows it: no RT/DS/UAV flags, one sample, and GetResourceAllocationInfo returning 4 KiB alignment for the description asking for it (most detailed level within 64 KiB). Otherwise, and when no heap can take it, it is committed as before. Its units are free again where late_release lets its last reference go (the queues are past the work before it); with XCL_LATE_RELEASE=0 the switch does nothing (logged once), as uploads of XCL's into a texture could still be in flight at the title's release. XCL asks no residency priority for the heaps, as for a committed texture (logged per heap). Measured on the title (RTX 5070 Ti, one 480 s run per arm, same base and env, with and without the switch): 8,192 small textures live in 58 MiB of 15 heaps, against at least 512 MiB as committed resources; local video memory over 250-310 s 18,332 vs 18,793 MB (-461 MB) with equal sparse pools and target pages. Still 3.1 GB over the budget there, and the frame rate did not move. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 24fdb7b9297e47af1433a7c1069436becfe7a724) --- crates/xcl/src/hle/d3d12x/device_x.rs | 6 +- crates/xcl/src/hle/d3d12x/late_release.rs | 1 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 1 + crates/xcl/src/hle/d3d12x/small_tex.rs | 247 ++++++++++++++++++++++ 5 files changed, 254 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/small_tex.rs diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index e8bb4f54a7..d4298900f2 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1215,7 +1215,9 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, placed_hr = super::vram::place_pages(this, va as usize, &pc, state, clear, console_bytes, riid, ppv); } } - let hr = match placed_hr { + // (a small one the shared pages do not take: on a 4 KiB placement, `XCL_SMALL_TEXTURES=1`) + let small_hr = if placed_hr.is_none() && !buffer { super::small_tex::place(this, &std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC), state, clear, riid, ppv) } else { None }; + let hr = match placed_hr.or(small_hr) { Some(hr) => hr, None => { let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; @@ -1231,7 +1233,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, Ok(()) => { real::note_title_address(*ppv as usize, va as usize); super::depth_uav::note_created(*ppv, &x, Some(va as usize), state); - super::lut3d::created(if placed_hr.is_some() { "CreatePlacedResourceX (sampled: on shared pages)" } else { "CreatePlacedResourceX (sampled: committed)" }, *ppv, Some(&x), Some(va as usize), true, state); + super::lut3d::created(if placed_hr.is_some() { "CreatePlacedResourceX (sampled: on shared pages)" } else if small_hr.is_some() { "CreatePlacedResourceX (sampled: 4 KiB placement)" } else { "CreatePlacedResourceX (sampled: committed)" }, *ppv, Some(&x), Some(va as usize), true, state); return hr; } Err(e) if once(&M, 4) => { diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 3323175647..a37d72b75e 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -263,6 +263,7 @@ pub unsafe fn drain_known(seal_now: bool) { // lock of this module's and does not wait for the sparse state's.) super::sparse::forget_buffer(res); super::placements::gone(res); + super::small_tex::gone(res); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res as *mut c_void, 2)); f(res as *mut c_void); } diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index c5e01c8b57..0bbb11aca7 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -46,6 +46,7 @@ pub mod real; mod scatter; mod shader_cache_session; mod sharded; +mod small_tex; pub mod sparse; mod standin; mod targets; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e76efee194..e4f7a3e82f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2144,6 +2144,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { // (a held one is gone when `late_release` lets it go) if !held { super::placements::gone(this as usize); + super::small_tex::gone(this as usize); } super::depth_uav::forget(this as usize); super::barrier_groups::forget(this as usize); diff --git a/crates/xcl/src/hle/d3d12x/small_tex.rs b/crates/xcl/src/hle/d3d12x/small_tex.rs new file mode 100644 index 0000000000..0a2ba2a855 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/small_tex.rs @@ -0,0 +1,247 @@ +//! Small sampled textures of the title that get no shared pages (`vram::place_pages` refuses them: +//! a 1D texture cannot be a reserved resource) on 4 KiB placements in heaps of XCL's own +//! (`XCL_SMALL_TEXTURES=1`), instead of a committed resource each: a committed resource takes at +//! least 64 KiB of video memory, and a title's thousands of tiny lookup textures (a few hundred +//! bytes each) took ~300 MiB that way. +//! +//! Only what the PC itself allows: no render target, depth or UAV flags, one sample, and +//! `GetResourceAllocationInfo` giving `D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT` (4 KiB) for the +//! description asking for it (its most detailed level fits in 64 KiB). Anything else, and a +//! texture the heaps here cannot take, is made committed as before. +//! +//! A texture's units are free again once its last reference goes (`gone`, where `late_release` +//! lets it go: the queues are past the work submitted before; with `XCL_LATE_RELEASE=0` nothing +//! is placed here). The heaps stay (4 MiB each). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::util::HRESULT; + +/// a placement unit: the small-resource alignment +const UNIT: u64 = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64; +/// one heap of XCL's own +const HEAP_BYTES: u64 = 4 << 20; +const UNITS: usize = (HEAP_BYTES / UNIT) as usize; + +/// Whether small sampled textures go on 4 KiB placements (`XCL_SMALL_TEXTURES=1`). +pub(super) fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SMALL_TEXTURES").is_ok_and(|v| v.trim() == "1")) +} + +/// The units of one heap: first fit of a run of `n`. +struct Units(Vec); + +impl Units { + fn new() -> Self { + Units(vec![false; UNITS]) + } + + fn take(&mut self, n: usize) -> Option { + let mut run = 0; + for i in 0..self.0.len() { + run = if self.0[i] { 0 } else { run + 1 }; + if run == n { + let first = i + 1 - n; + self.0[first..=i].iter_mut().for_each(|u| *u = true); + return Some(first); + } + } + None + } + + fn give(&mut self, first: usize, n: usize) { + self.0[first..first + n].iter_mut().for_each(|u| *u = false); + } +} + +struct Pool { + /// the device the heaps are of + dev: usize, + heaps: Vec<(ID3D12Heap, Units)>, + /// live texture → (heap, first unit, units) + live: HashMap, + units_live: usize, +} + +static POOL: Mutex> = Mutex::new(None); + +/// The units `desc` takes on a 4 KiB placement, or None when the PC does not place it so. +pub(super) unsafe fn units_for(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> Option { + let shut = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || desc.Dimension == D3D12_RESOURCE_DIMENSION_UNKNOWN || (desc.Flags & shut).0 != 0 || desc.SampleDesc.Count != 1 { + return None; + } + let mut small = *desc; + small.Alignment = UNIT; + let info = dev.GetResourceAllocationInfo(0, &[small]); + (info.Alignment == UNIT && info.SizeInBytes != u64::MAX && info.SizeInBytes > 0 && info.SizeInBytes <= D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64) + .then(|| info.SizeInBytes.div_ceil(UNIT) as usize) +} + +/// A sampled texture `desc` on a 4 KiB placement in a heap of XCL's own (device `this`), made as +/// `CreatePlacedResource` (adopted as any resource); None when it is not placed so (the caller makes +/// it committed). +pub(super) unsafe fn place(this: *mut c_void, desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option { + // (with `XCL_LATE_RELEASE=0` a texture's units would be free at the title's release, while an + // upload of XCL's into it can still be in flight: committed then) + if !enabled() { + return None; + } + if !super::late_release::enabled() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: XCL_SMALL_TEXTURES=1 does nothing with XCL_LATE_RELEASE=0: small textures stay committed")); + return None; + } + let dev = ID3D12Device::from_raw_borrowed(&this)?; + let n = units_for(dev, desc)?; + let mut small = *desc; + small.Alignment = UNIT; + // the units first (the heap stays while the pool does); the resource is made outside the lock + let (heap_raw, heap_index, first) = { + let mut g = POOL.lock().unwrap(); + let pool = g.get_or_insert_with(|| Pool { dev: this as usize, heaps: Vec::new(), live: HashMap::new(), units_live: 0 }); + if pool.dev != this as usize { + return None; + } + let found = pool.heaps.iter_mut().enumerate().find_map(|(k, (h, u))| u.take(n).map(|first| (h.as_raw() as usize, k, first))); + match found { + Some(f) => f, + None => { + let hd = D3D12_HEAP_DESC { + SizeInBytes: HEAP_BYTES, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option = None; + if dev.CreateHeap(&hd, &mut heap).is_err() { + return None; + } + let heap = heap?; + let mut units = Units::new(); + let first = units.take(n)?; + let raw = heap.as_raw() as usize; + pool.heaps.push((heap, units)); + let k = pool.heaps.len(); + if k <= 4 || k.is_power_of_two() { + // (XCL asks no residency priority for these heaps or for a committed texture, + // with or without XCL_VRAM_HOT_PRIORITY) + crate::xlog_info!("D3D12.X: small textures: heap {k} of 4 MiB made, residency priority: default, no override (as for a committed texture)"); + } + (raw, k - 1, first) + } + } + }; + let hr = super::real::dev_create_placed_resource(this, heap_raw, first * UNIT as usize, &small as *const _ as usize, state as usize, clear as usize, riid, ppv); + let mut g = POOL.lock().unwrap(); + let pool = g.as_mut().unwrap(); + if hr < 0 || (*ppv).is_null() { + pool.heaps[heap_index].1.give(first, n); + static FAILED: AtomicU64 = AtomicU64::new(0); + if FAILED.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: a small texture's 4 KiB placement failed ({hr:#x}); it is made committed"); + } + return None; + } + pool.live.insert(*ppv as usize, (heap_index, first, n)); + pool.units_live += n; + static PLACED: AtomicU64 = AtomicU64::new(0); + let k = PLACED.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() && k >= 64 { + crate::xlog_info!( + "D3D12.X: {k} small textures on 4 KiB placements so far; {} live in {} KiB of {} heaps of 4 MiB (committed: at least {} KiB)", + pool.live.len(), + pool.units_live * UNIT as usize >> 10, + pool.heaps.len(), + pool.live.len() * 64 + ); + } + Some(hr) +} + +/// The texture `res` is destroyed next: its units are free. +pub(super) fn gone(res: usize) { + if !enabled() { + return; + } + let mut g = POOL.lock().unwrap(); + if let Some(pool) = g.as_mut() { + if let Some((k, first, n)) = pool.live.remove(&res) { + pool.heaps[k].1.give(first, n); + pool.units_live -= n; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_SAMPLE_DESC}; + + /// Units go first fit and come back: a freed run is taken again, a run longer than any gap is not. + #[test] + fn units_are_taken_first_fit_and_given_back() { + let mut u = Units::new(); + assert_eq!(u.take(1), Some(0)); + assert_eq!(u.take(4), Some(1)); + assert_eq!(u.take(1), Some(5)); + u.give(1, 4); + assert_eq!(u.take(2), Some(1)); + assert_eq!(u.take(3), Some(6), "the 2-unit gap left at 3 is too small"); + assert_eq!(u.take(2), Some(3)); + let mut full = Units::new(); + assert_eq!(full.take(UNITS), Some(0)); + assert_eq!(full.take(1), None); + full.give(UNITS - 2, 2); + assert_eq!(full.take(3), None); + assert_eq!(full.take(2), Some(UNITS - 2)); + } + + fn tex(dim: D3D12_RESOURCE_DIMENSION, w: u64, h: u32, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: dim, + Alignment: 0, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + } + } + + /// The PC's rules decide: a tiny 1D or 2D sampled texture is placed on 4 KiB, a render target + /// or a texture over 64 KiB is not, and a buffer is never. + #[test] + fn only_textures_the_pc_places_on_4_kib_are_taken() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + } + let dev = dev.unwrap(); + unsafe { + // 256 texels of RGBA8: 1 KiB of texels, on a 4 KiB placement of the driver's size (8 KiB + // on an RTX 5070 Ti with driver 610.74) + let n = units_for(&dev, &tex(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 256, 1, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOURCE_FLAG_NONE)); + assert!(n.is_some_and(|n| (1..=16).contains(&n)), "{n:?}"); + // 64x64 RGBA8: 16 KiB + let n = units_for(&dev, &tex(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)); + assert!(n.is_some_and(|n| (4..=16).contains(&n)), "{n:?}"); + assert_eq!(units_for(&dev, &tex(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)), None); + assert_eq!(units_for(&dev, &tex(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 512, 512, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE)), None); + let mut buf = tex(D3D12_RESOURCE_DIMENSION_BUFFER, 4096, 1, windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE); + buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + assert_eq!(units_for(&dev, &buf), None); + } + } +} From 87e900b89ed6c443a263ff1b50a8c2fe3b9d68ad Mon Sep 17 00:00:00 2001 From: Prime1997 Date: Sat, 28 Nov 2026 03:48:08 -0800 Subject: [PATCH 022/175] Memory: defer private physical-home GPU tiles on NVIDIA NVIDIA adaptation of CallMeBrado's xcl-dev/xcl#1916 at e2aa856010a637d33adc2cf8b49766da91574747. Keep storage-only homes CPU-backed until explicitly mapped, then replay preserved bytes even when ordinary storage write hints are disabled. Based directly on nvidia-dev 54225f588, without the separate physical-page liveness, alias-identity or owner-sampler integration. Preserves NVIDIA's existing free/title mapping behavior. Prepared from integration abc027544; source-reviewed independently. Added fixtures are unrun, no native or build results claimed. Assisted-by: Codex (GPT-6) (cherry picked from commit 6330fba1f3d2cfcfebef82d3032b38639f0b175e) --- README.md | 5 + crates/xcl/src/hle/d3d12x/sparse.rs | 61 ++++++++++ crates/xcl/src/hle/d3d12x/title_textures.rs | 8 ++ crates/xcl/src/hle/kernelx.rs | 116 +++++++++++++++----- 4 files changed, 162 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 28391856ca..e2b00e9191 100644 --- a/README.md +++ b/README.md @@ -355,6 +355,11 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. fills into its GPU views) are applied: a GPU-view page shows the physical page mapped into it. `XCL_PAGE_MAPPINGS=0` turns them off (the call is ignored and a GPU-view page shows its CPU view at the same offset, as before). +- `XCL_DEFER_PRIVATE_HOME_TILES=1` keeps physical-page home storage used only by CPU/storage + transfers from acquiring a second sparse GPU copy. Explicit home mappings expose and upload + the existing bytes before the next submission, even after an earlier write-watch scan. + Already-exposed homes keep their normal behavior. Off by default; this reduces avoidable + backing, not the memory needed by live GPU mappings, and is not a VRAM budget cap. - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 6b0e8ac807..c0e41a43aa 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -4840,6 +4840,67 @@ fn forget_in(s: &mut State, res: usize) { mod tests { use super::*; + /// Adapted from CallMeBrado's #1916: consumed CPU writes still reach first GPU exposure. + #[test] + fn private_physical_pages_reach_the_gpu_on_mapping() { + const CHILD: &str = "XCL_TEST_PRIVATE_PHYSICAL_PAGES"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping", "--nocapture"]) + .env(CHILD, "1").env("XCL_DEFER_PRIVATE_HOME_TILES", "1") + .env("XCL_SPARSE_LAZY", "1").env("XCL_DS_KNOWN_WRITES", "0") + .output().unwrap(); + print!("{}", String::from_utf8_lossy(&output.stdout)); + eprint!("{}", String::from_utf8_lossy(&output.stderr)); + assert!(output.status.success()); + return; + } + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, write_physical_pages}; + unsafe { + let dev = test_device(); + if software(&dev) { + return crate::gpu::recomp::runner::skip_test("no hardware sparse adapter"); + } + let Some(u) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no UMA"); }; + if !u.has_sparse() { return crate::gpu::recomp::runner::skip_test("no sparse windows"); } + let windows = init(&dev); + if windows.is_empty() { return crate::gpu::recomp::runner::skip_test("no reserved sparse buffers"); } + for (_, raw, _) in windows { drop(ID3D12Resource::from_raw(raw as *mut c_void)); } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let mut pages = [0usize; 3]; + let mut n = pages.len(); + let null = std::ptr::null_mut(); + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let first = vec![0xa7; TILE]; + let last = vec![0x38; TILE]; + let before = mapped_ranges(); + assert!(write_physical_pages(&pages[..1], 0, &first)); + assert!(write_physical_pages(&pages[2..], 0, &last)); + super::super::title_textures::refresh(queue.as_raw()); + assert_eq!(mapped_ranges(), before, "storage-only homes acquired sparse GPU tiles"); + let first_home = MapTitlePhysicalPages(null, 1, 0, 4, pages.as_mut_ptr()); + assert!(!first_home.is_null()); + let home = MapTitlePhysicalPages(null, n, 0, 4, pages.as_mut_ptr()) as usize; + assert_eq!(home, first_home as usize); + assert!(mapped_ranges().iter().any(|&(a, b)| a <= home && home + n * TILE <= b)); + assert_eq!(windows_sys::Win32::System::Memory::ResetWriteWatch(home as *const c_void, n * TILE), 0); + super::super::title_textures::refresh(queue.as_raw()); + std::ptr::write_bytes(home as *mut u8, 0xdd, n * TILE); + readback_after_execute(&queue, &[(home, n * TILE)], &[]); + let started = std::time::Instant::now(); + while RB_PENDING.load(Ordering::Acquire) != 0 && started.elapsed().as_secs() < 5 { + settle_readbacks(); + std::thread::yield_now(); + } + assert_eq!(RB_PENDING.load(Ordering::Acquire), 0, "copy back did not finish"); + let result = std::slice::from_raw_parts(home as *const u8, n * TILE); + assert_eq!(&result[..TILE], &first); + assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0)); + assert_eq!(&result[2 * TILE..], &last); + assert_eq!(FreeTitlePhysicalPages(null, n, pages.as_mut_ptr()), 1); + } + } + thread_local! { /// The VirtualQuery calls `source_holes` made on this thread. pub(super) static VIRTUAL_QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 7eedaca0c6..18bad6a4b9 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1483,6 +1483,14 @@ unsafe fn walk() { /// the other (each block of them stayed hot for `hot_for`, and every look walked it). static KNOWN: Mutex> = Mutex::new(Vec::new()); +/// Newly GPU-visible backing must be scanned even if a prior look consumed its CPU writes. +/// Unlike an optional storage hint, this is required for the first upload after exposure. +pub(crate) fn rescan_cpu_backing(at: usize, len: usize) { + if len != 0 { + KNOWN.lock().unwrap().push((at, len)); + } +} + /// `XCL_DS_KNOWN_WRITES=0`: what DirectStorage writes is found by the write watch, as before. fn known_writes() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4ca45d807f..cef6aa9374 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1903,9 +1903,14 @@ static PHYS_BLOCKS: std::sync::Mutex, at: std::collections::BTreeMap, page: std::collections::HashMap, /// homes in a sparse window whose pages went away in this call, given back at its end in @@ -2042,7 +2047,7 @@ fn lazy_home(home: usize) -> bool { /// Resolve the live virtual addresses of the physical pages covering `offset..offset+len`. /// Caller must hold `AWAY`. -unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: usize, len: usize) -> Option> { +unsafe fn resolve_physical_pages(away: &mut Away, pages: &[usize], offset: usize, len: usize) -> Option> { if offset >= PHYS_PAGE { return None; } @@ -2054,9 +2059,9 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u let mut addrs = Vec::with_capacity(need); for &p in &pages[..need] { let home = page_home(p)?; - let addr = match away.and_then(|a| a.page.get(&p).copied()) { + let addr = match away.page.get(&p).copied() { Some(at) => at, - None => home_again(home)?, + None => home_again(home, p, away)?, }; addrs.push(addr); } @@ -2071,8 +2076,8 @@ pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8] if dst.is_empty() { return offset < PHYS_PAGE; } - let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, dst.len()) else { return false }; + let mut g = AWAY.lock().unwrap(); + let Some(addrs) = resolve_physical_pages(g.get_or_insert_with(Away::default), pages, offset, dst.len()) else { return false }; let mut done = 0; let mut page_off = offset; for addr in addrs { @@ -2091,8 +2096,8 @@ pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) - if src.is_empty() { return offset < PHYS_PAGE; } - let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, src.len()) else { return false }; + let mut g = AWAY.lock().unwrap(); + let Some(addrs) = resolve_physical_pages(g.get_or_insert_with(Away::default), pages, offset, src.len()) else { return false }; let mut done = 0; let mut page_off = offset; for addr in addrs { @@ -2185,14 +2190,29 @@ unsafe fn give_back_homes(away: &mut Away) { } } +fn defer_private_home_tiles() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DEFER_PRIVATE_HOME_TILES").is_ok_and(|v| v.trim() == "1")) +} + +/// Once its home was exposed, later recommits keep the existing GPU-visible behavior. +fn private_home(away: &mut Away, page: usize, enabled: bool) -> bool { + if enabled && away.sparse_homes.get(&page) != Some(&SparseHome::Exposed) { + away.sparse_homes.insert(page, SparseHome::CpuOnly); + true + } else { + false + } +} + /// The page's home, committed again if `move_home_away` gave it back (None: it could not be). -unsafe fn home_again(home: usize) -> Option { +unsafe fn home_again(home: usize, page: usize, away: &mut Away) -> Option { if lazy_home(home) && !committed_page(home) { if mem::VirtualAlloc(home as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical page: its home {home:#x} could not be committed again"); return None; } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(home)) { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(home)) && !private_home(away, page, defer_private_home_tiles()) { crate::hle::d3d12x::sparse::committed(home, PHYS_PAGE); } } @@ -2210,12 +2230,11 @@ const HOMES_AHEAD: usize = 1024; /// already (another page may be mapped at that address, given up in this call), or that cannot /// be, is left to `home_again`. unsafe fn commit_homes_ahead(away: &mut Away, ats: impl Iterator) { - let mut homes: Vec = ats - .filter_map(|at| away.at.get(&at).filter(|_| !lazy::is_marked(at)).and_then(|&p| page_home(p))) - .filter(|&h| lazy_home(h) && !away.gone.contains(&h)) + let home_pages: std::collections::BTreeMap = ats + .filter_map(|at| away.at.get(&at).filter(|_| !lazy::is_marked(at)).and_then(|&p| page_home(p).map(|h| (h, p)))) + .filter(|&(h, _)| lazy_home(h) && !away.gone.contains(&h)) .collect(); - homes.sort_unstable(); - homes.dedup(); + let homes: Vec = home_pages.keys().copied().collect(); let mut i = 0; while i < homes.len() { let start = homes[i]; @@ -2239,7 +2258,13 @@ unsafe fn commit_homes_ahead(away: &mut Away, ats: impl Iterator) && !mem::VirtualAlloc(first as *const c_void, last - first, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(first)) { - crate::hle::d3d12x::sparse::committed(first, last - first); + let mut exposed = SparseRun::new(crate::hle::d3d12x::sparse::committed); + for at in (first..last).step_by(PHYS_PAGE) { + if !private_home(away, home_pages[&at], defer_private_home_tiles()) { + exposed.add(at); + } + } + exposed.flush(); } #[cfg(test)] tests::HOME_RUNS.with(|c| c.set(c.get() + 1)); @@ -2251,23 +2276,40 @@ unsafe fn commit_homes_ahead(away: &mut Away, ats: impl Iterator) } /// `n` pages from `home` committed (a sparse home is only reserved until it is used). -unsafe fn commit_homes(home: usize, n: usize) -> bool { - let Some(u) = crate::gpu::uma::get() else { return false }; +unsafe fn commit_homes(home: usize, pages: &[usize], away: &mut Away) -> Option> { + let Some(u) = crate::gpu::uma::get() else { return None }; if !lazy_home(home) { - return true; + return Some(Vec::new()); } + let n = pages.len(); let len = n * PHYS_PAGE; - if committed_range(home, len) { - return true; - } - if mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + let ready = committed_range(home, len); + if !ready && mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed"); - return false; + return None; } + let mut replay = Vec::new(); if u.is_sparse(home) { - crate::hle::d3d12x::sparse::committed(home, len); + let private = |p: &usize| away.sparse_homes.get(p) == Some(&SparseHome::CpuOnly); + let has_private = defer_private_home_tiles() && pages.iter().any(private); + if !ready || has_private { + crate::hle::d3d12x::sparse::committed(home, len); + } + if has_private { + let mut at = home; + for run in pages.chunk_by(|a, b| private(a) == private(b)) { + let bytes = run.len() * PHYS_PAGE; + if private(&run[0]) { + replay.push((at, bytes)); + } + at += bytes; + } + } + if defer_private_home_tiles() { + away.sparse_homes.extend(pages.iter().map(|&p| (p, SparseHome::Exposed))); + } } - true + Some(replay) } /// Whether all of `[a, a + len)` is committed: one VirtualQuery per run of pages in one state @@ -2356,7 +2398,7 @@ unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range= home + n * PHYS_PAGE); for (i, &p) in pages.iter().enumerate() { @@ -2609,6 +2652,12 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) unmap_away(away, at, &(home..home + n * PHYS_PAGE)); } } + // After copies home: a prior write-watch look may have consumed the storage writes + // while these pages had no GPU tiles. Queue their bytes even when known-write hints + // are disabled, and even when the next submit skips its ordinary write-watch look. + for (at, bytes) in replay { + crate::hle::d3d12x::title_textures::rescan_cpu_backing(at, bytes); + } return home as *mut c_void; } let base = va as usize; @@ -3372,6 +3421,17 @@ pub unsafe extern "system" fn DisableThreadLibraryCalls(h: usize) -> BOOL { mod tests { use super::*; + #[test] + fn exposed_physical_home_is_never_made_private_again() { + let mut away = Away::default(); + assert!(!private_home(&mut away, 7, false)); + assert!(away.sparse_homes.is_empty()); + assert!(private_home(&mut away, 7, true)); + away.sparse_homes.insert(7, SparseHome::Exposed); + assert!(!private_home(&mut away, 7, true), "a later recommit keeps explicit home exposure"); + assert!(private_home(&mut away, 8, true), "another private page is independent"); + } + /// `XCL_COHERENT_HEAPS=sparse[:N]`: which heaps go to the sparse windows #[test] fn sparse_heaps_setting() { From 01a99a40faf73ff551f176b37415a2c1d994da6f Mon Sep 17 00:00:00 2001 From: Prime <215761102+Prime1997@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:32:22 -0800 Subject: [PATCH 023/175] Memory: use a 2 MiB grain for allocator page size two Correct PageSize=2 rounding while preserving explicit alignment, checked sizes, and recorded allocation/free accounting. Update the test title's alignment and zeroing-tail probes to the same 2 MiB contract, keeping the tail read inside its allocation. Three focused tests passed on the earlier preserved patch; restoring the old 4 MiB grain failed all three controls. The new squashed head has not been run individually. Full-suite and retail merge checks remain pending. Assisted-by: Codex (GPT-6) (cherry picked from commit f00e1c4fec6207ed99489947b0180caefaf57c53) --- README.md | 2 +- crates/xcl/src/hle/kernelx.rs | 60 +++++++++++++++++++++++++++++++++-- tests/testtitle/src/main.rs | 12 +++---- 3 files changed, 64 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index e2b00e9191..d41a80eca6 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif |---|---|---|---| | **PE loader** | ✅ | relocations, imports by name / ordinal / delay-load, TLS callbacks, exception tables, game DLLs, data-driven import routing (HLE / Windows / stub) | the game's 16 console DLLs load with 0 unresolved imports | | **kernelx** | ✅ | title memory (budget from MicrosoftGame.Config, physical pages), threads on the PC's processors, modules, OS / console info | unit + end-to-end tests | -| **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows) | GPU tests: loads, stores and atomics across windows | +| **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows); XMem graphics requests for 2 MiB pages round to 2 MiB boundaries | GPU tests: loads, stores and atomics across windows | | **File system** | ✅ | console paths (`GAME:`, `G:`, `D:` …) → the game folder; writes go to an overlay, the game folder is never modified; the console's drives: `S:\` (persistent local storage) and `T:\` (temp) in the title's data folder; free disk space answered for console paths | end-to-end: the test title's folder stays byte-identical; PLS and free space through the real call path | | **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) | diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index cef6aa9374..6255a9118d 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1411,10 +1411,10 @@ unsafe fn aligned_heap_free(p: *mut c_void) { } /// Rounded byte size and alignment for an XMem graphics allocation honoring `page_size` -/// (`2` = `XALLOC_PAGESIZE_4MB`, otherwise 64 KiB sparse tile grain) and `alignment`. +/// (`2` = 2 MiB pages, otherwise 64 KiB sparse tile grain) and `alignment`. fn xmem_graphics_layout(size: usize, a: XAllocAttrs) -> Option<(usize, usize)> { let page_grain = match a.page_size { - 2 => 4 << 20, // XALLOC_PAGESIZE_4MB + 2 => 2 << 20, _ => crate::gpu::uma::GRAIN, }; let align = (1usize << a.alignment.min(usize::BITS - 2)).max(page_grain); @@ -1499,7 +1499,7 @@ pub unsafe fn adopt_title_hooks(main: &crate::modules::MappedModule) { /// asserts that they start there. pub const D3D_DESCRIPTOR_HEAP: u64 = 4 | 1 << 14 | 0x80 << 16 | 16 << 24 | 1 << 29; -/// XALLOC_ATTRIBUTES of a display target's memory: 4 MiB pages (the retail game's hook for its back buffers +/// XALLOC_ATTRIBUTES of a display target's memory: 2 MiB pages (the retail game's hook for its back buffers /// takes every request with them), allocator 0x80, graphics memory. pub const D3D_DISPLAY_TARGET: u64 = 2 << 14 | 0x80 << 16 | 16 << 24 | 1 << 29; @@ -3724,6 +3724,60 @@ mod tests { } } + #[test] + fn xmem_graphics_page_size_two_uses_two_mib_grain() { + const PAGE: usize = 2 << 20; + let attrs = XAllocAttrs::decode((2 << 14) | (1 << 29)); + for (size, rounded) in [(0, PAGE), (1, PAGE), (PAGE - 1, PAGE), (PAGE, PAGE), (PAGE + 1, 2 * PAGE), (2 * PAGE, 2 * PAGE)] { + assert_eq!(xmem_graphics_layout(size, attrs), Some((rounded, PAGE)), "size {size}"); + } + let larger_alignment = XAllocAttrs::decode((2 << 14) | (23 << 24) | (1 << 29)); + assert_eq!(xmem_graphics_layout(1, larger_alignment), Some((PAGE, 8 << 20)), "alignment does not enlarge the allocation's page grain"); + } + + #[test] + fn xmem_graphics_page_grain_preserves_other_codes_and_checks_overflow() { + const PAGE: usize = 2 << 20; + // Code 3 is reserved; keep its existing fallback rather than defining a new contract here. + for code in [0, 1, 3] { + let attrs = XAllocAttrs::decode((code << 14) | (1 << 29)); + assert_eq!(xmem_graphics_layout(0x1_0001, attrs), Some((0x2_0000, 0x1_0000))); + assert!(xmem_graphics_layout(usize::MAX, attrs).is_none()); + } + let attrs = XAllocAttrs::decode((2 << 14) | (1 << 29)); + let largest = usize::MAX & !(PAGE - 1); + assert_eq!(xmem_graphics_layout(largest, attrs), Some((largest, PAGE))); + assert!(xmem_graphics_layout(largest + 1, attrs).is_none()); + assert!(xmem_graphics_layout(usize::MAX, attrs).is_none()); + } + + #[test] + fn xmem_two_mib_layout_accounts_and_releases_owned_memory() { + const PAGE: usize = 2 << 20; + // An owned CPU-only window keeps global UMA state and GPU initialization out of the fixture. + let u = crate::gpu::uma::Uma::with_windows(1, 16 << 20).expect("owned memory window"); + let attrs = XAllocAttrs::decode((2 << 14) | (1 << 29)); + for (requested, expected) in [(1, PAGE), (PAGE, PAGE), (PAGE + 1, 2 * PAGE)] { + let (size, align) = xmem_graphics_layout(requested, attrs).unwrap(); + let p = u.alloc(size, align).expect("owned allocation"); + let (recorded, used) = (u.block_len(p as usize), u.used()); + let address = p as usize; + unsafe { + p.write(0x37); + p.add(requested - 1).write(0x69); + } + // Reclaim before assertions so the negative control also leaves no live allocation. + let released = u.free(address); + assert!(released); + assert_eq!(u.used(), 0); + assert_eq!(u.block_len(address), None); + assert!(!u.free(address), "one allocation is released only once"); + assert_eq!(address % PAGE, 0); + assert_eq!(recorded, Some(expected), "request {requested}: recorded allocation size"); + assert_eq!(used, expected, "request {requested}: memory charged"); + } + } + #[test] fn xmem_alignment_and_zeroing() { let attrs = |align_log2: u64, mtype: u64| (align_log2 << 24) | (mtype << 29); diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index d5ae267a44..92aaa31e17 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -348,12 +348,12 @@ fn main() { ensure!(c == a, "freed blocks merge and are reused: {c:?}"); ensure!(std::slice::from_raw_parts(c as *const u8, 0x30000).iter().all(|&x| x == 0), "reused block not zeroed"); XMemFree(c, attrs); - // 4 MiB page-size semantics (XALLOC_PAGESIZE_4MB = 2 << 14): 4 MiB-aligned & zeroed - let attrs_4m = (1u64 << 29) | (2u64 << 14); - let big = XMemAlloc(0x1000, attrs_4m); - ensure!(!big.is_null() && (big as usize) % (4 << 20) == 0, "4MB page alloc not 4 MiB aligned: {big:?}"); - ensure!(*(big as *const u64) == 0 && *((big as usize + (4 << 20) - 8) as *const u64) == 0, "4MB page alloc not zeroed"); - XMemFree(big, attrs_4m); + // Page-size code 2 requests 2 MiB-aligned, zeroed memory. + let attrs_2m = (1u64 << 29) | (2u64 << 14); + let big = XMemAlloc(0x1000, attrs_2m); + ensure!(!big.is_null() && (big as usize) % (2 << 20) == 0, "2MB page alloc not 2 MiB aligned: {big:?}"); + ensure!(*(big as *const u64) == 0 && *((big as usize + (2 << 20) - 8) as *const u64) == 0, "2MB page alloc not zeroed"); + XMemFree(big, attrs_2m); Ok(()) }); From 4fb9d4952c448c3e69470d1ee530de495196f9e4 Mon Sep 17 00:00:00 2001 From: Royalflamejlh <49204095+Royalflamejlh@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:02:28 -0700 Subject: [PATCH 024/175] Recompiler: the pixel prelude's quad ballot has no loop for DXC to unroll `ballot_px_quad` took its quad's four members in an `[unroll]` loop. It is called in most translated pixel shaders, often hundreds of times, and DXC unrolls every inlined copy: on a 395 KB one with 84 calls, `-ftime-report` put 22 % of its pass time in "Dxil Loop Unroll" and 9 % more in "Unroll loops" and LCSSA. The four members are now written out, in the form thehollowedone gave in review. On a retail pack, 282 pixel shaders compiled in-process on 8 threads took 72.1 s instead of 125.1 s on Windows (Ryzen 7 5700X3D). 980 of them through dxc.exe took 505 s instead of 854 s with DXC 1.9 and 575 s instead of 961 s with DXC 1.8. Under Wine, XCL's own pass over the 980 took 59 s instead of 116 s with #688's private DXC heaps; without them it was slower (428 s against 387 s). Co-authored-by: thehollowedone <36892342+thehollowedone@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 2dad32e6303c6a90d738c87427023d9ad0cc287e) --- crates/xcl/src/gpu/recomp/emit.rs | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 938b6e60ad..92d1e732ab 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -6596,13 +6596,16 @@ const PRELUDE_PIXEL: &str = r#" // compare's vector operands, not of its result (`quad_bits`: AMD's compiler crashed on those, // #134); elsewhere ballot_px quad-reads the result. uint2 ballot_px_quad(uint q) { - uint2 m = uint2(0u, 0u); - [unroll] for (uint p = 0u; p < 4u; p++) { - uint2 w = WaveActiveBallot(((q >> p) & 1u) != 0u).xy; - w |= w >> 1; - w |= w >> 2; - m |= (w & 0x11111111u) << p; - } + uint2 w0 = WaveActiveBallot(((q >> 0u) & 1u) != 0u).xy; + w0 |= w0 >> 1; w0 |= w0 >> 2; + uint2 w1 = WaveActiveBallot(((q >> 1u) & 1u) != 0u).xy; + w1 |= w1 >> 1; w1 |= w1 >> 2; + uint2 w2 = WaveActiveBallot(((q >> 2u) & 1u) != 0u).xy; + w2 |= w2 >> 1; w2 |= w2 >> 2; + uint2 w3 = WaveActiveBallot(((q >> 3u) & 1u) != 0u).xy; + w3 |= w3 >> 1; w3 |= w3 >> 2; + uint2 m = ((w0 & 0x11111111u) << 0u) | ((w1 & 0x11111111u) << 1u) + | ((w2 & 0x11111111u) << 2u) | ((w3 & 0x11111111u) << 3u); return uint2(select(and(xcl_w32, xcl_half != 0u), m.y, m.x), select(xcl_w32, 0u, m.y)); } uint2 ballot_px(bool b) { @@ -7149,4 +7152,14 @@ mod tests { } } } + + #[test] + fn quad_ballot_pixel_helper_has_no_loop_for_dxc_to_unroll() { + let pixel = super::PRELUDE_PIXEL; + let start = pixel.find("uint2 ballot_px_quad(uint q) {").expect("ballot_px_quad in PRELUDE_PIXEL"); + let rest = &pixel[start..]; + let quad = &rest[..rest.find("\n}\n").expect("ballot_px_quad closing brace") + 2]; + let looped = quad.split(|c: char| !(c.is_alphanumeric() || c == '_')).any(|w| ["for", "while", "unroll"].contains(&w)); + assert!(!looped, "a loop remains in ballot_px_quad():\n{quad}"); + } } From c5ff1d0663a1edef04385bb41ac1756e1ad02edf Mon Sep 17 00:00:00 2001 From: itsSio <31954644+itsSio@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:26:23 +0100 Subject: [PATCH 025/175] D3D12.X: pack sparse pool tile reuse into the fullest heap sparse.rs previously stored free pool tiles in a flat Vec and popped the oldest cooled tile from cooling in FIFO order before checking free. When tiles freed across multiple 64 MiB pools cooled, reuse_tile handed out tiles from nearly-empty draining pools instead of packing fuller ones, keeping sparse pools pinned so retire_free_pools could not reclaim them and splitting UpdateTileMappings calls across more heaps. Partition free sparse pool tiles by heap in FreePools. reuse_tile drains cooled tiles into their heaps and takes from the fullest partially-used heap (fewest free tiles in 1..POOL_TILES, lowest heap index on ties), leaving nearly-empty and all-free heaps untouched for retirement unless no partially-used heap has a free tile. retire_free_pools drains cooling and checks heap counts in O(pools) instead of scanning all free tiles, and before_execute_on passes free.has_empty_heap() to retire_due so an all-free heap completed by take_tile's drain_cooling still retires even when cooling is empty. Measured on RTX 5080 (180 s Series S XCL_DEVICE_TYPE=lockhart A/B vs nvidia-dev af2cecc4): peak commit 22042 -> 21818 MB (-224 MB), steady sparse pools 5440 -> 5376 MB (-64 MB), UpdateTileMappings calls 891 -> 736 (-17.4%) for 120k mapped tiles, 0 device removals, 0 crashes. sparse::tests: 61 passed, 0 failed, 1 ignored. Assisted-by: Antigravity (Gemini 4 Neon (High)) (cherry picked from commit 8cf249e55603a3e6dc4c34aa9e1b4fec5077d997) --- crates/xcl/src/hle/d3d12x/sparse.rs | 236 +++++++++++++++++++++++----- 1 file changed, 193 insertions(+), 43 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index c0e41a43aa..3325cbbf6b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -372,29 +372,132 @@ fn zero_runs(pieces: BTreeSet<(usize, usize)>) -> Vec<(usize, usize)> { out } +/// Free pool tiles partitioned by pool heap so `reuse_tile` packs the fullest live heap that +/// still has a free tile instead of scattering allocations across nearly-empty pools that are +/// draining towards `State::retire_free_pools`. +#[derive(Default)] +struct FreePools { + by_heap: Vec>, + total: usize, +} + +impl FreePools { + fn new() -> Self { + Self::default() + } + + fn len(&self) -> usize { + self.total + } + + fn is_empty(&self) -> bool { + self.total == 0 + } + + fn heap_len(&self, h: usize) -> usize { + self.by_heap.get(h).map_or(0, Vec::len) + } + + fn has_empty_heap(&self) -> bool { + self.by_heap.iter().any(|tiles| tiles.len() >= POOL_TILES as usize) + } + + fn add_heap(&mut self, h: u32) { + let idx = h as usize; + if idx >= self.by_heap.len() { + self.by_heap.resize_with(idx + 1, Vec::new); + } + debug_assert!(self.by_heap[idx].is_empty()); + self.by_heap[idx] = (1..POOL_TILES).rev().collect(); + self.total += (POOL_TILES - 1) as usize; + } + + fn push(&mut self, (h, t): (u32, u32)) { + let idx = h as usize; + if idx >= self.by_heap.len() { + self.by_heap.resize_with(idx + 1, Vec::new); + } + self.by_heap[idx].push(t); + self.total += 1; + } + + fn clear_heap(&mut self, h: usize) { + if let Some(tiles) = self.by_heap.get_mut(h) { + self.total -= tiles.len(); + tiles.clear(); + tiles.shrink_to_fit(); + } + } + + /// Move every cooled tile (`>= COOL`) from `cooling` into its pool heap's free list. + fn drain_cooling(&mut self, cooling: &mut VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) { + while cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + if let Some((tile, _)) = cooling.pop_front() { + self.push(tile); + } + } + } + + /// Take a tile from the fullest partially-used heap (`0 < len < POOL_TILES`, lowest heap index + /// on ties) so nearly-empty heaps stay untouched and retire; only take from an all-free heap + /// when no partially-used heap has a free tile. + fn pop_packed(&mut self) -> Option<(u32, u32)> { + if self.total == 0 { + return None; + } + let h = self + .by_heap + .iter() + .enumerate() + .filter(|(_, tiles)| !tiles.is_empty() && tiles.len() < POOL_TILES as usize) + .min_by_key(|(_, tiles)| tiles.len()) + .or_else(|| self.by_heap.iter().enumerate().find(|(_, tiles)| tiles.len() >= POOL_TILES as usize)) + .map(|(h, _)| h)?; + let t = self.by_heap[h].pop()?; + self.total -= 1; + Some((h as u32, t)) + } + + #[cfg(test)] + fn contains(&self, &(h, t): &(u32, u32)) -> bool { + self.by_heap.get(h as usize).is_some_and(|tiles| tiles.contains(&t)) + } + + #[cfg(test)] + fn clear(&mut self) { + for tiles in &mut self.by_heap { + tiles.clear(); + } + self.total = 0; + } + + #[cfg(test)] + fn has_pool(&self, h: u32) -> bool { + self.heap_len(h as usize) > 0 + } +} + /// Whether the oldest tile of `cooling` was freed `COOL` ago or more at `now` fn cooled(cooling: &VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) -> bool { cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) } -/// The pool tile to use next (`State::take_tile`): the oldest of `cooling` if it cooled, else -/// one of `free`. None: neither, though tiles freed less than `COOL` ago may be cooling. -fn reuse_tile(free: &mut Vec<(u32, u32)>, cooling: &mut VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) -> Option<(u32, u32)> { - if cooled(cooling, now) { - return cooling.pop_front().map(|(t, _)| t); - } - free.pop() +/// The pool tile to use next (`State::take_tile`): drain cooled tiles into their pool heaps and +/// take from the fullest partially-used heap (or an all-free heap if none is partially used). +/// None: neither, though tiles freed less than `COOL` ago may be cooling. +fn reuse_tile(free: &mut FreePools, cooling: &mut VecDeque<((u32, u32), std::time::Instant)>, now: std::time::Instant) -> Option<(u32, u32)> { + free.drain_cooling(cooling, now); + free.pop_packed() } /// The pool heaps (`pools` of them) all of whose tiles are in `free` or cooled in `cooling` at /// `now` (`State::retire_free_pools`): a tile still cooling keeps its heap. -fn free_heaps(free: &[(u32, u32)], cooling: &VecDeque<((u32, u32), std::time::Instant)>, pools: usize, now: std::time::Instant) -> Vec { - let ready = cooling.iter().take_while(|&&(_, at)| now.duration_since(at) >= COOL).map(|&(t, _)| t); - if free.len() + ready.clone().count() < POOL_TILES as usize { - return Vec::new(); - } +fn free_heaps(free: &FreePools, cooling: &VecDeque<((u32, u32), std::time::Instant)>, pools: usize, now: std::time::Instant) -> Vec { let mut count = vec![0u32; pools]; - for (h, _) in free.iter().copied().chain(ready) { + for (h, c) in count.iter_mut().enumerate() { + *c = free.heap_len(h) as u32; + } + for &((h, _), _) in cooling.iter().take_while(|&&(_, at)| now.duration_since(at) >= COOL) { if let Some(c) = count.get_mut(h as usize) { *c += 1; } @@ -506,8 +609,9 @@ struct State { windows: Vec<(usize, ID3D12Resource)>, /// video-memory pool heaps (None: given back, its index free for the next one) pools: Vec>, - /// pool tiles to use: those of a pool that were never used, and cooled ones (`cooling`) - free: Vec<(u32, u32)>, + /// pool tiles to use, partitioned by heap (`FreePools`): those of a pool that were never used, + /// and cooled ones (`cooling`) + free: FreePools, /// pool tiles freed (`flush_parked`, once `quarantined` lets them go, and `release_if_unused`), /// oldest first, with when: used again `COOL` after that at the earliest (`take_tile`). /// Before, a tile unmapped went to `free` and was the next one taken, mapped, cleared and @@ -1072,7 +1176,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - job_seq: 0, windows, pools: Vec::new(), - free: Vec::new(), + free: FreePools::new(), cooling: VecDeque::new(), retired: Vec::new(), retire_tried: std::time::Instant::now(), @@ -1280,7 +1384,7 @@ impl State { self.pools.len() as u32 - 1 } }; - self.free.extend((1..POOL_TILES).rev().map(|t| (h, t))); + self.free.add_heap(h); h } @@ -1293,24 +1397,13 @@ impl State { let done = unsafe { super::real::fence_completed(&self.fence) }; let rb_done = self.rbq.as_ref().map_or(u64::MAX, |(_, f)| unsafe { super::real::fence_completed(f) }); self.retired.retain(|(_, v, rb_v, at)| !(done >= *v && rb_done >= *rb_v && now.duration_since(*at).as_secs() >= 2)); - let gone_list = free_heaps(&self.free, &self.cooling, self.pools.len(), now); - if gone_list.is_empty() { + self.free.drain_cooling(&mut self.cooling, now); + let gone: Vec = free_heaps(&self.free, &self.cooling, self.pools.len(), now).into_iter().filter(|&h| self.pools[h].is_some()).collect(); + if gone.is_empty() { return; } - let mut gone = vec![false; self.pools.len()]; - let mut any = false; - for h in gone_list { - if self.pools[h].is_some() { - gone[h] = true; - any = true; - } - } - if !any { - return; - } - self.free.retain(|&(h, _)| !gone[h as usize]); - self.cooling.retain(|&((h, _), _)| !gone[h as usize]); - for h in (0..gone.len()).filter(|&h| gone[h]) { + for h in gone { + self.free.clear_heap(h); if let Some(heap) = self.pools[h].take() { let rb_v = if self.rbq.is_some() { self.rbq_value } else { 0 }; self.retired.push((heap, self.value, rb_v, now)); @@ -4477,7 +4570,7 @@ impl State { s.note_queue(queue); let flushed = s.flush_parked(); s.drain_quarantined(); - if flushed || retire_due(&s.cooling, !s.retired.is_empty(), s.retire_tried, std::time::Instant::now()) { + if flushed || retire_due(&s.cooling, !s.retired.is_empty() || s.free.has_empty_heap(), s.retire_tried, std::time::Instant::now()) { s.retire_free_pools(); } let t_locked = std::time::Instant::now(); @@ -5177,7 +5270,7 @@ mod tests { job_seq: 0, windows: vec![(base, reserved.clone())], pools: Vec::new(), - free: Vec::new(), + free: FreePools::new(), cooling: VecDeque::new(), retired: Vec::new(), retire_tried: std::time::Instant::now(), @@ -5510,7 +5603,7 @@ mod tests { job_seq: 0, windows: Vec::new(), pools: Vec::new(), - free: Vec::new(), + free: FreePools::new(), cooling: VecDeque::new(), retired: Vec::new(), retire_tried: std::time::Instant::now(), @@ -5749,7 +5842,7 @@ mod tests { job_seq: 0, windows: vec![(base, reserved)], pools: Vec::new(), - free: Vec::new(), + free: FreePools::new(), cooling: VecDeque::new(), retired: Vec::new(), retire_tried: std::time::Instant::now(), @@ -5877,7 +5970,7 @@ mod tests { job_seq: 0, windows: vec![(base, reserved)], pools: Vec::new(), - free: Vec::new(), + free: FreePools::new(), cooling: VecDeque::new(), retired: Vec::new(), retire_tried: std::time::Instant::now(), @@ -7589,7 +7682,7 @@ mod tests { fn a_freed_pool_tile_cools_before_it_is_used_again() { let t0 = std::time::Instant::now(); let ms = |n: u64| t0 + std::time::Duration::from_millis(n); - let mut free: Vec<(u32, u32)> = Vec::new(); + let mut free = FreePools::new(); let mut cooling: VecDeque<((u32, u32), std::time::Instant)> = VecDeque::new(); cooling.push_back(((0, 5), ms(0))); cooling.push_back(((0, 6), ms(10))); @@ -7710,13 +7803,70 @@ mod tests { let t0 = std::time::Instant::now(); let ms = |n: u64| t0 + std::time::Duration::from_millis(n); // pool 1 free but its last tile, freed at 0 ms; pool 0 free but its first, freed at 1500 ms - let mut free: Vec<(u32, u32)> = (0..POOL_TILES - 1).map(|t| (1, t)).collect(); - free.extend((1..POOL_TILES).map(|t| (0, t))); + let mut free = FreePools::new(); + for t in 0..POOL_TILES - 1 { + free.push((1, t)); + } + for t in 1..POOL_TILES { + free.push((0, t)); + } let cooling = VecDeque::from([((1, POOL_TILES - 1), ms(0)), ((0, 0), ms(1500))]); assert!(free_heaps(&free, &cooling, 2, ms(1999)).is_empty(), "their last tiles are cooling"); assert_eq!(free_heaps(&free, &cooling, 2, ms(2000)), vec![1], "pool 1's cooled"); assert_eq!(free_heaps(&free, &cooling, 2, ms(3500)), vec![0, 1]); - assert_eq!(free_heaps(&free[1..], &cooling, 2, ms(3500)), vec![0], "a tile of pool 1 in use"); + let mut partial = FreePools::new(); + for t in 1..POOL_TILES - 1 { + partial.push((1, t)); + } + for t in 1..POOL_TILES { + partial.push((0, t)); + } + assert_eq!(free_heaps(&partial, &cooling, 2, ms(3500)), vec![0], "a tile of pool 1 in use"); + } + + /// `reuse_tile` packs the fullest partially-used pool heap rather than handing out the oldest + /// cooled tile from a nearly-empty heap, so draining heaps become completely empty and retire. + /// Before, FIFO `cooling.pop_front()` re-pinned the nearly-empty heap with new allocations. + #[test] + fn reuse_tile_packs_fuller_heaps_so_nearly_empty_pools_retire() { + let t0 = std::time::Instant::now(); + let ms = |n: u64| t0 + std::time::Duration::from_millis(n); + let mut free = FreePools::new(); + let mut cooling: VecDeque<((u32, u32), std::time::Instant)> = VecDeque::new(); + // Pool 1 is almost empty (1000 tiles freed earlier at 0 ms, only 24 still live). + for t in 24..POOL_TILES { + cooling.push_back(((1, t), ms(0))); + } + // Pool 0 is mostly full (only 24 tiles freed later at 10 ms, 1000 still live). + for t in 0..24 { + cooling.push_back(((0, t), ms(10))); + } + // Allocate 24 new tiles once both have cooled: all 24 must pack into fuller pool 0, + // leaving draining pool 1 untouched. + for _ in 0..24 { + let (h, _) = reuse_tile(&mut free, &mut cooling, ms(2010)).expect("a packed tile"); + assert_eq!(h, 0, "must pack into fuller pool 0 instead of re-pinning draining pool 1"); + } + assert_eq!(free.heap_len(0), 0, "pool 0 is completely packed"); + assert_eq!(free.heap_len(1), (POOL_TILES - 24) as usize, "pool 1 stayed untouched"); + + // When pool 1's remaining 24 tiles free and cool, all of pool 1 is free and ready to retire. + for t in 0..24 { + cooling.push_back(((1, t), ms(2100))); + } + assert_eq!(free_heaps(&free, &cooling, 2, ms(4100)), vec![1]); + + // An all-free heap is skipped while a partially-used heap has space, and `has_empty_heap` + // reports it so `retire_due` retires it even after `cooling` has been drained. + free.push((0, 0)); + free.drain_cooling(&mut cooling, ms(4100)); + assert!(cooling.is_empty()); + assert!(free.has_empty_heap()); + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(4100)), Some((0, 0)), "partial pool 0 before all-free pool 1"); + assert_eq!(free.heap_len(1), POOL_TILES as usize, "all-free pool 1 left intact for retirement"); + assert!(retire_due(&cooling, free.has_empty_heap(), ms(0), ms(4100))); + // When no partial pool remains, the all-free pool is reused instead of creating a new heap. + assert_eq!(reuse_tile(&mut free, &mut cooling, ms(4100)).map(|(h, _)| h), Some(1)); } /// A GPU-view tile given back and unmapped at a submit is not the video memory of the next @@ -7798,7 +7948,7 @@ mod tests { assert!(v.s.parked.is_empty()); v.submit(&[]); assert!(v.s.pools[pool.0 as usize].is_none(), "retired with nothing parked"); - assert!(v.s.cooling.is_empty() && !v.s.free.iter().any(|t| t.0 == pool.0)); + assert!(v.s.cooling.is_empty() && !v.s.free.has_pool(pool.0)); assert_eq!(v.s.retired.len(), 1); } } From 8942a5b9b5049335159d75070b1f5c9c3135cba4 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:03:33 +0100 Subject: [PATCH 026/175] D3D12.X: indirect light made in space, bake sources by index, shadowed textures drawn again Work in progress on the visual defects of a retail title on an RX 9070 XT (direct DXIL), not split into single changes yet: - ambient: the resolve's light and depth are taken from their own slots; the estimate is made in space from the depth (cells placed, gathered at 160x90 points, raised along a normal rebuilt from the depth), the air's light is held to the light around, magenta is rejected in the reflection clamps. Switches: XCL_AMBIENT_SPACE, XCL_AMBIENT_SPLIT, XCL_AMBIENT_MOST, XCL_AMBIENT_SKY. Credit in THIRD_PARTY.md. - shadowed textures a draw's tables name are made active again (after open PR #2956): video frames no longer come up green. - draws of bake pipelines (drawn once and kept) wait for their pipeline and make the shadowed textures they pick by index active again (XCL_KEPT_DRAWS, XCL_BAKE_SOURCES). - diagnostics: XCL_TRACE_LATE, XCL_TRACE_SLOT. - earlier fixes of this branch: vertex buffers kept out of the alias space, the PS export patch table for all pixel shaders, ambient levels. Tested: cargo test -p xcl --lib -- ambient stage_name placements title_textures pso_async bcpack rt_leave_out: 117 passed, 0 failed (RX 9070 XT, release build runs of 300 s without device removal). Not tested: the whole suite, scripts/smoke.ps1, other GPUs. Open: black heads at a distance, dotted diagonals, 3-5 fps in the world. Co-Authored-By: Claude Mythos 5.2 --- HANDOFF.md | 2 +- README.md | 15 +- THIRD_PARTY.md | 1 + crates/xcl/build.rs | 3 +- crates/xcl/src/gpu/recomp/mod.rs | 96 ++- crates/xcl/src/gpu/recomp/pso.rs | 24 +- crates/xcl/src/gpu/rt_leave_out.rs | 4 +- crates/xcl/src/gpu/uma.rs | 11 +- crates/xcl/src/hle/bcpack/tests.rs | 2 +- crates/xcl/src/hle/bcpack/victory.rs | 2 +- crates/xcl/src/hle/d3d12x/ambient.rs | 608 ++++++++++++--- crates/xcl/src/hle/d3d12x/bind.rs | 786 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/capture.rs | 21 + crates/xcl/src/hle/d3d12x/console_heap.rs | 554 +++++++++++++- crates/xcl/src/hle/d3d12x/device_x.rs | 19 +- crates/xcl/src/hle/d3d12x/list_x.rs | 13 + crates/xcl/src/hle/d3d12x/present.rs | 20 + crates/xcl/src/hle/d3d12x/pso_async.rs | 48 +- crates/xcl/src/hle/d3d12x/real.rs | 406 +++++++++- crates/xcl/src/hle/d3d12x/small_tex.rs | 11 +- crates/xcl/src/hle/d3d12x/sparse.rs | 135 +++- crates/xcl/src/hle/d3d12x/texture_upload.rs | 11 +- crates/xcl/src/hle/d3d12x/title_list.rs | 139 +++- crates/xcl/src/hle/d3d12x/title_textures.rs | 344 ++++++++- crates/xcl/src/hle/d3d12x/vram.rs | 33 +- crates/xcl/src/hle/kernelx.rs | 15 +- crates/xcl/src/hle/kernelx/alias.rs | 2 +- crates/xcl/src/ram_budget.rs | 3 +- crates/xcl/src/shaders.rs | 49 +- docs/specs/2026-11-24-direct-dxil.md | 4 - scripts/gen_bcpack_victory_tables.py | 2 +- 31 files changed, 3139 insertions(+), 244 deletions(-) diff --git a/HANDOFF.md b/HANDOFF.md index 984a45360a..d0a01a790d 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -258,7 +258,7 @@ NOTE: ### Console DLLs from the game pack (session 5, without the exe) The user provided 16 DLLs from chunk 1002 (`\*.dll`, ordinary PEs): the console CRT (vcruntime140(_1), msvcp140(_1/_2/_atomic_wait/_codecvt_ids), concrt140, vcomp140, vccorlib140), Bink2Scarlett, XCurl, libHttpClient.GDK, -amd_fidelityfx_loader_xbox / amd_fidelityfx_upscaler_xbox, XboxBvhBuilder. The game exe (`game_scarlett_master.exe`) is still missing. +amd_fidelityfx_loader_xbox / amd_fidelityfx_upscaler_xbox, XboxBvhBuilder. The game exe is still missing. - `xcl inspect`: after fixes **0 missing imports in all 16**. Added: - `XMemVirtualQuery(process, address, info) → BOOL` (signature from the call sites in XboxBvhBuilder, objdump from msys64): info = MEMORY_BASIC_INFORMATION + a field @48, bits 0–1 = memory readable by the CPU (message on error: diff --git a/README.md b/README.md index d41a80eca6..faf7f98233 100644 --- a/README.md +++ b/README.md @@ -355,11 +355,20 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. fills into its GPU views) are applied: a GPU-view page shows the physical page mapped into it. `XCL_PAGE_MAPPINGS=0` turns them off (the call is ignored and a GPU-view page shows its CPU view at the same offset, as before). -- `XCL_DEFER_PRIVATE_HOME_TILES=1` keeps physical-page home storage used only by CPU/storage +- `XCL_DEFER_PRIVATE_HOME_TILES` keeps physical-page home storage used only by CPU/storage transfers from acquiring a second sparse GPU copy. Explicit home mappings expose and upload the existing bytes before the next submission, even after an earlier write-watch scan. - Already-exposed homes keep their normal behavior. Off by default; this reduces avoidable - backing, not the memory needed by live GPU mappings, and is not a VRAM budget cap. + Already-exposed homes keep their normal behavior. On by default (`=0` turns it off); this + reduces avoidable backing, not the memory needed by live GPU mappings, and is not a VRAM + budget cap. +- Memory on 32 GB PCs: Windows charges every byte of video memory to the system's commit (RAM + + page file), so video memory XCL does not need counts like RAM. These are on by default to keep + it down: a streamed texture's levels get video memory when they are loaded + (`XCL_TEXTURE_LEVEL_PAGES=0` gives every level its memory at once), small sampled textures share + 4 KiB placements (`XCL_SMALL_TEXTURES=0`: a committed resource each), and 64 MB of idle texture + upload buffers are kept (`XCL_UPLOAD_KEEP_MB`). Shader preparation starts no more workers than + the RAM available holds (2 GB each, 4 GB left over) and the commit left (3 GB each); + `XCL_PREPARE_WORKERS=N` sets the number. - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index db38e8a443..c088995ee0 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -11,6 +11,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | +| [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs` (the programs left out); `crates/xcl/src/hle/d3d12x/ambient.rs`: the cells and their slow mean, and the stand-in for the indirect light made in space – `LIGHT_PLACE_HLSL`, `LIGHT_GATHER_HLSL`, the depth path of `AMBIENT_FILL_R9G9B9E5_HLSL`, `AIR_CAP_HLSL` and the resolve's descriptor slots, after `place`, `gather`, `raise`, `clear_air`, `LIGHT` and `DEPTH` of its `ambient.rs` (commit 99a7f9b) | port of the HLSL into XCL's ambient pass (2026-11-28) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8e..dd1fbe361b 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -58,7 +58,8 @@ fn main() { Ok("gnu") => println!("cargo:rustc-link-arg-bin=xcl=-Wl,--disable-high-entropy-va"), _ => {} } - let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"); + let root = Path::new(&manifest_dir); let mut h = 0xcbf2_9ce4_8422_2325u64; add(&mut h, b"xcl-translator-source-v1\0"); add(&mut h, TRANSLATION_GLUE_REVISION.as_bytes()); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index dc0d08c65b..ac0826e996 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -453,12 +453,67 @@ pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { pub const DEPTH_BEFORE_SHADER: u32 = 1 << 12; /// DB_SHADER_CONTROL of an FSSM: the dword after SPI_PS_INPUT_ENA in the PS input table -/// (`ps_input_table`, +0x114; the same layout VIctory's `native.rs` reads it from). +/// (`ps_input_table`, +0x114). pub fn ps_shader_control(fssm: &[u8]) -> Option { let o = 0x130 + fssm_shift(fssm)? + 0x114; fssm.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())) } +/// Apply the FSSM pixel-shader export patches (full 32-bit `32_ABGR` slot, index 9 of 10) to a PS +/// program's code bytes. Console pixel shaders ship with compressed FP16 export templates +/// (`v_cvt_pkrtz_f16_f32` + `exp compr`) that the console driver patches per bound RTV format at +/// pipeline creation; applying slot 9 emits the shader's raw 32-bit `SV_TargetN` values +/// unconverted, matching PC DXIL/HLSL semantics (preventing `R32_UINT` / 32-bit MRTs such as +/// packed SSS radiance from being mangled into `0x7BFF` via FP16 conversion). +pub fn patch_ps_exports(f: &super::xbox::Fssm, p: &super::xbox::Program) -> (Vec, usize) { + let mut code = f.data[p.offset..p.offset + p.len].to_vec(); + let Some(shift) = fssm_shift(&f.data) else { return (code, 0) }; + if ps_input_table(&f.data).is_none() { + return (code, 0); + } + let base = 0x130 + shift; + let rd = |o: usize| f.data.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + const PATCH_SLOT_DWORDS: usize = 10; + const PATCH_FULL: usize = 9; + const PATCH_BYTES: usize = 4 + 10 * PATCH_SLOT_DWORDS * 4; + let Some(size) = rd(base + 0x124).map(|n| n as usize) else { return (code, 0) }; + if size == 0 || size > PATCH_SLOT_DWORDS { + return (code, 0); + } + let Some((code_start, code_len)) = f.code else { return (code, 0) }; + let patch_bytes = size * 4; + let mut patches: Vec<(usize, usize)> = Vec::new(); + for mrt in 0..8usize { + let at = base + 0x128 + mrt * PATCH_BYTES; + let Some(off) = rd(at) else { return (code, 0) }; + if off == u32::MAX { + continue; + } + let Some(end_bytes) = (off as usize).checked_add(size).and_then(|w| w.checked_mul(4)) else { return (code, 0) }; + if end_bytes > code_len { + return (code, 0); + } + let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + let Some(slice) = f.data.get(full..full + patch_bytes) else { return (code, 0) }; + let mut cur = 0usize; + while cur < slice.len() { + match super::rdna2::decode(&slice[cur..], cur as u64) { + Ok(d) if cur + d.len <= slice.len() => cur += d.len, + _ => return (code, 0), + } + } + let target_abs = code_start + off as usize * 4; + if target_abs >= p.offset && target_abs + patch_bytes <= p.offset + p.len { + patches.push((target_abs - p.offset, full)); + } + } + let count = patches.len(); + for (dst, src) in patches { + code[dst..dst + patch_bytes].copy_from_slice(&f.data[src..src + patch_bytes]); + } + (code, count) +} + /// The VS output table of an FSSM: per `exp param N`, the OSG1 register it writes. 32 records /// of 6 bytes at +0x1D4 (+ the sub-version shift): kind (6 user, 0 position), register, param /// number, 0, 0, 0; the record count after them (+0xC0). Usually param N = the N-th output @@ -1959,4 +2014,43 @@ mod attribute_tests { f[0x1D4 + 8] = 7; assert_eq!(vs_output_table(&f), None); } + + #[test] + fn patches_ps_exports_to_full_32bit_variant() { + // 4 dwords of code: s_nop; v_cvt_pkrtz_f16_f32 v4, v6, v6; exp mrt1 v4 compr done vm + let orig: [u32; 4] = [0xBF80_0000, 0x5E08_0D06, 0xF800_1C13, 0x0000_0004]; + let full: [u32; 3] = [0xBF80_0000, 0xF800_1811, 0x0000_0006]; // s_nop; exp mrt1 v6 done vm + let base = 0x138usize; // sub-version 6 + let code_start = 0xF08usize; + let mut data = vec![0u8; code_start + orig.len() * 4]; + data[0x10..0x14].copy_from_slice(&6u32.to_le_bytes()); + // valid empty PS input table + data[base + 0x100..base + 0x104].copy_from_slice(&0u32.to_le_bytes()); + data[base + 0x110..base + 0x114].copy_from_slice(&0u32.to_le_bytes()); + data[base + 0x124..base + 0x128].copy_from_slice(&3u32.to_le_bytes()); // patch size = 3 dwords + for mrt in 0..8usize { + let at = base + 0x128 + mrt * 404; + data[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + } + // MRT1 at dword offset 1 + let mrt1 = base + 0x128 + 404; + data[mrt1..mrt1 + 4].copy_from_slice(&1u32.to_le_bytes()); + let slot9 = mrt1 + 4 + 9 * 40; + for (i, w) in full.iter().enumerate() { + data[slot9 + i * 4..slot9 + i * 4 + 4].copy_from_slice(&w.to_le_bytes()); + } + for (i, w) in orig.iter().enumerate() { + data[code_start + i * 4..code_start + i * 4 + 4].copy_from_slice(&w.to_le_bytes()); + } + let f = super::super::xbox::Fssm { + data, + code: Some((code_start, orig.len() * 4)), + ..Default::default() + }; + let p = super::super::xbox::Program { offset: code_start, len: orig.len() * 4 }; + let (patched, n) = patch_ps_exports(&f, &p); + assert_eq!(n, 1); + let words: Vec = patched.chunks_exact(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + assert_eq!(words, vec![orig[0], full[0], full[1], full[2]]); + } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index a9890986f8..048b200ae0 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1139,7 +1139,20 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == want)).ok_or("no hardware variant")?; let mode = interface(blob, &sh, f).ok_or("unknown shader interface")?; let p = f.programs.first().ok_or("FSSM without a program")?; - let code = &f.data[p.offset..p.offset + p.len]; + let patched; + let code: &[u8] = if stage == Stage::Pixel { + let (buf, n) = super::patch_ps_exports(f, p); + if n > 0 { + static LOGGED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 10 { + crate::xlog_info!("[SHADER] PS {:016x}: applied {n} full-32b export patch(es) (direct DXIL)", crate::gpu::shader::fnv64(blob)); + } + } + patched = buf; + &patched + } else { + &f.data[p.offset..p.offset + p.len] + }; let o = crate::gpu::dxil::kernel::KernelOptions { wave64: super::fssm_wave64(f, code), split: false, mem_windows: windows, sampler_base }; let entry = match (&mode, stage) { (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::Entry::Vertex(vs.clone()), @@ -1185,7 +1198,14 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, _ => return Err("the shader stage does not match its slot in the PSO".into()), }; let p = f.programs.first().ok_or("FSSM without a program")?; - let code = &f.data[p.offset..p.offset + p.len]; + let patched; + let code: &[u8] = if stage == Stage::Pixel { + let (buf, _) = super::patch_ps_exports(f, p); + patched = buf; + &patched + } else { + &f.data[p.offset..p.offset + p.len] + }; let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, rodata: f.rodata(p), ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); diff --git a/crates/xcl/src/gpu/rt_leave_out.rs b/crates/xcl/src/gpu/rt_leave_out.rs index 762acb7114..174248a4b9 100644 --- a/crates/xcl/src/gpu/rt_leave_out.rs +++ b/crates/xcl/src/gpu/rt_leave_out.rs @@ -14,9 +14,7 @@ //! memory) and warns once when one of them gets a root node: from then on rays can hit, and //! the programs left out would have shaded those hits. //! -//! Ported from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later), commit -//! `1f69d67`, `crates/victory-gpu/src/pipeline/make.rs` (`left_out`: `VICTORY_RT_RESOLVE`, -//! `VICTORY_ACTIVATE_RAYS`, `VICTORY_BVH_BUILDER`; there since codec_d's `8cc31ab`). +//! Ported from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later; THIRD_PARTY.md). //! Changes (2026-11-27): the programs are named by the user's fragments instead of names in //! the source; one switch; the structure watch and its warning are new; the preparation and //! the precompile pass the programs over. diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 1c07197c32..7b12ec9b0d 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -110,6 +110,11 @@ pub(crate) fn configured_runtime_windows() -> usize { const DESC_HEADROOM: usize = 512 << 20; /// cap on the eager committed coherent window in `for_runtime` (per-draw args, readback buffers) const RUNTIME_COMMITTED_CAP: usize = 512 << 20; +/// What the coherent window has beyond the title's need stored from earlier runs +/// (`coherent_hint_for`). The window is committed and held in RAM whole while it is open as a +/// heap: with 512 MB a retail title's 968 MB window had 416 MB in use at most (its 457 MB need, +/// XCL's 96 MB kept for itself included). +const COHERENT_HEADROOM: usize = 192 << 20; #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum WindowKind { @@ -1065,7 +1070,7 @@ pub fn coherent_hint_for(windows: usize) -> usize { ); return RUNTIME_COMMITTED_CAP; } - (title + RUNTIME_COMMITTED_CAP).min(cap) + (title + COHERENT_HEADROOM).max(RUNTIME_COMMITTED_CAP).min(cap) } /// Bytes the coherent window is made with (legacy 4-window cap). @@ -1131,7 +1136,7 @@ pub fn note_coherent_need(bytes: usize) { } let _ = std::fs::write(&f, bytes.to_string()); let cap = max_coherent_bytes(configured_runtime_windows()); - crate::xlog_info!("UMA: the title's graphics memory for the coherent window: {} MB (up to {} MB from the next run)", bytes >> 20, (bytes + RUNTIME_COMMITTED_CAP).min(cap) >> 20); + crate::xlog_info!("UMA: the title's graphics memory for the coherent window: {} MB (up to {} MB from the next run)", bytes >> 20, (bytes + COHERENT_HEADROOM).max(RUNTIME_COMMITTED_CAP).min(cap) >> 20); } } @@ -1149,7 +1154,7 @@ fn settle_coherent_need() { "UMA: this run put {} MB of the title's graphics memory in the coherent window, {} MB were stored for '{route}' (XCL_COHERENT_HEAPS): the next run makes it {} MB", run >> 20, before >> 20, - (next + RUNTIME_COMMITTED_CAP).min(max_coherent_bytes(configured_runtime_windows())) >> 20 + (next + COHERENT_HEADROOM).max(RUNTIME_COMMITTED_CAP).min(max_coherent_bytes(configured_runtime_windows())) >> 20 ); } } diff --git a/crates/xcl/src/hle/bcpack/tests.rs b/crates/xcl/src/hle/bcpack/tests.rs index 70c425a95f..6dc20525ca 100644 --- a/crates/xcl/src/hle/bcpack/tests.rs +++ b/crates/xcl/src/hle/bcpack/tests.rs @@ -102,7 +102,7 @@ fn junk_streams_do_not_panic() { } } -/// The BC7 dictionary indices follow VIctory PR #658: a set with 0 bits holds no +/// The BC7 dictionary indices: a set with 0 bits holds no /// indices, and pixel 0 is the anchor (top bit clear). Entry 0 stores all 32 indices /// directly without the repeated width word, keeping its leading `[2, 1, 0, ...]` values. #[test] diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index 31e1230391..49094c3be2 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -594,7 +594,7 @@ fn pbits(mode: u16) -> bool { /// The channel rotation of a BC7 block: only modes 4 and 5 have the 2-bit /// field; in the other modes those control bits mean something else, and -/// reading them as a rotation swapped channels (upstream VIctory PR #3111). +/// reading them as a rotation swapped channels. fn rotation(ctrl: u16) -> usize { if matches!(ctrl & 7, 4 | 5) { usize::from(ctrl >> 3 & 3) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 669aca26db..56cc0adc1a 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -12,18 +12,29 @@ //! //! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, //! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`, `XCL_AMBIENT_FRAME`, -//! `XCL_AMBIENT_KEEP`. +//! `XCL_AMBIENT_KEEP`, `XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`, `XCL_AMBIENT_SPACE`, `XCL_AMBIENT_SPLIT`. //! //! The sky alone leaves a night scene black wherever no lamp reaches. So the fill is also raised //! to an estimate taken from the frame itself: the light the visible surfaces send out, which the //! title keeps for its own screen traces (`CS_CacheScreenSpaceRadiance`, the frame before), is //! averaged in 64x36 cells right after that program, and every texel of the resolve's output gets //! `XCL_AMBIENT_FRAME` (default 0.8; 0: off) of the cells around it, a fifth of it their slow -//! mean. The idea and the 64x36 cells, the 5x5 taps, the damping of lamps and the slow mean with -//! its jump are from mavis-9070xt's fork of VIctory (GPL-3.0-or-later), -//! `crates/victory-gpu/src/ambient.rs` (`keep`, `mean`, `raise`), after beloooo's -//! VIctory-Belobug-AMD. Not ported (2026-11-28): the directional gather at 160x90 points, the -//! normal rebuilt from depth and the bound on the title's own value. +//! mean. +//! +//! Ported in part from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later; +//! THIRD_PARTY.md): the cells, their slow mean, and the estimate made in space (2026-11-28). +//! +//! With the depth the resolve reads, the estimate is made in space rather than on the screen: +//! each cell is placed where it is seen (`LIGHT_PLACE_HLSL`), the cells' light is +//! gathered at 160x90 points by distance, as a mean and a direction for each colour +//! (`LIGHT_GATHER_HLSL`), and a texel takes the four points around it, those at its own depth +//! first, along a normal rebuilt from the depth, shaded where its surroundings close over it. So +//! a dark car cabin gets the light of the lit street beside it, and a face has a lit and a +//! shaded side. What the title's own resolve left is kept up to `XCL_AMBIENT_MOST` times the +//! estimate (2 unless given) when it is kept at all (`XCL_AMBIENT_KEEP`), the sky's level counts +//! for `XCL_AMBIENT_SKY` of itself (0.35 unless given), and the air's +//! scattered light (`XCL_AMBIENT_AIR`, 1.5 unless given, 0: off) is held to that multiple of the +//! light of the room and of the surface seen behind it. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; @@ -58,24 +69,33 @@ struct Config { settle_ms: f32, air: f32, frame: f32, + /// what the title's own resolve left counts for at most this many times the estimate + most: f32, + /// the share of the sky's level every texel gets whatever the frame's light + sky: f32, } impl Default for Config { fn default() -> Self { Self { mode: Mode::Auto, - gain: 0.22, - power: 0.65, - least: 0.02, + gain: 0.44, + power: 0.36, + least: 0.075, ao: 0.55, reflect: 0.50, settle_ms: 250.0, - air: 0.0, + air: 1.5, frame: 0.8, + most: 2.0, + sky: 0.35, } } } +/// Fallback ambient level used before the first sky-dome capture completes. +const PRE_SKY_FALLBACK: f32 = 0.28; + fn parse_mode(raw: Option<&str>) -> Mode { match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { Some("0" | "off" | "none" | "false") => Mode::Off, @@ -107,6 +127,8 @@ fn config() -> &'static Config { settle_ms: env_f32("XCL_AMBIENT_SETTLE_MS", def.settle_ms, 0.0, 10_000.0), air: env_f32("XCL_AMBIENT_AIR", def.air, 0.0, 16.0), frame: env_f32("XCL_AMBIENT_FRAME", def.frame, 0.0, 4.0), + most: env_f32("XCL_AMBIENT_MOST", def.most, 1.0, 16.0), + sky: env_f32("XCL_AMBIENT_SKY", def.sky, 0.0, 1.0), } }) } @@ -146,6 +168,20 @@ pub fn active() -> bool { /// (`XCL_AMBIENT_KEEP=1` / `=0`). Unset: kept, unless programs that feed the resolve are left out /// (`XCL_RT_LEAVE_OUT`) – then what it stores is made of memory nothing wrote this frame (on a /// retail title: one colour all over, as bright as the fill's cap lets it be). +/// Whether the resolve's light is made in space, from the depth it reads (`XCL_AMBIENT_SPACE=0`: +/// on the screen, from the cells under each texel). +fn space_light() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_AMBIENT_SPACE").map_or(true, |v| v.trim() != "0")) +} + +/// `XCL_AMBIENT_SPLIT=1`: only the left half of the picture gets the light made in space (the +/// right half the one made on the screen), to compare the two in one frame. +fn split_screen() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_AMBIENT_SPLIT").is_ok_and(|v| v.trim() == "1")) +} + fn keeps_title_light() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| keeps(std::env::var("XCL_AMBIENT_KEEP").ok().as_deref(), crate::gpu::rt_leave_out::enabled())) @@ -170,6 +206,8 @@ pub(super) enum PassRole { SkyDome, TemporalResolve, ReflectionHistory, + /// `CS_TemporalResolve2_Opaque` / `CS_TemporalResolve1_Alpha` (R9G9B9E5 packed in R32_UINT) + ReflectionResolve, InscatteringVolume, /// keeps the light visible surfaces send out (`CS_CacheScreenSpaceRadiance`) Radiance, @@ -193,6 +231,10 @@ fn classify_ps(blob: &[u8]) -> Option { fn classify_cs(blob: &[u8]) -> Option { if contains_ascii_ci(blob, b"CS_ScreenProbes_TemporalResolve") { Some(PassRole::TemporalResolve) + } else if contains_ascii_ci(blob, b"CS_TemporalResolve2_Opaque") + || contains_ascii_ci(blob, b"CS_TemporalResolve1_Alpha") + { + Some(PassRole::ReflectionResolve) } else if contains_ascii_ci(blob, b"CS_UpdateHistory") { Some(PassRole::ReflectionHistory) } else if contains_ascii_ci(blob, b"CS_AccumulateLocalLightInscatteringVolume") { @@ -401,7 +443,7 @@ fn is_sky_dome_target(rd: &D3D12_RESOURCE_DESC) -> bool { /// restricting `TemporalResolve` to `R32_UINT` avoids accidentally overwriting a `R11G11B10_FLOAT` /// (`fmt 26`) HDR scene color buffer bound in the same descriptor heap. fn score_dispatch_target_for_role(role: PassRole, rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; 3]) -> Option { - if role == PassRole::TemporalResolve && view_fmt != 42 { + if matches!(role, PassRole::TemporalResolve | PassRole::ReflectionResolve) && view_fmt != 42 { return None; } if role == PassRole::ReflectionHistory && view_fmt == 42 { @@ -533,13 +575,17 @@ struct AmbientDevice { fill_pso: ID3D12PipelineState, fill_write_pso: ID3D12PipelineState, fill_r9_pso: ID3D12PipelineState, + place_pso: ID3D12PipelineState, + gather_pso: ID3D12PipelineState, reflect_pso: ID3D12PipelineState, + reflect_r9_pso: ID3D12PipelineState, air_pso: ID3D12PipelineState, keep_pso: ID3D12PipelineState, mean_pso: ID3D12PipelineState, sky_copy: ID3D12Resource, sky_level: ID3D12Resource, dummy_depth: ID3D12Resource, + dummy_indirect: ID3D12Resource, heap: ID3D12DescriptorHeap, heap_cpu: u64, heap_gpu: u64, @@ -630,10 +676,13 @@ void main(uint3 gtid : SV_GroupThreadID, uint gidx : SV_GroupIndex) { } "#; -/// The cells the frame's light is kept in, and the float4s of the level buffer: the sky's level, -/// the cells' slow mean, the cells. +/// The cells the frame's light is kept in, the points it is gathered at, and the float4s of the +/// level buffer: the sky's level, the cells' slow mean, the cells, where each cell is seen +/// (`LIGHT_PLACE_HLSL`), and three for each point – red, green and blue, a direction and a mean +/// (`LIGHT_GATHER_HLSL`). const FRAME_CELLS: (u32, u32) = (64, 36); -const LEVEL_ELEMENTS: u32 = 2 + FRAME_CELLS.0 * FRAME_CELLS.1; +const GATHER_POINTS: (u32, u32) = (160, 90); +const LEVEL_ELEMENTS: u32 = 2 + 2 * FRAME_CELLS.0 * FRAME_CELLS.1 + 3 * GATHER_POINTS.0 * GATHER_POINTS.1; /// A change of the cells' mean by more than this factor is taken at once (a cut, a new room). const FRAME_JUMP: f32 = 3.0; @@ -804,11 +853,11 @@ void main(uint3 tid : SV_DispatchThreadID) { } "#; -/// Screen-space diffuse probe radiance floor + 8-tap IGN-rotated horizon crease AO for -/// `CS_ScreenProbes_TemporalResolve` targets stored as `R9G9B9E5_SHAREDEXP` packed in `R32_UINT`. -const AMBIENT_FILL_R9G9B9E5_HLSL: &str = r#" +/// What the place, gather and raise programs share (`light_hlsl`): the level buffer's layout and +/// the point seen at a texel, from the depth the resolve reads (the title's depth is near / z +/// with near 0.1 m, its view 0.45 high at 1 m). +const LIGHT_COMMON_HLSL: &str = r#" Texture2D depth_tex : register(t0); -RWTexture2D out_uav : register(u0); RWStructuredBuffer sky_level : register(u1); cbuffer C : register(b0) { uint width; @@ -820,25 +869,107 @@ cbuffer C : register(b0) { uint sky_ready; float fallback_level; }; +#define CX 64 +#define CY 36 +#define CELLS 2304 +#define PX 160 +#define PY 90 +#define CELL_AT 2 +#define PLACE_AT 2306 +#define POINT_AT 4610 +static const float3 LUMA = float3(0.2126, 0.7152, 0.0722); +// The point seen at a texel of the width x height picture, in metres from the eye (x right, y up, +// z away). +float3 seen(int2 p, float2 size) { + int2 q = clamp(int2((float2(p) + 0.5) * float2(depth_w, depth_h) / size), int2(0, 0), int2(depth_w, depth_h) - 1); + float d = depth_tex.Load(int3(q, 0)); + float z = min(0.1 / max(d, 1e-7), 1000.0); + float2 ndc = (float2(p) + 0.5) / size * 2.0 - 1.0; + return float3(ndc.x * 0.45 * size.x / size.y * z, -ndc.y * 0.45 * z, z); +} +"#; + +/// A light program's source: the switches' values (`XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`), what +/// the programs share, and `body`. +fn light_hlsl(body: &str) -> String { + let cfg = config(); + format!("#define MOST {:.6}\n#define SKY_SHARE {:.6}\n{LIGHT_COMMON_HLSL}{body}", cfg.most, cfg.sky) +} + +/// Where each of the 64x36 cells is seen, and its distance squared. +const LIGHT_PLACE_HLSL: &str = r#" +[numthreads(8, 4, 1)] +void main(uint3 at : SV_DispatchThreadID) { + if (at.x >= CX || at.y >= CY) return; + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(CX, CY)), size); + sky_level[PLACE_AT + at.y * CX + at.x] = float4(p, p.z * p.z); +} +"#; + +/// The cells' light as it reaches each of 160x90 points: every cell by its distance, a mean and +/// a direction for each colour. +const LIGHT_GATHER_HLSL: &str = r#" +[numthreads(8, 2, 1)] +void main(uint3 at : SV_DispatchThreadID) { + if (at.x >= PX || at.y >= PY) return; + float2 size = float2(width, height); + float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(PX, PY)), size); + float r2 = 0.25 + 0.0025 * p.z * p.z; + float whole = 0.0; + float3 toward = float3(0.0, 0.0, 0.0), light = float3(0.0, 0.0, 0.0); + float3 red = float3(0.0, 0.0, 0.0), green = float3(0.0, 0.0, 0.0), blue = float3(0.0, 0.0, 0.0); + [loop] + for (uint i = 0; i < CELLS; ++i) { + float4 c = sky_level[PLACE_AT + i]; + float3 L = sky_level[CELL_AT + i].rgb; + L = all(isfinite(L)) ? max(L, 0.0) : float3(0.0, 0.0, 0.0); + float3 d = c.xyz - p; + float dd = dot(d, d); + float w = c.w / (dd + r2); + float3 dir = d / sqrt(dd + 0.25 * r2); + whole += w; + toward += w * dir; + light += w * L; + red += w * L.r * dir; + green += w * L.g * dir; + blue += w * L.b * dir; + } + whole = max(whole, 1e-6); + light /= whole; + toward /= whole; + uint at0 = POINT_AT + (at.y * PX + at.x) * 3; + sky_level[at0] = float4(red / whole - light.r * toward, light.r); + sky_level[at0 + 1] = float4(green / whole - light.g * toward, light.g); + sky_level[at0 + 2] = float4(blue / whole - light.b * toward, light.b); +} +"#; + +/// The diffuse light of a texel of the resolve's output (`R9G9B9E5_SHAREDEXP` packed in +/// `R32_UINT`), after `light_hlsl`. With the depth: the four gathered points +/// around the texel, those at its own depth first, along the normal the depth gives, shaded where +/// the surroundings close over it within 0.6 m. Without it: the cells under the texel. The sky's +/// level counts for `SKY_SHARE`, and what the title left for at most `MOST` times the estimate. +const AMBIENT_FILL_R9G9B9E5_HLSL: &str = r#" +RWTexture2D out_uav : register(u0); float3 unpack_r9g9b9e5(uint v) { - float scale = exp2(float(v >> 27) - 24.0); - return float3(float(v & 511u), float((v >> 9) & 511u), float((v >> 18) & 511u)) * scale; + return float3(float(v & 511u), float((v >> 9) & 511u), float((v >> 18) & 511u)) * exp2(float(v >> 27) - 24.0); } uint pack_r9g9b9e5(float3 c) { c = clamp(c, 0.0, 65408.0); float top = max(c.r, max(c.g, c.b)); int e = clamp(int(floor(log2(max(top, 1e-9)))) + 16, 0, 31); - float inv_s = exp2(float(24 - e)); - uint3 m = min(uint3(floor(c * inv_s + 0.5)), uint3(511u, 511u, 511u)); + float scale = exp2(float(24 - e)); + if (top * scale >= 511.5) { + e = min(e + 1, 31); + scale = exp2(float(24 - e)); + } + uint3 m = min(uint3(c * scale + 0.5), uint3(511u, 511u, 511u)); return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); } -// The light the frame before sent out around this texel: 64x36 cells from `sky_level[2]` on, -// their slow mean at `sky_level[1]` (its fourth part 0: nothing kept yet, no light). -float3 frame_light(uint2 tid) { - float4 mean = sky_level[1]; - if (!(mean.a > 0.0)) { - return float3(0.0, 0.0, 0.0); - } +// The light the frame before sent out around this texel on the screen: 64x36 cells, their slow +// mean a fifth of it. +float3 frame_light(uint2 tid, float3 mean) { float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; int2 g0 = int2(floor(g)); float2 f = g - float2(g0); @@ -848,65 +979,87 @@ float3 frame_light(uint2 tid) { int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(63, 35)); float wx = (k & 1) ? f.x : 1.0 - f.x; float wy = (k >> 1) ? f.y : 1.0 - f.y; - sum += wx * wy * sky_level[2 + q.y * 64 + q.x].rgb; - } - float3 found = lerp(sum, mean.rgb, 0.2); - return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); -} -float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { - float d0 = depth_tex.Load(int3(dc, 0)); - if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { - return 1.0; + sum += wx * wy * sky_level[CELL_AT + q.y * 64 + q.x].rgb; } - float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); - float base_ang = ign * 6.2831853; - float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); - float inv_d0 = 1.0 / max(d0, 1e-5); - float occ = 0.0; - [unroll] - for (uint i = 0; i < 4; ++i) { - float ang = base_ang + float(i) * 0.78539816; - float t = frac(ign * 0.61803399 + (float(i) + 0.5) * 0.25); - float rad = clamp(max_rad * sqrt(t), 1.5, 16.0); - int2 ofs = int2(int(round(cos(ang) * rad)), int(round(sin(ang) * rad))); - float dp = depth_tex.Load(int3(clamp(dc + ofs, int2(0, 0), maxc), 0)); - float dn = depth_tex.Load(int3(clamp(dc - ofs, int2(0, 0), maxc), 0)); - float rp = (dp - d0) * inv_d0; - float rn = (dn - d0) * inv_d0; - float wp = (isfinite(dp) && dp > 1e-6 && dp < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rp))) : 0.0; - float wn = (isfinite(dn) && dn > 1e-6 && dn < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rn))) : 0.0; - float conc = max(0.0, rp * wp + rn * wn); - occ += saturate((conc - 0.003) * 4.5); - } - return saturate(1.0 - ao_strength * saturate(occ * 0.25)); + return lerp(sum, mean, 0.2); } [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { if (tid.x >= width || tid.y >= height) return; - float3 raw_amb = ((sky_ready & 1u) != 0u) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); - float3 amb = max(clamp(raw_amb, 0.0, 0.65), frame_light(tid.xy)); - float ao = 1.0; - if (has_depth != 0 && depth_w > 0 && depth_h > 0) { - int2 dc = int2( - int(min((tid.x * depth_w) / max(width, 1u), depth_w - 1)), - int(min((tid.y * depth_h) / max(height, 1u), depth_h - 1)) - ); - int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); - ao = horizon_crease_ao(tid.xy, dc, maxc); - } - float3 amb_ao = amb * ao; - float3 existing = unpack_r9g9b9e5(out_uav[tid.xy]); - if (!all(isfinite(existing)) || (sky_ready & 2u) == 0u) existing = float3(0.0, 0.0, 0.0); - if (existing.g < 0.5 * min(existing.r, existing.b) && max(existing.r, existing.b) > 0.02) { - existing = float3(0.0, 0.0, 0.0); - } - float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.02); - float cap_lum = 6.0 * amb_lum; - float cur_lum = dot(existing, float3(0.2126, 0.7152, 0.0722)); - if (cur_lum > cap_lum) { - existing *= (cap_lum / max(cur_lum, 1e-6)); - } - out_uav[tid.xy] = pack_r9g9b9e5(max(existing, amb_ao)); + int2 p = int2(tid.xy); + float2 size = float2(width, height); + float3 sky = ((sky_ready & 1u) != 0u) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + sky = all(isfinite(sky)) ? clamp(sky, 0.0, 0.65) : float3(0.0, 0.0, 0.0); + float4 mean = sky_level[1]; + bool kept = mean.a > 0.0 && all(isfinite(mean.rgb)); + float3 found = float3(0.0, 0.0, 0.0); + float open = 1.0; + // (`XCL_AMBIENT_SPLIT=1`: bit 1 of has_depth – only the left half is made in space, to compare) + bool in_space = (has_depth & 1u) != 0u && depth_w > 0u && depth_h > 0u && ((has_depth & 2u) == 0u || tid.x * 2u < width); + if (in_space) { + float3 c = seen(p, size); + float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size); + float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size); + float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c; + float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c; + float3 n = normalize(cross(dy, dx) + float3(0.0, 0.0, -1e-9)); + if (dot(n, c) > 0.0) n = -n; + // How open it is: what stands over the surface within 0.6 m shades it. + const float radius = 0.6; + float px = min(radius * size.y / (2.0 * 0.45 * c.z), 128.0); + float noise = frac(52.9829189 * frac(dot(float2(p), float2(0.06711056, 0.00583715)))); + if (ao_strength > 0.0 && px >= 1.5 && c.z < 400.0) { + float over_sum = 0.0; + [loop] + for (int i = 0; i < 12; ++i) { + float a = float(i) * 2.399963 + noise * 6.2831853; + float2 o = float2(cos(a), sin(a)) * (sqrt((float(i) + 0.5) / 12.0) * px); + float3 v = seen(p + int2(round(o)), size) - c; + float vv = dot(v, v); + float over = dot(v, n) - 0.004 * c.z - 0.005; + over_sum += max(over, 0.0) / sqrt(vv + 1e-6) * saturate(1.0 - vv / (radius * radius)); + } + open = saturate(1.0 - ao_strength * 2.0 * over_sum / 12.0); + } + if (kept) { + // Between the four points around, those at its own depth first; which four is + // dithered a little. + float2 g = (float2(p) + 0.5) / size * float2(PX, PY) - 0.5 + (noise - 0.5) * 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float4 sr = float4(0.0, 0.0, 0.0, 0.0), sg = float4(0.0, 0.0, 0.0, 0.0), sb = float4(0.0, 0.0, 0.0, 0.0); + float sum = 0.0; + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float z = seen(int2((float2(q) + 0.5) * size / float2(PX, PY)), size).z; + float2 bw = float2((k & 1) ? f.x : 1.0 - f.x, (k >> 1) ? f.y : 1.0 - f.y); + float w = (bw.x * bw.y + 1e-3) / (0.02 + abs(z - c.z) / c.z); + uint at0 = POINT_AT + (q.y * PX + q.x) * 3; + sr += w * sky_level[at0]; + sg += w * sky_level[at0 + 1]; + sb += w * sky_level[at0 + 2]; + sum += w; + } + float3 all_ = float3(sr.w, sg.w, sb.w) / sum; + found = all_ + 1.2 * float3(dot(sr.xyz, n), dot(sg.xyz, n), dot(sb.xyz, n)) / sum; + found = clamp(found, 0.2 * all_, 2.5 * all_); + found = lerp(found, mean.rgb, 0.2); + } + } else if (kept) { + found = frame_light(tid.xy, mean.rgb); + } + found = all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); + found = max(found, sky * SKY_SHARE) * open; + float3 was = unpack_r9g9b9e5(out_uav[p]); + if (!all(isfinite(was)) || (sky_ready & 2u) == 0u) was = float3(0.0, 0.0, 0.0); + // Magenta (green far below red and blue) is what the probes' memory held, not light. + if (was.g < 0.5 * min(was.r, was.b) && max(was.r, was.b) > 0.02) was = float3(0.0, 0.0, 0.0); + // What the program left counts as far as it can be true: the sky's light outdoors, not the + // blocks of other memory. + float top = max(dot(found, LUMA) * MOST, 1e-6); + was *= min(1.0, top / max(dot(was, LUMA), 1e-6)); + out_uav[p] = pack_r9g9b9e5(max(was, found)); } "#; @@ -992,14 +1145,14 @@ void main(uint3 tid : SV_DispatchThreadID) { "#; const REFLECT_CLAMP_HLSL: &str = r#" -Texture2D _unused : register(t0); +ByteAddressBuffer indirect_args : register(t0); RWTexture2D out_uav : register(u0); RWStructuredBuffer sky_level : register(u1); cbuffer C : register(b0) { uint width; uint height; - uint _u2; - uint _u3; + uint indirect_flag; + uint indirect_off; uint _u4; float reflect_scale; float _p6; @@ -1007,17 +1160,92 @@ cbuffer C : register(b0) { }; [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { + if (indirect_flag != 0u && any(indirect_args.Load3(indirect_off) == 0u)) return; if (tid.x >= width || tid.y >= height) return; float4 cur = out_uav[tid.xy]; float3 rgb = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + // Magenta (green far below red and blue) is what the probes' memory held, not light. + if (rgb.g < 0.5 * min(rgb.r, rgb.b) && max(rgb.r, rgb.b) > 0.02) rgb = float3(0.0, 0.0, 0.0); float3 cap = max(sky_level[0].rgb * reflect_scale, float3(0.005, 0.005, 0.005)); out_uav[tid.xy] = float4(min(rgb, cap), isfinite(cur.a) ? cur.a : 1.0); } "#; -/// Lightweight 3D froxel luminance cap for `CS_AccumulateLocalLightInscatteringVolume`: smoothly -/// compresses over-bright indoor volumetric haze against the settled sky luminance * `air_scale` -/// while preserving sky scatter chromaticity through windows. +/// Hue-preserving reflection luminance cap for `CS_TemporalResolve2_Opaque` / +/// `CS_TemporalResolve1_Alpha` (`R9G9B9E5` packed in `R32_UINT`), with optional GPU indirect-args +/// zero-group gating so empty indirect dispatches leave the texture untouched. +const REFLECT_CLAMP_R9_HLSL: &str = r#" +ByteAddressBuffer indirect_args : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint indirect_flag; + uint indirect_off; + uint _u4; + float reflect_scale; + float _p6; + float _p7; +}; +float3 unpack_r9g9b9e5(uint v) { + float e = exp2(float(v >> 27) - 24.0); + return float3(float(v & 0x1FFu), float((v >> 9) & 0x1FFu), float((v >> 18) & 0x1FFu)) * e; +} +uint pack_r9g9b9e5(float3 rgb) { + rgb = clamp(rgb, 0.0, 65408.0); + float m = max(rgb.r, max(rgb.g, rgb.b)); + int e = clamp(int(floor(log2(max(m, 1e-9)))) + 16, 0, 31); + float s = exp2(float(24 - e)); + if (m * s >= 511.5) { + e = min(e + 1, 31); + s = exp2(float(24 - e)); + } + uint3 q = min(uint3(rgb * s + 0.5), uint3(511u, 511u, 511u)); + return q.r | (q.g << 9) | (q.b << 18) | (uint(e) << 27); +} +float3 frame_light(uint2 tid) { + float4 mean = sky_level[1]; + if (mean.a <= 0.0 || !all(isfinite(mean.rgb))) return float3(0.0, 0.0, 0.0); + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(64.0, 36.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (uint k = 0u; k < 4u; ++k) { + int2 q = clamp(g0 + int2(int(k & 1u), int(k >> 1)), int2(0, 0), int2(63, 35)); + float wx = (k & 1u) != 0u ? f.x : 1.0 - f.x; + float wy = (k >> 1) != 0u ? f.y : 1.0 - f.y; + sum += wx * wy * sky_level[2 + q.y * 64 + q.x].rgb; + } + float3 found = lerp(sum, mean.rgb, 0.2); + return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (indirect_flag != 0u && any(indirect_args.Load3(indirect_off) == 0u)) return; + if (tid.x >= width || tid.y >= height) return; + float3 cur = unpack_r9g9b9e5(out_uav[tid.xy]); + if (!all(isfinite(cur))) cur = float3(0.0, 0.0, 0.0); + cur = max(cur, 0.0); + // Magenta (green far below red and blue) is what the probes' memory held, not light. + if (cur.g < 0.5 * min(cur.r, cur.b) && max(cur.r, cur.b) > 0.02) cur = float3(0.0, 0.0, 0.0); + float3 amb = max(clamp(sky_level[0].rgb, 0.0, 0.65), frame_light(tid.xy)); + float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.005); + float cap_lum = max(amb_lum * reflect_scale, 0.005); + float cur_lum = dot(cur, float3(0.2126, 0.7152, 0.0722)); + if (cur_lum > cap_lum) { + cur *= (cap_lum / max(cur_lum, 1e-6)); + } + out_uav[tid.xy] = pack_r9g9b9e5(cur); +} +"#; + +/// The air's scattered light after `CS_AccumulateLocalLightInscatteringVolume`: no more than +/// `air_scale` times the light around – of the room as the last seconds showed it, and of the +/// surface seen in this direction (towards a window the air outside may be as bright as the sky +/// is); what is brighter is scaled down with its colour kept. Before any +/// light is kept or gathered, the sky's level stands for it. const AIR_CAP_HLSL: &str = r#" Texture2D _unused : register(t0); RWTexture3D vol_uav : register(u0); @@ -1032,21 +1260,21 @@ cbuffer C : register(b0) { float _p6; float _p7; }; +static const float3 LUMA = float3(0.2126, 0.7152, 0.0722); [numthreads(8, 8, 2)] void main(uint3 tid : SV_DispatchThreadID) { if (tid.x >= width || tid.y >= height || tid.z >= depth) return; float4 cur = vol_uav[tid]; float3 rgb = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); - float sky_lum = max(sky_level[0].w, 0.01); - float cap = max(sky_lum * air_scale, 0.01); - float lum = dot(rgb, float3(0.2126, 0.7152, 0.0722)); - if (lum > cap) { - float excess = lum - cap; - float rolled = cap + excess / (1.0 + excess / max(cap, 1e-4)); - rgb *= (rolled / max(lum, 1e-6)); - } - float ch_cap = cap * 2.0; - rgb = min(rgb, float3(ch_cap, ch_cap, ch_cap)); + float4 mean = sky_level[1]; + float room = (mean.a > 0.0 && all(isfinite(mean.rgb))) ? dot(mean.rgb, LUMA) : max(sky_level[0].w, 0.01); + uint2 q = min(uint2((float2(tid.xy) + 0.5) / float2(width, height) * float2(160.0, 90.0)), uint2(159u, 89u)); + uint at0 = 4610 + (q.y * 160 + q.x) * 3; + float there = dot(float3(sky_level[at0].w, sky_level[at0 + 1].w, sky_level[at0 + 2].w), LUMA); + if (!(there > 0.0) || !isfinite(there)) there = room; + float cap = max(air_scale * lerp(room, there, float(tid.z) / float(max(depth, 1u))), 0.002); + float lum = dot(rgb, LUMA); + if (lum > cap) rgb *= cap / lum; vol_uav[tid] = float4(rgb, isfinite(cur.a) ? cur.a : 0.0); } "#; @@ -1055,8 +1283,11 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let reduce_bc = compile_cs_sm5(SKY_REDUCE_HLSL)?; let fill_bc = compile_cs_sm5(AMBIENT_FILL_HLSL)?; let fill_write_bc = compile_cs_sm5(AMBIENT_FILL_WRITE_HLSL)?; - let fill_r9_bc = compile_cs_sm5(AMBIENT_FILL_R9G9B9E5_HLSL)?; + let fill_r9_bc = compile_cs_sm5(&light_hlsl(AMBIENT_FILL_R9G9B9E5_HLSL))?; + let place_bc = compile_cs_sm5(&light_hlsl(LIGHT_PLACE_HLSL))?; + let gather_bc = compile_cs_sm5(&light_hlsl(LIGHT_GATHER_HLSL))?; let reflect_bc = compile_cs_sm5(REFLECT_CLAMP_HLSL)?; + let reflect_r9_bc = compile_cs_sm5(REFLECT_CLAMP_R9_HLSL)?; let air_bc = compile_cs_sm5(AIR_CAP_HLSL)?; let keep_bc = compile_cs_sm5(FRAME_KEEP_HLSL)?; let mean_bc = compile_cs_sm5(FRAME_MEAN_HLSL)?; @@ -1156,7 +1387,10 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let fill_pso = make_cs(&fill_bc, "xcl ambient fill")?; let fill_write_pso = make_cs(&fill_write_bc, "xcl ambient fill_write")?; let fill_r9_pso = make_cs(&fill_r9_bc, "xcl ambient fill_r9")?; + let place_pso = make_cs(&place_bc, "xcl ambient light_place")?; + let gather_pso = make_cs(&gather_bc, "xcl ambient light_gather")?; let reflect_pso = make_cs(&reflect_bc, "xcl ambient reflect_clamp")?; + let reflect_r9_pso = make_cs(&reflect_r9_bc, "xcl ambient reflect_clamp_r9")?; let air_pso = make_cs(&air_bc, "xcl ambient air_cap")?; let keep_pso = make_cs(&keep_bc, "xcl ambient frame_keep")?; let mean_pso = make_cs(&mean_bc, "xcl ambient frame_mean")?; @@ -1208,6 +1442,19 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { }, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, )?; + let dummy_indirect = make_res( + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )?; let heap_desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, @@ -1230,13 +1477,17 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { fill_pso, fill_write_pso, fill_r9_pso, + place_pso, + gather_pso, reflect_pso, + reflect_r9_pso, air_pso, keep_pso, mean_pso, sky_copy, sky_level, dummy_depth, + dummy_indirect, heap, heap_cpu, heap_gpu, @@ -1250,14 +1501,13 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { unsafe fn get_device(dev: &ID3D12Device) -> Option> { let key = dev.as_raw() as usize; - { - let g = DEVICES.lock().unwrap(); - if let Some(entry) = g.as_ref().and_then(|m| m.get(&key)) { - return entry.clone(); - } + let mut g = DEVICES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + if let Some(entry) = map.get(&key) { + return entry.clone(); } let built = build_device(dev).map(std::sync::Arc::new); - DEVICES.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, built.clone()); + map.insert(key, built.clone()); built } @@ -1388,7 +1638,7 @@ const MAX_SLOT_INDEX: u32 = 2_000_000; /// Decode a CBV / buffer `V#` descriptor (`gpu::desc::cbv_words` / `buffer_words`) into /// `(va, byte_len)` if it is a readable buffer descriptor (`w3 >> 28 < 8` and dst_sel `0xFAC`). -fn decode_cbv_vsharp(w: [u32; 4]) -> Option<(usize, usize)> { +pub(super) fn decode_cbv_vsharp(w: [u32; 4]) -> Option<(usize, usize)> { if (w[3] >> 28) >= 8 || (w[3] & 0xFFF) != 0xFAC { return None; } @@ -1453,7 +1703,7 @@ unsafe fn scan_cbv_indices_with( /// Scan up to `max_bytes` (capped at 2048 B) of readable constant-buffer memory at `va` in /// page-bounded chunks and feed candidate bindless descriptor indices `< MAX_SLOT_INDEX` into `push_idx`. -unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMut(u32)) { +pub(super) unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMut(u32)) { scan_cbv_indices_with(va, max_bytes, resolve_cbv_va, push_idx); } @@ -1596,7 +1846,67 @@ unsafe fn find_dispatch_views( check_slot(addr); } } - (uav_hit.map(|(_, r, f, w, h, d)| (r, f, w, h, d)), depth_hit, tables.len(), indices.len(), table_cbvs) + let mut uav = uav_hit.map(|(_, r, f, w, h, d)| (r, f, w, h, d)); + if role == PassRole::TemporalResolve && !want_3d { + // The resolve's own slots: its + // light at dword 176 of root parameter 1's table, the depth it reads at dword 464 of + // parameter 0's. The program has several R32_UINT outputs of the picture's size and reads + // other pictures of it besides the depth: a guess by format alone can take the wrong one. + let pinned = |param: usize, dword: usize| -> Option<(ViewEntry, D3D12_RESOURCE_DESC)> { + let Some(&Param::Table { at }) = layout.params.get(param) else { return None }; + let t = word(at as usize).filter(|&t| t != 0)?; + let addr = u.base().checked_add(t as usize)?.checked_add(4 * dword)?; + if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { + return None; + } + let (w0, w3) = ((addr as *const u32).read_unaligned(), ((addr + 12) as *const u32).read_unaligned()); + if (w3 >> 28) < 8 { + return None; + } + // (only views of the light's and of depth formats are noted here: any other picture + // is named by the heap's own record of its index, read in a format of its resource's) + let noted = vs.by_addr.get(&addr).or_else(|| (w0 != 0).then(|| vs.by_idx.get(&w0)).flatten()).copied(); + let named = || match super::console_heap::named_by_index(w0) { + 0 | super::console_heap::GONE => None, + res => Some(ViewEntry { res, fmt: 0, is_uav: false }), + }; + let mut ve = noted.or_else(named)?; + let ptr = ve.res as *mut c_void; + let rd = ID3D12Resource::from_raw_borrowed(&ptr)?.GetDesc(); + if ve.fmt == 0 { + ve.fmt = match rd.Format.0 { + 39..=41 => 41, + 19..=21 => 21, + 44..=46 => 46, + 53 | 55 | 56 => 56, + f => f, + }; + } + (rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && rd.DepthOrArraySize == 1 && rd.SampleDesc.Count == 1).then_some((ve, rd)) + }; + let light = pinned(1, 176).filter(|(ve, _)| ve.is_uav && ve.fmt == 42); + if let Some((ve, rd)) = &light { + uav = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height, 1)); + } + // (the depth is the picture's size, or it is another picture: none then, and the fill is + // made on the screen) + let same_size = |w: u64, h: u32| uav.is_some_and(|(_, _, uw, uh, _)| w == uw as u64 && h == uh); + let depth = pinned(0, 464).filter(|(ve, rd)| !ve.is_uav && matches!(ve.fmt, 21 | 41 | 46 | 54 | 56) && same_size(rd.Width, rd.Height)); + let found = depth_hit.filter(|&(_, f, w, h)| matches!(f, 20 | 21 | 39 | 40 | 41 | 46 | 55 | 56) && same_size(w as u64, h)); + static SLOTS: AtomicU64 = AtomicU64::new(0); + if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: the resolve's light is {} ({:?}), its depth {} ({:?}; the first picture it reads: {:?})", + if light.is_some() { "the one in its slot" } else { "found by its format" }, + uav.map(|(r, f, w, h, _)| (r, f, w, h)), + if depth.is_some() { "the one in its slot" } else if found.is_some() { "found by its format" } else { "not found" }, + depth.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, rd.Width, rd.Height)), + depth_hit + ); + } + depth_hit = depth.map(|(ve, rd)| (ve.res, ve.fmt, rd.Width as u32, rd.Height)).or(found); + } + (uav, depth_hit, tables.len(), indices.len(), table_cbvs) } /// Called right after a translated compute dispatch completes: when RT is gated off and a sky @@ -1611,12 +1921,20 @@ pub(super) unsafe fn after_compute_dispatch( layout: Option<&Layout>, args: &[u8], view_heap_base: u32, + indirect_args: Option<(usize, u32)>, ) { if !has_compute_psos() || !active() { return; } let Some(role) = role_of(pso_resolved) else { return }; - if !matches!(role, PassRole::TemporalResolve | PassRole::ReflectionHistory | PassRole::InscatteringVolume | PassRole::Radiance) { + if !matches!( + role, + PassRole::TemporalResolve + | PassRole::ReflectionHistory + | PassRole::ReflectionResolve + | PassRole::InscatteringVolume + | PassRole::Radiance + ) { return; } let cfg = config(); @@ -1662,6 +1980,8 @@ pub(super) unsafe fn after_compute_dispatch( let want_3d = role == PassRole::InscatteringVolume; let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(role, layout, args, groups, view_heap_base, want_3d); + // (`XCL_AMBIENT_SPACE=0`: no depth, the light is made on the screen) + let depth_opt = depth_opt.filter(|_| space_light()); let Some((uav_res, uav_fmt, w, h, d)) = uav_opt else { static MISS: AtomicU64 = AtomicU64::new(0); if MISS.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1692,6 +2012,8 @@ pub(super) unsafe fn after_compute_dispatch( (PassRole::TemporalResolve, Some((r, f, dw, dh))) => (r as *mut c_void, DXGI_FORMAT(f), dw, dh, 1u32), _ => (ad.dummy_depth.as_raw(), DXGI_FORMAT_R32_FLOAT, 1, 1, 0u32), }; + let is_reflect_role = matches!(role, PassRole::ReflectionHistory | PassRole::ReflectionResolve); + let gated_indirect = if is_reflect_role { indirect_args } else { None }; let depth_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: depth_fmt, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, @@ -1724,11 +2046,35 @@ pub(super) unsafe fn after_compute_dispatch( Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_ELEMENTS, StructureByteStride: 16, ..Default::default() }, }, }; - create_srv(dev_raw, depth_raw, &depth_srv, cpu0 as usize); + if is_reflect_role { + let (buf_raw, first_elem) = match gated_indirect { + Some((b, off)) => (b as *mut c_void, (off / 4) as u64), + None => (ad.dummy_indirect.as_raw(), 0u64), + }; + let raw_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: first_elem, + NumElements: 4, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + create_srv(dev_raw, buf_raw, &raw_srv, cpu0 as usize); + } else { + create_srv(dev_raw, depth_raw, &depth_srv, cpu0 as usize); + } create_uav(dev_raw, uav_res as *mut c_void, std::ptr::null_mut(), &out_uav_desc, (cpu0 + inc) as usize); create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); uav_barrier(list, uav_res); + if let Some((arg_buf, _)) = gated_indirect { + list_x::transition(list, arg_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } let heap_raw = ad.heap.as_raw() as usize; let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); @@ -1738,6 +2084,7 @@ pub(super) unsafe fn after_compute_dispatch( let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 35)); let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); + let indirect_flag = gated_indirect.is_some() as u32; let (pso, consts, disp) = match role { PassRole::TemporalResolve => ( if uav_fmt == 42 { @@ -1747,12 +2094,17 @@ pub(super) unsafe fn after_compute_dispatch( } else { ad.fill_write_pso.as_raw() }, - [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), sky_ready as u32 | (keeps_title_light() as u32) << 1, cfg.least.to_bits()], + [w, h, depth_w, depth_h, has_depth | (has_depth & split_screen() as u32) << 1, cfg.ao.to_bits(), sky_ready as u32 | (keeps_title_light() as u32) << 1, PRE_SKY_FALLBACK.to_bits()], (w.div_ceil(8), h.div_ceil(8), 1), ), PassRole::ReflectionHistory => ( ad.reflect_pso.as_raw(), - [w, h, 0, 0, 0, cfg.reflect.to_bits(), 0, 0], + [w, h, indirect_flag, 0, 0, cfg.reflect.to_bits(), 0, 0], + (w.div_ceil(8), h.div_ceil(8), 1), + ), + PassRole::ReflectionResolve => ( + ad.reflect_r9_pso.as_raw(), + [w, h, indirect_flag, 0, 0, cfg.reflect.to_bits(), 0, 0], (w.div_ceil(8), h.div_ceil(8), 1), ), PassRole::InscatteringVolume => ( @@ -1774,8 +2126,27 @@ pub(super) unsafe fn after_compute_dispatch( set_cs_consts(list, 0, 8, consts.as_ptr(), 0); set_cs_table(list, 1, gpu0); set_cs_table(list, 2, gpu0 + inc); + if role == PassRole::TemporalResolve && uav_fmt == 42 && has_depth != 0 { + // where the cells are seen, then their light gathered at the points: what the fill reads + let level = ad.sky_level.as_raw() as usize; + let passes = [ + (ad.place_pso.as_raw(), FRAME_CELLS.0.div_ceil(8), FRAME_CELLS.1.div_ceil(4)), + (ad.gather_pso.as_raw(), GATHER_POINTS.0.div_ceil(8), GATHER_POINTS.1.div_ceil(2)), + ]; + for (pass, gx, gy) in passes { + super::dred::mark_pipeline(list, pass as usize, pass as usize); + set_pso(list, pass); + dispatch(list, gx, gy, 1); + uav_barrier(list, level); + } + super::dred::mark_pipeline(list, pso as usize, pso as usize); + set_pso(list, pso); + } dispatch(list, disp.0, disp.1, disp.2); uav_barrier(list, uav_res); + if let Some((arg_buf, _)) = gated_indirect { + list_x::transition(list, arg_buf, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + } if role == PassRole::Radiance { // the cells' slow mean, by the clock let level = ad.sky_level.as_raw() as usize; @@ -1904,13 +2275,18 @@ mod tests { assert!(compile_cs_sm5(SKY_REDUCE_HLSL).is_some(), "SKY_REDUCE_HLSL failed D3DCompile"); assert!(compile_cs_sm5(AMBIENT_FILL_HLSL).is_some(), "AMBIENT_FILL_HLSL failed D3DCompile"); assert!(compile_cs_sm5(AMBIENT_FILL_WRITE_HLSL).is_some(), "AMBIENT_FILL_WRITE_HLSL failed D3DCompile"); - assert!(compile_cs_sm5(AMBIENT_FILL_R9G9B9E5_HLSL).is_some(), "AMBIENT_FILL_R9G9B9E5_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(&light_hlsl(AMBIENT_FILL_R9G9B9E5_HLSL)).is_some(), "AMBIENT_FILL_R9G9B9E5_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(&light_hlsl(LIGHT_PLACE_HLSL)).is_some(), "LIGHT_PLACE_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(&light_hlsl(LIGHT_GATHER_HLSL)).is_some(), "LIGHT_GATHER_HLSL failed D3DCompile"); assert!(compile_cs_sm5(REFLECT_CLAMP_HLSL).is_some(), "REFLECT_CLAMP_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(REFLECT_CLAMP_R9_HLSL).is_some(), "REFLECT_CLAMP_R9_HLSL failed D3DCompile"); + assert_eq!(classify_cs(b"ILDN\0CS_TemporalResolve2_Opaque_1234\0"), Some(PassRole::ReflectionResolve)); + assert_eq!(classify_cs(b"ILDN\0CS_TemporalResolve1_Alpha_5678\0"), Some(PassRole::ReflectionResolve)); assert!(compile_cs_sm5(AIR_CAP_HLSL).is_some(), "AIR_CAP_HLSL failed D3DCompile"); assert!(compile_cs_sm5(FRAME_KEEP_HLSL).is_some(), "FRAME_KEEP_HLSL failed D3DCompile"); assert!(compile_cs_sm5(FRAME_MEAN_HLSL).is_some(), "FRAME_MEAN_HLSL failed D3DCompile"); // the cells the fills read are the cells the keeping writes, and the mean sums all of them - assert_eq!((FRAME_CELLS, LEVEL_ELEMENTS), ((64, 36), 2 + 2304)); + assert_eq!((FRAME_CELLS, GATHER_POINTS, LEVEL_ELEMENTS), ((64, 36), (160, 90), 2 + 2 * 2304 + 3 * 14400)); } #[test] @@ -1951,7 +2327,7 @@ mod tests { let def = Config::default(); assert!((def.settle_ms - 250.0).abs() < 1e-6); - assert!((def.air - 0.0).abs() < 1e-6); + assert!((def.air - 1.5).abs() < 1e-6 && (def.most - 2.0).abs() < 1e-6 && (def.sky - 0.35).abs() < 1e-6); // First capture or settle_ms == 0 snaps immediately; subsequent samples follow 1 - exp(-dt/tau). assert_eq!(settle_alpha(0.016, 250.0, true), 1.0); diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7076ff743c..bf1c9eba20 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -547,6 +547,47 @@ pub(super) fn bound_pso(this: *mut c_void) -> usize { with(this, |s| s.pso) } +/// `XCL_TRACE_SLOT=`: the image views at that place of the descriptor tables of graphics +/// draws – each resource once (the first 64), with its description and the view's words. Places +/// that hold no image view (another table's layout) are passed over. +unsafe fn trace_table_slot(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8], pso: usize) { + static WANT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let Some(dword) = *WANT.get_or_init(|| std::env::var("XCL_TRACE_SLOT").ok()?.trim().parse().ok()) else { return }; + let Some(layout) = layout else { return }; + for (param, p) in layout.params.iter().enumerate() { + let Param::Table { at } = *p else { continue }; + let Some(word) = args.get(at as usize..at as usize + 4) else { continue }; + let offset = u32::from_le_bytes(word.try_into().unwrap()) as usize; + if offset == 0 { + continue; + } + let mut slot = [0u8; 32]; + super::title_textures::copy_readable(u.base() + offset + 4 * dword, &mut slot); + let w: [u32; 8] = std::array::from_fn(|k| u32::from_le_bytes(slot[4 * k..4 * k + 4].try_into().unwrap())); + // (an image view: type 8 and up in the top bits of word 3; its index in word 0) + if w[3] >> 28 < 8 || w[0] == 0 || w[0] > 4 << 20 { + continue; + } + let res = super::console_heap::named_by_index(w[0]); + static SEEN: Mutex>> = Mutex::new(None); + let mut g = SEEN.lock().unwrap(); + let seen = g.get_or_insert_with(Default::default); + if seen.len() >= 64 || !seen.insert((param, res)) { + continue; + } + let desc = (res != 0 && res != super::console_heap::GONE) + .then(|| { + let ptr = res as *mut c_void; + ID3D12Resource::from_raw_borrowed(&ptr).map(|r| r.GetDesc()) + }) + .flatten() + .map(|d| (d.Dimension.0, d.Width, d.Height, d.DepthOrArraySize, d.MipLevels, d.Format.0, d.Flags.0)); + crate::xlog_info!( + "D3D12.X: XCL_TRACE_SLOT: parameter {param} dword {dword} of pipeline {pso:#x}: resource {res:#x} (dimension, width, height, depth, mips, format, flags) {desc:?}, view words {w:08x?}" + ); + } +} + /// `XCL_DUMP_TARGETS`: the resources the first 16 slots of each descriptor table of `this`'s /// graphics arguments name, each once (as `trace_reads_of_watched` reads them). pub(super) fn table_resources(this: *mut c_void) -> Vec { @@ -573,6 +614,103 @@ fn table_resources_of(this: *mut c_void, gfx: bool, slots: usize) -> Vec out } +/// Check the first 64 slots of each bound table. A texture descriptor copied as bytes still +/// samples the resource named by its heap index in word 0. +unsafe fn uncover_bound_tables(layout: Option<&Layout>, args: &[u8], u: &crate::gpu::uma::Uma) { + let Some(layout) = layout.filter(|_| super::title_textures::has_shadowed()) else { return }; + const TABLE_SLOTS: usize = 64; + let mut resources = Vec::new(); + for p in &layout.params { + let Param::Table { at } = *p else { continue }; + let at = at as usize; + let Some(word) = args.get(at..at + 4) else { continue }; + let offset = u32::from_le_bytes(word.try_into().unwrap()) as usize; + if offset == 0 { + continue; + } + let addr = u.base() + offset; + let mut table = [0u8; TABLE_SLOTS * 32]; + if u.in_committed_window(addr, table.len()) { + std::ptr::copy_nonoverlapping(addr as *const u8, table.as_mut_ptr(), table.len()); + } else { + super::title_textures::copy_readable(addr, &mut table); + } + for slot in table.chunks_exact(32) { + let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); + if slot[15] >> 4 < 8 || index == 0 { + continue; + } + let res = super::console_heap::named_by_index(index); + if res != 0 && res != super::console_heap::GONE && !resources.contains(&res) { + resources.push(res); + } + } + } + super::title_textures::uncover_drawn(&resources); +} + +/// A draw whose result is drawn once and kept (`pso_async::is_kept`: the title's bake of its +/// characters' skin and decorations) picks its source textures by their index in the shared +/// heap, from its constants, and names none in a table: `uncover_bound_tables` does not see +/// them. A source that is shadowed then (a newer placement lies over its memory) is not uploaded, +/// and the bake takes nothing from it – once, for the run: a head stays black. +/// So every word of the draw's root constants and constant buffers (root ones, and those in the +/// first 16 slots of its tables) that is the index of a shadowed texture makes that texture +/// active again, for the upload ahead of the list's submit. `XCL_BAKE_SOURCES=0` turns it off. +unsafe fn uncover_indexed(layout: Option<&Layout>, args: &[u8], u: &crate::gpu::uma::Uma) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_BAKE_SOURCES").map_or(true, |v| v.trim() != "0")) { + return; + } + let Some(layout) = layout.filter(|_| super::title_textures::has_shadowed()) else { return }; + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + let mut indices: Vec = Vec::new(); + let mut push = |v: u32| { + if v != 0 && v < 4 << 20 && indices.len() < 4096 { + indices.push(v); + } + }; + for p in &layout.params { + match *p { + Param::Constants { at, count } => (0..count.min(64) as usize).for_each(|k| push(word(at as usize + 4 * k))), + Param::Descriptor { at } => { + let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; + super::ambient::scan_cbv_indices(va, 2048, &mut push); + } + Param::Table { at } => { + let offset = word(at as usize) as usize; + if offset == 0 { + continue; + } + let mut table = [0u8; 16 * 32]; + super::title_textures::copy_readable(u.base() + offset, &mut table); + for slot in table.chunks_exact(32) { + let w: [u32; 4] = std::array::from_fn(|k| u32::from_le_bytes(slot[4 * k..4 * k + 4].try_into().unwrap())); + if let Some((va, len)) = super::ambient::decode_cbv_vsharp(w) { + super::ambient::scan_cbv_indices(va, len, &mut push); + } + } + } + } + } + indices.sort_unstable(); + indices.dedup(); + let resources: Vec = indices.iter().map(|&i| super::console_heap::named_by_index(i)).filter(|&r| r != 0 && r != super::console_heap::GONE).collect(); + let shadowed = super::title_textures::shadowed_among(&resources); + static DRAWS: AtomicU64 = AtomicU64::new(0); + static FOUND: AtomicU64 = AtomicU64::new(0); + let (n, found) = (DRAWS.fetch_add(1, Ordering::Relaxed) + 1, FOUND.fetch_add(shadowed as u64, Ordering::Relaxed) + shadowed as u64); + if shadowed != 0 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a bake's draw (#{n}) picks {} textures by index, {shadowed} of them shadowed: made active again for its upload ({found} so far)", + resources.len() + ); + } + if shadowed != 0 { + super::title_textures::uncover_drawn(&resources); + } +} + /// `XCL_CAPTURE_FRAME`: a draw or dispatch of the title's on `this` (`gfx`: with the graphics /// root arguments), with the root arguments, heaps and pipeline it has, until the call returns. pub(super) unsafe fn capture_work(this: *mut c_void, kind: impl FnOnce() -> super::capture::WorkKind, gfx: bool) -> super::capture::Guard { @@ -1895,6 +2033,10 @@ unsafe fn prepare_two_pass_stage(this: *mut c_void, real_mesh_pso: usize, tp: &s if pso == 0 { return Err(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" }.into()); } + if !compute_pass { + // Both passes use the same graphics root tables. + uncover_bound_tables(layout.as_deref(), &args, u); + } let w = |k: usize| super::real::uma_window_va(k).filter(|&v| v != 0).unwrap_or(first); Ok(StageBind { rs, pso, views: [va(io_at), res_va, w(0), w(1), w(2), w(3)] }) } @@ -2257,7 +2399,11 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: } } let plan = two_pass_plan(1, records, with(this, |s| s.record_open)); - run_two_pass_plan(this, list, &plan, &res_buf, res_va, cap, |_, compute, va| { + let mut first_rec_off = 0u64; + let passes = run_two_pass_plan(this, list, &plan, &res_buf, res_va, cap, |_, compute, va| { + if compute { + first_rec_off = va - res_va; + } bind_two_pass_stage(this, list, pso, &tp, va, compute)?; if compute { list.Dispatch(n, 1, 1); @@ -2265,7 +2411,11 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: pc_dm(this, n * tp.mesh_groups_per_record, 1, 1); } Ok(()) - }) + }); + if passes.is_ok() { + trace_record(list, pso, &tp, &res_buf, first_rec_off, None, 0, 0, Some((n, n * tp.mesh_groups_per_record))); + } + passes })(); super::gpu_times::after(this); match run { @@ -2303,6 +2453,497 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: pc_dm(this, x, y, z); } +/// `XCL_TRACE_ARGS=[,…]` (a diagnostic, with `XCL_TRACE_MS` set): the group counts +/// the GPU has in the arguments of two-pass indirect mesh draws with those mesh shaders. The +/// title's culling writes them on the GPU, so the CPU reads zeros when the draw is recorded: +/// one draw in four has its 12 bytes read back after its submit, and what came back is counted +/// a second later (draws with no groups / with groups), logged at powers of two. +unsafe fn trace_args(this: *mut c_void, pso: usize, commands_at: Option<(usize, usize)>, sig: usize) { + static WANT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let want = WANT.get_or_init(|| std::env::var("XCL_TRACE_ARGS").unwrap_or_default().split(',').filter_map(|h| u64::from_str_radix(h.trim(), 16).ok()).collect()); + if want.is_empty() { + return; + } + let Some(h) = super::real::pso_shaders(pso).map(|s| s.0).filter(|h| want.contains(h)) else { return }; + let (Some((p, n)), Some(msig)) = (commands_at, dispatch_mesh_sig_of(sig)) else { return }; + if n < msig.mesh_offset as usize + 12 { + return; + } + let at = p + msig.mesh_offset as usize; + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) % 4 != 0 { + return; + } + // (address, MS, when) + static PENDING: Mutex> = Mutex::new(std::collections::VecDeque::new()); + // MS → draws with no groups, with groups, with counts that are no counts (the memory was + // used again), the most groups in X, the last counts with groups + static STATS: Mutex>> = Mutex::new(None); + let now = std::time::Instant::now(); + let mut due = Vec::new(); + { + let mut q = PENDING.lock().unwrap(); + while q.front().is_some_and(|f| now.duration_since(f.2).as_millis() >= 250) { + due.push(q.pop_front().unwrap()); + } + if q.len() < 4096 { + q.push_back((at, h, now)); + } + } + for (a, ms, _) in due { + if !crate::gpu::shader::readable(a, 12) { + continue; + } + let g: [u32; 3] = std::array::from_fn(|i| std::ptr::read_unaligned((a + 4 * i) as *const u32)); + let mut st = STATS.lock().unwrap(); + let e = st.get_or_insert_with(HashMap::new).entry(ms).or_insert((0, 0, 0, 0, [0; 3])); + if g == [0, 1, 1] || g == [0, 0, 0] { + e.0 += 1; + } else if (1..=65_535).contains(&g[0]) && g[1] == 1 && g[2] == 1 { + e.1 += 1; + e.3 = e.3.max(g[0]); + e.4 = g; + } else { + e.2 += 1; + } + let total = e.0 + e.1 + e.2; + if total.is_power_of_two() || total % 128 == 0 { + crate::xlog_info!("trace args: MS {ms:016x}: {total} draws read back: {} with no groups, {} with groups (most in X: {}, last {:?}), {} unreadable", e.0, e.1, e.3, e.4, e.2); + } + } + super::list_x::trace_read_back(this as usize, at as u64, 12); +} + +/// `XCL_TRACE_RECORD=1` (with `XCL_TRACE_MS=`) or `XCL_TRACE_RECORD=all`: copies the +/// scaled indirect args (or direct group counts) and first two-pass record of sampled draws into +/// a small readback ring and logs per-MS vertex/primitive counts, positions, and indices. +#[allow(clippy::too_many_arguments)] +unsafe fn trace_record( + list: &ID3D12GraphicsCommandList, + pso: usize, + tp: &super::real::TwoPassPso, + res_buf: &ID3D12Resource, + res_off: u64, + scaled: Option<&ID3D12Resource>, + compute_args_off: u64, + mesh_args_off: u64, + direct_groups: Option<(u32, u32)>, +) { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| match std::env::var("XCL_TRACE_RECORD").as_deref().map(str::trim) { + Ok("1") => 1, + Ok(v) if v.eq_ignore_ascii_case("all") => 2, + _ => 0, + }); + if mode == 0 { + return; + } + let Some((ms_h, ps_h)) = super::real::pso_shaders(pso) else { return }; + if mode == 1 { + let Some(want) = super::real::trace_ms() else { return }; + if ms_h != want { + return; + } + } + const SLOTS: usize = 64; + const SLOT_BYTES: usize = 32768; + const HDR_BYTES: usize = 32; + struct Pending { + slot: usize, + ms_h: u64, + ps_h: u64, + draw_id: u64, + direct: Option<(u32, u32)>, + when: std::time::Instant, + max_v: u32, + max_p: u32, + vert_dw: usize, + copy_bytes: usize, + } + #[derive(Default)] + struct MsStat { + zero_g: u64, + nonzero_g: u64, + valid_rec: u64, + empty_rec: u64, + nan_v: u64, + zero_v: u64, + ndc_v: u64, + close_v: u64, + tot_v: u64, + ok_p: u64, + null_p: u64, + oob_p: u64, + logged_early: u32, + logged_late: u32, + ps_h: u64, + split: u32, + direct_draws: u64, + } + struct Ring { + dev: usize, + buf: ID3D12Resource, + ptr: usize, + free: [bool; SLOTS], + pending: std::collections::VecDeque, + stats: HashMap, + last_dump: std::time::Instant, + t0: std::time::Instant, + } + static RING: Mutex> = Mutex::new(None); + static DRAW_N: AtomicU64 = AtomicU64::new(0); + let draw_id = DRAW_N.fetch_add(1, Ordering::Relaxed); + if mode == 1 && draw_id % 4 != 0 { + return; + } + if mode == 2 && direct_groups.is_none() && draw_id % 16 != 0 { + return; + } + let mut dev_opt: Option = None; + if list.GetDevice(&mut dev_opt).is_err() { + return; + } + let Some(dev) = dev_opt else { return }; + let dev_key = dev.as_raw() as usize; + + let mut guard = RING.lock().unwrap(); + if guard.as_ref().is_none_or(|r| r.dev != dev_key) { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (SLOTS * SLOT_BYTES) as u64, + 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, + ..Default::default() + }; + let mut rb: Option = None; + if dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).is_err() { + return; + } + let Some(rb) = rb else { return }; + let mut p: *mut c_void = std::ptr::null_mut(); + if rb.Map(0, None, Some(&mut p)).is_err() || p.is_null() { + return; + } + let now = std::time::Instant::now(); + *guard = Some(Ring { + dev: dev_key, + buf: rb, + ptr: p as usize, + free: [true; SLOTS], + pending: std::collections::VecDeque::new(), + stats: HashMap::new(), + last_dump: now, + t0: now, + }); + } + let ring = guard.as_mut().unwrap(); + let now = std::time::Instant::now(); + // Drain completed slots (>= 400 ms old) + while ring.pending.front().is_some_and(|p| now.duration_since(p.when).as_millis() >= 400) { + let p = ring.pending.pop_front().unwrap(); + let base = (ring.ptr + p.slot * SLOT_BYTES) as *const u32; + let (cg, mg) = match p.direct { + Some((n, m)) => ([n, 1, 1], [m, 1, 1]), + None => ([*base, *base.add(1), *base.add(2)], [*base.add(4), *base.add(5), *base.add(6)]), + }; + let rec_ptr = base.add(HDR_BYTES / 4); + let rec_dwords = p.copy_bytes / 4; + let st = ring.stats.entry(p.ms_h).or_default(); + st.ps_h = p.ps_h; + if p.direct.is_some() { + st.direct_draws += 1; + } + if cg[0] == 0 { + st.zero_g += 1; + } else { + st.nonzero_g += 1; + let nv = if rec_dwords > 0 { *rec_ptr } else { 0 }; + let np = if rec_dwords > 1 { *rec_ptr.add(1) } else { 0 }; + let r2 = if rec_dwords > 2 { *rec_ptr.add(2) } else { 0 }; + let r3 = if rec_dwords > 3 { *rec_ptr.add(3) } else { 0 }; + if nv == 0 || np == 0 { + st.empty_rec += 1; + } else { + st.valid_rec += 1; + } + let nv_c = nv.min(p.max_v) as usize; + let np_c = np.min(p.max_p) as usize; + let mut finite = 0usize; + let mut nan_v = 0usize; + let mut zero_v = 0usize; + let mut w_pos = 0usize; + let mut onscreen = 0usize; + let mut close_w = 0usize; + let mut sample_verts = Vec::new(); + for vi in 0..nv_c { + let vo = crate::gpu::recomp::MESH_HEADER + vi * p.vert_dw; + if vo + 4 > rec_dwords { + break; + } + let pos_u = [*rec_ptr.add(vo), *rec_ptr.add(vo + 1), *rec_ptr.add(vo + 2), *rec_ptr.add(vo + 3)]; + let pos = pos_u.map(f32::from_bits); + if pos_u == [0, 0, 0, 0] { + zero_v += 1; + } + if pos.iter().all(|x| x.is_finite()) { + finite += 1; + if pos[3] > 0.0 { + w_pos += 1; + if pos[3] < 25.0 { + close_w += 1; + } + let (nx, ny, nz) = (pos[0] / pos[3], pos[1] / pos[3], pos[2] / pos[3]); + if nx.abs() <= 1.0 && ny.abs() <= 1.0 && (0.0..=1.0).contains(&nz) { + onscreen += 1; + } + } + } else { + nan_v += 1; + } + if vi < 3 { + sample_verts.push(format!("v{vi}=({:.2},{:.2},{:.3},{:.2})", pos[0], pos[1], pos[2], pos[3])); + } + } + let tri_base = crate::gpu::recomp::MESH_HEADER + p.max_v as usize * p.vert_dw; + let mut null_p = 0usize; + let mut oob_p = 0usize; + let mut ok_p = 0usize; + let mut sample_prims = Vec::new(); + for pi in 0..np_c { + if tri_base + pi >= rec_dwords { + break; + } + let raw = *rec_ptr.add(tri_base + pi); + let (i0, i1, i2, nul) = (raw & 0x1FF, (raw >> 10) & 0x1FF, (raw >> 20) & 0x1FF, raw >> 31); + if nul != 0 { + null_p += 1; + } else if i0 >= nv || i1 >= nv || i2 >= nv { + oob_p += 1; + } else { + ok_p += 1; + } + if pi < 3 { + sample_prims.push(format!("p{pi}=({i0},{i1},{i2},n={nul})")); + } + } + st.tot_v += nv_c as u64; + st.nan_v += nan_v as u64; + st.zero_v += zero_v as u64; + st.ndc_v += onscreen as u64; + st.close_v += close_w as u64; + st.ok_p += ok_p as u64; + st.null_p += null_p as u64; + st.oob_p += oob_p as u64; + + let elapsed_s = now.duration_since(ring.t0).as_secs(); + let detail = if mode == 1 { + st.logged_early < 16 || st.nonzero_g % 64 == 0 + } else if elapsed_s >= 175 { + st.logged_late < 2 || (nan_v > 0 && st.logged_late < 4) + } else { + st.logged_early < 1 || ((nv == 0 || np == 0 || nan_v > 0 || zero_v == nv_c) && st.logged_early < 3) + }; + if detail { + if elapsed_s >= 175 { + st.logged_late += 1; + } else { + st.logged_early += 1; + } + crate::xlog_info!( + "trace record: MS {:016x} PS {:016x} {} cg={cg:?} hdr=[nv={nv},np={np},{r2:#x},{r3:#x}] v(fin={finite},nan={nan_v},z={zero_v},w>0={w_pos},w<25={close_w},ndc={onscreen}/{nv_c}) p(ok={ok_p},null={null_p},oob={oob_p}/{np_c}) | {} | {}", + p.ms_h, + p.ps_h, + if p.direct.is_some() { "DIRECT" } else { "IND" }, + sample_verts.join(" "), + sample_prims.join(" ") + ); + } + } + ring.free[p.slot] = true; + } + + if mode == 2 && now.duration_since(ring.last_dump).as_secs() >= 25 { + ring.last_dump = now; + let mut rows: Vec<(u64, &MsStat)> = ring.stats.iter().map(|(&k, v)| (k, v)).collect(); + rows.sort_by_key(|&(_, s)| std::cmp::Reverse(s.zero_g + s.nonzero_g)); + crate::xlog_info!("trace record table ({} MS hashes):", rows.len()); + for (h, s) in rows { + crate::xlog_info!( + " MS {h:016x} PS {:016x} split={} dir={}: 0g={} nz={} (valid={} empty={}) v(tot={} ndc={} w<25={} nan={} zero={}) p(ok={} null={} oob={})", + s.ps_h, s.split, s.direct_draws, s.zero_g, s.nonzero_g, s.valid_rec, s.empty_rec, s.tot_v, s.ndc_v, s.close_v, s.nan_v, s.zero_v, s.ok_p, s.null_p, s.oob_p + ); + } + } + + ring.stats.entry(ms_h).or_default().split = tp.mesh_groups_per_record; + let Some(slot) = ring.free.iter().position(|&f| f) else { return }; + ring.free[slot] = false; + let slot_off = (slot * SLOT_BYTES) as u64; + let copy_bytes = ((tp.record.record_dwords() * 4).min(SLOT_BYTES - HDR_BYTES)) & !3; + let dst_u32 = (ring.ptr + slot * SLOT_BYTES) as *mut u32; + for i in 0..((HDR_BYTES + copy_bytes.min(64)) / 4) { + *dst_u32.add(i) = 0xDEAD_BEEF; + } + let rb = ring.buf.clone(); + ring.pending.push_back(Pending { + slot, + ms_h, + ps_h, + draw_id, + direct: direct_groups, + when: now, + max_v: tp.record.max_vertices, + max_p: tp.record.max_primitives, + vert_dw: tp.record.vert_dwords(), + copy_bytes, + }); + drop(guard); + + if let Some(scaled) = scaled { + emit_transition(list, scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb, slot_off, scaled, compute_args_off, 12); + list.CopyBufferRegion(&rb, slot_off + 16, scaled, mesh_args_off, 12); + emit_transition(list, scaled, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + } + + emit_transition(list, res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb, slot_off + HDR_BYTES as u64, res_buf, res_off, copy_bytes as u64); + emit_transition(list, res_buf, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); +} + +/// `XCL_TRACE_MS=` (diagnostic): the first draws with a mesh pipeline of that MS (and +/// one in a thousand after them) – the root arguments, the descriptors in the first slots of +/// its tables (slot 89 of the first: the title's skinned mesh shader reads it) and the first +/// words the CPU sees behind each buffer view. A mesh shader that reads its vertex and primitive +/// counts as 0 draws nothing. +unsafe fn trace_ms_draw(this: *mut c_void, pso: usize, max: u32) { + let Some(want) = super::real::trace_ms() else { return }; + if super::real::pso_shaders(pso).map(|s| s.0) != Some(want) { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let Some(layout) = layout else { return }; + // `XCL_TRACE_READBACK=1`: what the GPU holds, after the submit that draws with them, in two + // places it writes and the CPU does not (slot 5 of the second table; the dword of the whole + // heap, slot 86 of the first, that the root constant names): read back for a few draws, and + // logged some hundred draws later + if std::env::var("XCL_TRACE_READBACK").is_ok_and(|v| v.trim() == "1") { + static PENDING: Mutex> = Mutex::new(Vec::new()); + let dwords = |at: u64, bytes: u64| -> Vec { + let cpu = super::sparse::cpu_of(at as usize); + if !crate::gpu::shader::readable(cpu, bytes as usize) { + return Vec::new(); + } + (0..(bytes / 4).min(16) as usize).map(|i| std::ptr::read_unaligned((cpu + 4 * i) as *const u32)).collect() + }; + { + let mut g = PENDING.lock().unwrap(); + g.retain(|&(at_n, what, at, bytes, records)| { + if n < at_n + 300 { + return true; + } + crate::xlog_info!("trace MS readback: draw #{at_n} {what} at {at:#x} ({records:#x}): after its submit the GPU had {:08x?}", dwords(at, bytes)); + false + }); + } + if n < 3 || n % 1500 < 3 { + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + let tables: Vec = layout.params.iter().filter_map(|p| if let Param::Table { at } = *p { Some(word(at as usize)) } else { None }).collect(); + let constant = layout.params.iter().find_map(|p| if let Param::Constants { at, .. } = *p { Some(word(at as usize)) } else { None }).unwrap_or(0); + let view = |t: u32, k: u32| super::console_heap::words_at(t.wrapping_add(32 * k)).map(|w| ((((w[1] as u64) & 0xFFFF) << 32) | w[0] as u64, ((w[1] >> 16) & 0x3FFF).max(1) as u64 * w[2] as u64, w[2])); + let mut asks: Vec<(&'static str, u64, u64, u32)> = Vec::new(); + if let Some((base, bytes, records)) = tables.get(1).and_then(|&t| view(t, 5)) { + asks.push(("slot 5", base, bytes.min(64), records)); + } + if let Some((heap, bytes, _)) = tables.first().and_then(|&t| view(t, 86)) { + let off = ((constant << 2) & 0x1FFF_FFFC) as u64; + if off + 16 <= bytes { + asks.push(("heap dword of the root constant", heap + off, 16, constant)); + } + } + // PreSkin trace: read table1[0]+0x54 -> offset & buffer selector (table0[33] vs table0[84]) + if let Some((cb0, cb0_bytes, _)) = tables.get(1).and_then(|&t| view(t, 0)) { + let cb0_cpu = super::sparse::cpu_of(cb0 as usize); + if cb0_bytes >= 0x58 && crate::gpu::shader::readable(cb0_cpu + 0x54, 4) { + let s0 = std::ptr::read_unaligned((cb0_cpu + 0x54) as *const u32); + let off = ((s0 << 4) & 0x0FFF_FFF0) as u64; + let slot_idx = if (s0 & 0x0300_0000) == 0 { 33 } else { 84 }; + let uav_idx = if (s0 & 0x0300_0000) == 0 { 24 } else { 25 }; + if let Some((base, bytes, _)) = tables.first().and_then(|&t| view(t, slot_idx)) { + crate::xlog_info!("trace MS preskin: draw #{n} cb0[0x54]={s0:#010x} (off={off:#x} fmt={:#x} sel={} srv_slot={slot_idx} uav_slot={uav_idx}) srv_base={base:#x} bytes={bytes:#x} tile={}", (s0 >> 28) & 3, (s0 >> 24) & 3, super::sparse::view_tile_diag((base + off) as usize)); + if off + 64 <= bytes { + asks.push(("preskin srv[off]", base + off, 64, s0)); + } + } + if let Some((ubase, ubytes, _)) = tables.first().and_then(|&t| view(t, uav_idx)) { + if off + 64 <= ubytes { + asks.push(("preskin uav[off]", ubase + off, 64, s0)); + } + } + } + } + if let Some((bone_base, bone_bytes, bone_rec)) = tables.first().and_then(|&t| view(t, 1)) { + asks.push(("table0 slot 1 (bones)", bone_base, bone_bytes.min(64), bone_rec)); + } + for (what, at, bytes, records) in asks { + if at != 0 && bytes >= 4 { + crate::xlog_info!("trace MS readback: draw #{n} {what} at {at:#x} ({records:#x}): the CPU has {:08x?}", dwords(at, bytes)); + super::list_x::trace_read_back(this as usize, at, bytes); + PENDING.lock().unwrap().push((n, what, at, bytes, records)); + } + } + } + } + if !(n < 6 || (n % 997 == 0 && n < 40_000)) { + return; + } + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + crate::xlog_info!("trace MS draw #{n} (max {max}): root arguments {:08x?}", (0..args.len() / 4).map(|k| word(4 * k)).collect::>()); + for va in console_list::root_views(&layout, &args) { + crate::xlog_info!("trace MS draw #{n}: root view {va:#x}: the view shows {:x?}; {}", crate::hle::kernelx::mirrors::shows(va as usize), super::sparse::view_tile_diag(va as usize)); + // (the skinned mesh shader reads a table at an offset the view's first word names) + let c = super::sparse::cpu_of(va as usize); + if crate::gpu::shader::readable(c, 16) { + let w0 = std::ptr::read_unaligned(c as *const u32); + let off = ((w0 >> 7) & 0x1ff_fffc) as usize; + crate::xlog_info!("trace MS draw #{n}: root view {va:#x}: first word {w0:#010x}: table at +{off:#x} (stride {}): {}", (w0 >> 3) & 60, super::sparse::view_tile_diag(va as usize + off)); + } + } + let mut tables = 0; + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize); + let slots: &[u32] = if tables == 0 { &[0, 1, 8, 24, 25, 29, 33, 84, 86, 89, 190] } else { &[0, 1, 2, 3, 4, 5, 6, 7] }; + for &k in slots { + let Some(w) = super::console_heap::words_at(t.wrapping_add(32 * k)) else { + crate::xlog_info!("trace MS draw #{n}: table {tables} ({t:#x}) slot {k}: not in a console heap"); + continue; + }; + let base = (((w[1] as u64) & 0xFFFF) << 32) | w[0] as u64; + // (in a GPU view the CPU cannot touch: what the view shows there, read at its CPU address) + use crate::hle::kernelx::mirrors::{shows, Shows}; + let shown = shows(base as usize); + let cpu = match shown { + Shows::Same(c) => c, + Shows::Page { at, .. } => at, + Shows::NoView | Shows::Nothing => base as usize, + }; + let head: Option> = (base != 0 && crate::gpu::shader::readable(cpu, 32)).then(|| (0..8).map(|i| std::ptr::read_unaligned((cpu + 4 * i) as *const u32)).collect()); + crate::xlog_info!("trace MS draw #{n}: table {tables} ({t:#x}) slot {k}: {w:08x?}; as a V#: base {base:#x} stride {} records {}; the view shows {shown:x?}; behind it {head:08x?}", (w[1] >> 16) & 0x3FFF, w[2]); + if !matches!(shown, Shows::NoView) || crate::gpu::uma::get().is_some_and(|u| u.is_sparse(base as usize)) { + let bytes = (((w[1] >> 16) & 0x3FFF).max(1) as u64 * w[2] as u64).max(1); + crate::xlog_info!("trace MS draw #{n}: table {tables} slot {k}: first {}; last {}", super::sparse::view_tile_diag(base as usize), super::sparse::view_tile_diag((base + bytes - 1) as usize)); + } + } + tables += 1; + } +} + /// `XCL_DUMP_TARGETS`: a DispatchMesh (the two passes of a translated mesh pipeline count as the /// one draw they stand for) with `outcome` unsafe fn mesh_work(this: *mut c_void, outcome: usize) { @@ -2322,6 +2963,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let raw_pso = with(this, |s| s.pso); // (a dispatching one whose pipeline would be waited for here: at the submit, `list_x::defer`; // recorded there through this call, with everything below) + if trace_range().is_some() && signature_dispatches(sig) { + trace_range_work(this, raw_pso, "indirect dispatch"); + } let unbuilt_compute = signature_dispatches(sig) && super::pso_async::waits_for(raw_pso) && super::real::is_console_compute(raw_pso); if unbuilt_compute { flush_two_pass(this, RunEnd::Draw); @@ -2363,6 +3007,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // the PC call under the title's root signature with the pass-through mesh pipeline on // the list, whose shaders read their memory through root views the title's root // signature does not have. + trace_ms_draw(this, pso, max); + trace_args(this, pso, commands_at, sig); let Some(msig) = dispatch_mesh_sig_of(sig) else { ei_work(this, sig, super::targets::SKIPPED); count(DRAWS_SKIPPED); @@ -2416,12 +3062,19 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // on the GPU (`SCALE_ARGS_HLSL`) let (scaled, at) = make_scaled_args_buffer(this, list, src, count, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap, batch)?; let plan = two_pass_plan(max, records, with(this, |s| s.record_open)); + let mut first_rec_off = 0u64; let passes = run_two_pass_plan(this, list, &plan, &res_buf, res_va, region, |k, compute, va| { + if k == 0 && compute { + first_rec_off = va - res_va; + } bind_two_pass_stage(this, list, pso, &tp, va, compute)?; let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); Ok(()) }); + if passes.is_ok() { + trace_record(list, pso, &tp, &res_buf, first_rec_off, Some(&scaled), at + msig.mesh_offset as u64, at + commands as u64 + msig.mesh_offset as u64, None); + } // (with `batch` the block stays in INDIRECT_ARGUMENT for the next rewrite) if !batch { emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); @@ -2571,6 +3224,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // (past the hook, as `bind_abi` binds the pipeline) super::list_x::set_compute_pipeline(this, whole.as_raw()); } + if compute && super::real::trace_preskin() { + trace_preskin_cs(this, pso, "indirect", [max, 0, 0], 0); + } ei_work(this, sig, super::targets::RAN); count(if gfx { DRAWS } else { DISPATCHES }); let t = super::gpu_profile::begin(this, pso, if gfx { super::gpu_profile::Kind::IndirectDraw } else { super::gpu_profile::Kind::IndirectDispatch }, [max, 0, 0]); @@ -2591,9 +3247,13 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us (None, None) => fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)), } super::gpu_profile::end(this, t); - if compute && super::ambient::has_compute_psos() { + if compute && super::ambient::has_compute_psos() && count_buf == 0 && max == 1 { + let indirect_args = checked.as_ref().map(|c| { + let (b, off) = c.arguments(); + (b, off as u32) + }); let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); - super::ambient::after_compute_dispatch(this, pso, [0, 0, 0], layout.as_deref(), &args, view_heap); + super::ambient::after_compute_dispatch(this, pso, [0, 0, 0], layout.as_deref(), &args, view_heap, indirect_args); } } Err(e) => { @@ -3354,6 +4014,68 @@ fn bvh_builder_enabled() -> bool { *ON.get_or_init(|| std::env::var("XCL_BVH_BUILDER").is_ok_and(|v| v.trim() == "1")) } +/// `XCL_TRACE_RANGE=-` (hex addresses; a diagnostic): the compute work whose descriptor +/// tables or root views hold a buffer view over `[lo, hi)`. +pub(super) fn trace_range_of() -> Option<(u64, u64)> { + trace_range() +} + +fn trace_range() -> Option<(u64, u64)> { + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + *V.get_or_init(|| { + let v = std::env::var("XCL_TRACE_RANGE").ok()?; + let (lo, hi) = v.trim().split_once('-')?; + let hex = |t: &str| u64::from_str_radix(t.trim().trim_start_matches("0x"), 16).ok(); + Some((hex(lo)?, hex(hi)?)) + }) +} + +/// `XCL_TRACE_RANGE`: compute work (`what`) recorded with pipeline `pso`: each (pipeline, table, +/// slot) with a buffer view over the range is logged the first time and at powers of 16. +unsafe fn trace_range_work(this: *mut c_void, pso: usize, what: &str) { + let Some((lo, hi)) = trace_range() else { return }; + let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + let Some(layout) = layout else { return }; + static SEEN: Mutex>> = Mutex::new(None); + let seen = |key: (usize, u32, u32)| { + let mut g = SEEN.lock().unwrap(); + let n = g.get_or_insert_with(HashMap::new).entry(key).or_insert(0); + *n += 1; + (*n == 1 || *n == 16 || *n == 256 || *n == 4096).then_some(*n) + }; + let real = super::pso_async::peek(pso); + let label = || format!("pipeline {pso:#x} (cs {:016x?}, translated {})", super::real::pso_shaders(real).map(|s| s.0), super::real::is_translated_compute(real)); + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + for (i, va) in console_list::root_views(&layout, &args).enumerate() { + if va + 0x1_0000 > lo && va < hi { + if let Some(n) = seen((pso, 1000, i as u32)) { + crate::xlog_info!("trace range: {what} #{n} of {}: root view {i} at {va:#x}", label()); + } + } + } + let mut tables = 0; + for p in layout.params.iter() { + let Param::Table { at } = *p else { continue }; + let t = word(at as usize); + for k in 0..256u32 { + if t == 0 { + break; + } + let Some(w) = super::console_heap::words_at(t.wrapping_add(32 * k)) else { break }; + let base = (((w[1] as u64) & 0xFFFF) << 32) | w[0] as u64; + let stride = ((w[1] >> 16) & 0x3FFF) as u64; + let bytes = if stride == 0 { w[2] as u64 } else { w[2] as u64 * stride }; + if bytes == 0 || bytes > 1 << 30 || base >= hi || base + bytes <= lo { + continue; + } + if let Some(n) = seen((pso, tables, k)) { + crate::xlog_info!("trace range: {what} #{n} of {}: table {tables} slot {k}: {w:08x?} = base {base:#x}, {bytes} bytes (stride {stride})", label()); + } + } + tables += 1; + } +} + /// `XCL_DIAG_VIEWS=1` turns on per-dispatch descriptor-table view tracking (off by default: /// locks `HEAPS` and `DISPATCH_VIEWS` on every compute dispatch). fn diag_views_enabled() -> bool { @@ -3391,14 +4113,56 @@ unsafe fn note_dispatch_views(this: *mut c_void, pso: usize) { } } +unsafe fn trace_preskin_cs(this: *mut c_void, pso: usize, kind: &str, groups: [u32; 3], flags: u32) { + let Some((cs_hash, _)) = super::real::pso_shaders(pso) else { return }; + if !matches!(cs_hash, 0x0d8cb7f3a2e49531 | 0x1404420b38db8597 | 0x44ca55bfefe67bd5 | 0x85c4edb089897347) { + return; + } + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if k >= 24 { + return; + } + let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).unwrap_or(0); + let mut tables = Vec::new(); + if let Some(l) = layout.as_ref() { + for (i, p) in l.params.iter().enumerate() { + if let Param::Table { at } = *p { + let t = word(at as usize); + tables.push((i, at, t)); + } + } + } + let t0 = tables.first().map(|x| x.2).unwrap_or(0); + let s24 = if t0 != 0 { super::console_heap::words_at(t0.wrapping_add(24 * 32)) } else { None }; + let s25 = if t0 != 0 { super::console_heap::words_at(t0.wrapping_add(25 * 32)) } else { None }; + let s33 = if t0 != 0 { super::console_heap::words_at(t0.wrapping_add(33 * 32)) } else { None }; + let s84 = if t0 != 0 { super::console_heap::words_at(t0.wrapping_add(84 * 32)) } else { None }; + crate::xlog_info!( + "trace preskin CS #{k} ({kind}) cs={cs_hash:016x} groups={groups:?} flags={flags:#x} tables={tables:x?} s24={s24:08x?} s25={s25:08x?} s33={s33:08x?} s84={s84:08x?}" + ); +} + /// `Dispatch` / `DispatchX(x, y, z, flags)`. pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + if trace_range().is_some() { + trace_range_work(this, with(this, |s| s.pso), if bvh_builder_runs(flags, bvh_builder_enabled()) { "dispatch" } else { "BVH builder pass (left out)" }); + } if !bvh_builder_runs(flags, bvh_builder_enabled()) { static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; if n == 1 || n.is_power_of_two() { crate::xlog_info!("D3D12.X: BVH builder pass left out ({n} so far; XCL_BVH_BUILDER=1 runs them)"); } + if super::real::trace_ms().is_some() { + static SEEN: Mutex>> = Mutex::new(None); + let pso = with(this, |s| s.pso); + let k = { let mut g = SEEN.lock().unwrap(); let k = g.get_or_insert_with(HashMap::new).entry(pso).or_insert(0); *k += 1; *k }; + if k == 1 || k == 64 || k == 4096 { + crate::xlog_info!("trace names: pass left out #{k} of pipeline {pso:#x} (cs {:016x?}): {x}x{y}x{z} flags {flags:#x}", super::real::pso_shaders(super::pso_async::peek(pso)).map(|s| s.0)); + } + } return; } let pso = with(this, |s| s.pso); @@ -3448,14 +4212,17 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f note_thread_dimensions([x, y, z], groups, super::real::pso_threads(pso).unwrap_or_default()); } with(this, |s| s.limits = limits); + if super::real::trace_preskin() { + trace_preskin_cs(this, pso, "direct", groups, flags); + } 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); - if super::ambient::has_compute_psos() { + if super::ambient::has_compute_psos() && groups[0] > 0 && groups[1] > 0 && groups[2] > 0 { let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); - super::ambient::after_compute_dispatch(this, pso, groups, layout.as_deref(), &args, view_heap); + super::ambient::after_compute_dispatch(this, pso, groups, layout.as_deref(), &args, view_heap, None); } } Err(e) => { @@ -3742,6 +4509,9 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi (layout.clone(), args.clone(), s.heaps) }); want_root_views(layout.as_deref(), &args, super::view_want::Path::RootView); + if gfx { + trace_table_slot(u, layout.as_deref(), &args, pso); + } // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let copy = |bytes: &[u8]| -> Result { let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or_else(|| { @@ -3788,6 +4558,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi } let real = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?.clone(); + uncover_bound_tables(layout.as_deref(), &args, u); + if gfx && super::pso_async::is_kept(pso) { + uncover_indexed(layout.as_deref(), &args, u); + } let b = Bound { rs, views, pso: pc, io: views[0] }; rebind(this, list, &b, gfx); Ok(b) diff --git a/crates/xcl/src/hle/d3d12x/capture.rs b/crates/xcl/src/hle/d3d12x/capture.rs index 47a09928cb..5f4876e74b 100644 --- a/crates/xcl/src/hle/d3d12x/capture.rs +++ b/crates/xcl/src/hle/d3d12x/capture.rs @@ -735,6 +735,27 @@ pub(super) fn note_stream(pso: usize) { g.get_or_insert_with(HashMap::new).entry(pso).or_insert_with(|| Arc::new(Pipe { kind: "stream", set: None, stages: Vec::new(), state: Value::Null, split: false })); } +/// Mesh pipeline `pso` was made from a stream with a console MS: its shaders by hash (no bytes +/// kept – a title makes tens of thousands of these and uses few), the depth state the stream +/// names (DepthEnable, DepthWriteMask, DepthFunc) and its render target formats. +pub(super) fn note_mesh_stream(pso: usize, stages: &[(&'static str, &[u8])], depth: Option<[u32; 3]>, formats: &[i32]) { + if !enabled() || pso == 0 { + return; + } + let stages = stages + .iter() + .map(|(s, b)| { + let h = crate::gpu::shader::fnv64(b); + (*s, super::real::shader_key_of_hash(h), h, None) + }) + .collect(); + let state = json!({ + "depth_stencil": depth.map(|d| json!({"depth": d[0] != 0, "write_mask": d[1], "func": d[2]})), + "rt_formats": formats, + }); + keep_pipe(pso, Pipe { kind: "mesh", set: None, stages, state, split: false }); +} + fn graphics_state(d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Value { let n = (d.NumRenderTargets as usize).min(8); let b = &d.BlendState; diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 676a8dd27c..1b4a47ada6 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -25,7 +25,8 @@ //! Without the shared heap (it could not be made) a heap keeps its own PC heap: SRV at 2k, //! UAV at 2k + 1. -use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::{Acquire, Relaxed, Release}}; use std::sync::Mutex; use windows::core::Interface; @@ -75,6 +76,93 @@ impl Heap { static HEAPS: Mutex> = Mutex::new(Vec::new()); +/// Released descriptor range in `GLOBAL` or `GLOBAL_SAMPLER` awaiting active GPU queues before +/// being returned to `free` (prevents overwriting shader-visible descriptors still read in flight). +struct RetiredRange { + first: u32, + count: u32, + /// Fence marks across all live queues on the device (`None` = signal failed, keep held). + marks: Option>, +} + +/// Pop retired ranges whose queue fences have all completed. A `None` entry (failed signal) stays +/// quarantined without wedging subsequent healthy ranges. +fn pop_ready_ranges( + retired: &mut VecDeque>, + mut completed: impl FnMut(&F) -> u64, +) -> Vec<(u32, u32)> { + let mut ready = Vec::new(); + let mut kept = VecDeque::new(); + while let Some(r) = retired.pop_front() { + match r.marks.as_ref() { + Some(m) if m.iter().all(|(f, v)| completed(f) >= *v) => ready.push((r.first, r.count)), + None => kept.push_back(r), + Some(_) => { + kept.push_back(r); + break; + } + } + } + while let Some(r) = kept.pop_back() { + retired.push_front(r); + } + ready +} + +struct QueueFences(HashMap); + +// D3D12 fences are free-threaded; accessed only under HEAP_FENCES lock. +unsafe impl Send for QueueFences {} + +static HEAP_FENCES: Mutex> = Mutex::new(None); +static GLOBAL_RETIRED: AtomicBool = AtomicBool::new(false); +/// Serialises `drain_global_retired` across `fill_nulls` and `merge_release` so a concurrent +/// `slot()` cannot miss ranges popped from `GLOBAL.retired` before they reach `GLOBAL.free`. +/// Lock order: `GLOBAL_DRAIN` -> `SLOT_WRITES` -> `GLOBAL` (never held alongside `HEAPS`). +static GLOBAL_DRAIN: Mutex<()> = Mutex::new(()); +/// Incremented under `GLOBAL` whenever descriptors are merged back into `GLOBAL.free`. +static GLOBAL_DRAIN_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Signal every known live title queue belonging to `dev` (called outside `GLOBAL`, +/// `GLOBAL_SAMPLER`, `HEAPS`, and `SLOT_WRITES`). Returns `Some(vec![])` when no live queues +/// exist for `dev`, or `None` if fence creation or signaling fails so released descriptor ranges +/// stay safely quarantined. +unsafe fn signal_live_queues_for(dev: &ID3D12Device) -> Option> { + let dev_raw = dev.as_raw(); + let mut queues: Vec<(usize, ID3D12CommandQueue)> = Vec::new(); + for raw in super::present::known_queues() { + let ptr = raw as *mut std::ffi::c_void; + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&ptr) { + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_ok() && qdev.as_ref().is_some_and(|d| d.as_raw() == dev_raw) { + queues.push((raw, q.clone())); + } + } + } + if queues.is_empty() { + return Some(Vec::new()); + } + let mut guard = HEAP_FENCES.lock().unwrap(); + let map = &mut guard.get_or_insert_with(|| QueueFences(HashMap::new())).0; + let mut marks = Vec::with_capacity(queues.len()); + for (key, q) in queues { + let (fence, val) = match map.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => { + let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + e.insert((f, 0)) + } + }; + let next = *val + 1; + if q.Signal(&*fence, next).is_err() { + return None; + } + *val = next; + marks.push((fence.clone(), next)); + } + Some(marks) +} + /// The shader-visible PC heap of all console view heaps. struct Global { dev: ID3D12Device, @@ -84,8 +172,10 @@ struct Global { inc: u32, cap: u32, next: u32, - /// released ranges (first, count) + /// released ranges (first, count) proven GPU-idle free: Vec<(u32, u32)>, + /// released ranges awaiting live GPU queue completion before nulling and entering `free` + retired: VecDeque>, /// a CPU-only heap of `NULL_BLOCK` null views (even SRV, odd UAV) and its start: copied over /// every range of the shared heap that is not handed out (`fill_nulls`) nulls: Option<(ID3D12DescriptorHeap, u64)>, @@ -349,6 +439,7 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { // the memory windows' raw UAVs (`set_window_views`) come first next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), + retired: VecDeque::new(), nulls, }); } @@ -493,24 +584,94 @@ fn page_of(h: &mut Heap, k: u32) -> Option<(u32, u32)> { Some((first, p as u32 * PAGE_SLOTS)) } -/// The shared range starting at `first` (`count` descriptors) is free again. Its views (of the -/// released heap's resources, which may be gone) are made null views first, before another -/// heap can be given the range: no shader that still has an index there reads them. +/// Move completed `GLOBAL.retired` ranges to `GLOBAL.free`, nulling their view descriptors and +/// clearing `NAMES` under `SLOT_WRITES` before another heap can allocate them. Must be called +/// outside `SLOT_WRITES`, `HEAPS`, and `GLOBAL`. +fn drain_global_retired() -> bool { + drain_global_retired_since(GLOBAL_DRAIN_SEQ.load(Acquire)) +} + +fn drain_global_retired_since(before_seq: u64) -> bool { + drain_global_retired_with(before_seq, |dev, cpu, inc, nulls, ready| { + let _w = SLOT_WRITES.lock().unwrap(); + for &(first, count) in ready { + unsafe { fill_nulls(dev, cpu, inc, first, first + count, nulls) }; + if let Some(n) = NAMES.get() { + n.clear(first, first + count); + } + } + }) +} + +fn drain_global_retired_with( + before_seq: u64, + on_nulls: impl FnOnce(&ID3D12Device, u64, u32, u64, &[(u32, u32)]), +) -> bool { + if !GLOBAL_RETIRED.load(Acquire) { + return GLOBAL_DRAIN_SEQ.load(Acquire) != before_seq; + } + let _drain = GLOBAL_DRAIN.lock().unwrap(); + let (ready, nulls_info) = { + let mut g = GLOBAL.lock().unwrap(); + let Some(s) = g.as_mut() else { + GLOBAL_RETIRED.store(false, Release); + return GLOBAL_DRAIN_SEQ.load(Acquire) != before_seq; + }; + let ready = pop_ready_ranges(&mut s.retired, |f| unsafe { super::real::fence_completed(f) }); + if ready.is_empty() { + GLOBAL_RETIRED.store(!s.retired.is_empty(), Release); + return GLOBAL_DRAIN_SEQ.load(Acquire) != before_seq; + } + // Keep `GLOBAL_RETIRED` true across `fill_nulls` until `merge_release` completes. + let nulls_info = s.nulls.as_ref().map(|n| (s.dev.clone(), s.cpu, s.inc, n.1)); + (ready, nulls_info) + }; + if let Some((dev, cpu, inc, nulls)) = nulls_info { + on_nulls(&dev, cpu, inc, nulls, &ready); + } + if let Some(s) = GLOBAL.lock().unwrap().as_mut() { + for (first, count) in ready { + merge_release(&mut s.free, first, count); + } + GLOBAL_DRAIN_SEQ.fetch_add(1, Release); + GLOBAL_RETIRED.store(!s.retired.is_empty(), Release); + } else { + GLOBAL_RETIRED.store(false, Release); + } + true +} + +/// The shared range starting at `first` (`count` descriptors) is quarantined behind active GPU +/// queues before its views are made null views and it returns to `free`, preventing overwrites +/// of live shader-visible descriptors. pub fn release_global(first: u32, count: u32) { if count == 0 { return; } - if let Some((dev, cpu, inc, nulls)) = null_source() { - // (the range is still the released heap's) - let _w = SLOT_WRITES.lock().unwrap(); - unsafe { fill_nulls(&dev, cpu, inc, first, first + count, nulls) }; - if let Some(n) = NAMES.get() { - n.clear(first, first + count); + let dev = GLOBAL.lock().unwrap().as_ref().map(|s| s.dev.clone()); + let Some(dev) = dev else { return }; + let marks = unsafe { signal_live_queues_for(&dev) }; + if marks.as_ref().is_some_and(Vec::is_empty) { + if let Some((dev, cpu, inc, nulls)) = null_source() { + // (the range is still the released heap's) + let _w = SLOT_WRITES.lock().unwrap(); + unsafe { fill_nulls(&dev, cpu, inc, first, first + count, nulls) }; + if let Some(n) = NAMES.get() { + n.clear(first, first + count); + } + } + if let Some(s) = GLOBAL.lock().unwrap().as_mut() { + merge_release(&mut s.free, first, count); + GLOBAL_DRAIN_SEQ.fetch_add(1, Release); } + drain_global_retired(); + return; } if let Some(s) = GLOBAL.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + s.retired.push_back(RetiredRange { first, count, marks }); + GLOBAL_RETIRED.store(true, Release); } + drain_global_retired(); } /// Add a released range to `free`, merging the ranges it touches: adjacent releases become @@ -749,14 +910,32 @@ pub fn write_shadow(s: &ShadowSlot, words: &[u32]) { unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), s.at as *mut u32, n) }; } +fn finish_view_slot(h: &Heap, k: u32, page: Option<(u32, u32)>) -> Slot { + let uav = ((2 * k + 1) * h.inc) as u64; + let shared = page.and_then(|(first, k0)| { + let g = GLOBAL.lock().unwrap(); + let g = g.as_ref()?; + let i = first + 2 * (k - k0); + Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) + }); + // A heap meant for the shared heap whose page found no room there: lists bind only the + // shared heap, where 2k is another heap's view, a memory window's raw UAV (k from 2 to 9) or + // past the heap's end; its T#s name the null views at 0 / 1 instead, and nothing is copied. + let own = if h.pages.is_empty() { (2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0) } else { (0, 0, 0) }; + let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or(own); + Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k } +} + /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot /// of a heap in the shared heap gets its page's place there now if the page has none yet; one /// whose page finds no room there gets index 0, the null SRV / UAV pair. pub fn slot(cpu: u64) -> Option { + drain_global_retired(); let mut heaps = HEAPS.lock().unwrap(); - let h = heaps.iter_mut().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; - let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32; - if h.sampler { + let idx = heaps.iter().position(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; + let k = ((cpu - heaps[idx].shadow as u64) / heaps[idx].slot_bytes() as u64) as u32; + if heaps[idx].sampler { + let h = &mut heaps[idx]; let shared = sampler_page_of(h, k).and_then(|(first, k0)| { let g = GLOBAL_SAMPLER.lock().unwrap(); let g = g.as_ref()?; @@ -769,19 +948,26 @@ pub fn slot(cpu: u64) -> Option { let (index, shared_srv) = shared.unwrap_or_else(|| (sampler_unmapped_index(!h.pages.is_empty(), k), 0)); return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k }); } - let uav = ((2 * k + 1) * h.inc) as u64; - let shared = page_of(h, k).and_then(|(first, k0)| { - let g = GLOBAL.lock().unwrap(); - let g = g.as_ref()?; - let i = first + 2 * (k - k0); - Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) - }); - // A heap meant for the shared heap whose page found no room there: lists bind only the - // shared heap, where 2k is another heap's view, a memory window's raw UAV (k from 2 to 9) or - // past the heap's end; its T#s name the null views at 0 / 1 instead, and nothing is copied. - let own = if h.pages.is_empty() { (2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0) } else { (0, 0, 0) }; - let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or(own); - Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k }) + let drain_seq = GLOBAL_DRAIN_SEQ.load(Acquire); + let page = page_of(&mut heaps[idx], k); + if page.is_none() && !heaps[idx].pages.is_empty() { + // Check `GLOBAL_RETIRED` before `GLOBAL_DRAIN_SEQ` (reverse of the Release order in + // `drain_global_retired_with`): observing `GLOBAL_RETIRED == false` guarantees the + // preceding `GLOBAL_DRAIN_SEQ` increment is visible. + if GLOBAL_RETIRED.load(Acquire) { + drop(heaps); + let drained = drain_global_retired_since(drain_seq); + heaps = HEAPS.lock().unwrap(); + let h = heaps.iter_mut().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; + let page = if drained || GLOBAL_DRAIN_SEQ.load(Acquire) != drain_seq { page_of(h, k) } else { None }; + return Some(finish_view_slot(h, k, page)); + } + if GLOBAL_DRAIN_SEQ.load(Acquire) != drain_seq { + let page = page_of(&mut heaps[idx], k); + return Some(finish_view_slot(&heaps[idx], k, page)); + } + } + Some(finish_view_slot(&heaps[idx], k, page)) } /// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) of the PC @@ -1053,6 +1239,7 @@ struct GlobalSampler { cap: u32, next: u32, free: Vec<(u32, u32)>, + retired: VecDeque>, } unsafe impl Send for GlobalSampler {} @@ -1105,6 +1292,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { // Reserve slot 0 as the immutable point-wrap zero sampler for empty/zeroed S# entries. next: 1, free: Vec::new(), + retired: VecDeque::new(), }); } true @@ -1113,6 +1301,9 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { fn reserve_global_sampler(count: u32) -> Option { let mut g = GLOBAL_SAMPLER.lock().unwrap(); let s = g.as_mut()?; + for (first, n) in pop_ready_ranges(&mut s.retired, |f| unsafe { super::real::fence_completed(f) }) { + merge_release(&mut s.free, first, n); + } let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; @@ -1139,8 +1330,18 @@ fn release_global_sampler(first: u32, count: u32) { if count == 0 { return; } + let dev = GLOBAL_SAMPLER.lock().unwrap().as_ref().map(|s| s.dev.clone()); + let Some(dev) = dev else { return }; + let marks = unsafe { signal_live_queues_for(&dev) }; if let Some(s) = GLOBAL_SAMPLER.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + if marks.as_ref().is_some_and(Vec::is_empty) { + merge_release(&mut s.free, first, count); + } else { + s.retired.push_back(RetiredRange { first, count, marks }); + } + for (f, n) in pop_ready_ranges(&mut s.retired, |f| unsafe { super::real::fence_completed(f) }) { + merge_release(&mut s.free, f, n); + } } } @@ -1316,7 +1517,7 @@ mod tests { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), nulls: None, + next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), retired: VecDeque::new(), nulls: None, }); let window = (&mut resource as *mut _ as usize, 0x10000); // the root-UAV slots past the windows there are: null views, not window 0 again @@ -1552,7 +1753,7 @@ mod tests { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x10_0000, gpu: 0x20_0000, inc: 32, cap: base + 2 * PAGE_SLOTS, - next: base, free: Vec::new(), nulls: None, + next: base, free: Vec::new(), retired: VecDeque::new(), nulls: None, }); } let rel = |p: u64| (p as usize - u.base()) as u32; @@ -1696,7 +1897,7 @@ mod tests { *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), - cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), + cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), }); assert_eq!(reserve_global_sampler(4), Some(1)); assert_eq!(reserve_global_sampler(4), Some(5)); @@ -1755,12 +1956,12 @@ mod tests { *GLOBAL.lock().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), - cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), nulls: None, + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), nulls: None, }); *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), - cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), + cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), }); if crate::gpu::uma::get().is_some() { assert!(register(0xC100, 16, 0x9000, 0, 16, true, true, true)); @@ -1810,4 +2011,289 @@ mod tests { assert_eq!(sampler_own_index(&[], 0), 0); assert_eq!(sampler_own_index(&[], 42), 42); } + + /// Released ranges in `GLOBAL` and `GLOBAL_SAMPLER` stay quarantined (and view descriptors + /// are not overwritten with null views) while a live queue on the device still has work in + /// flight, and are nulled and reclaimed once that queue's fence completes. + #[test] + fn released_shared_ranges_stay_quarantined_until_queue_completes() { + const CHILD: &str = "XCL_TEST_SHARED_QUARANTINE_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::released_shared_ranges_stay_quarantined_until_queue_completes", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + if crate::gpu::uma::get().is_none() { + return; + } + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + unsafe { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + super::super::present::note_execute(queue.as_raw(), &[]); + + let base = crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + let view_cap = base + 2 * PAGE_SLOTS; + let view_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: view_cap, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }).unwrap(); + let null_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: NULL_BLOCK, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }).unwrap(); + let view_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let nulls_at = null_heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; + null_views_in(&dev, nulls_at, view_inc, NULL_BLOCK as u64); + + let sampler_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: 5, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }).unwrap(); + let sampler_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + + *GLOBAL.lock().unwrap() = Some(Global { + dev: dev.clone(), + cpu: view_heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, + gpu: view_heap.GetGPUDescriptorHandleForHeapStart().ptr, + heap: view_heap, + inc: view_inc, + cap: view_cap, + next: base, + free: Vec::new(), + retired: VecDeque::new(), + nulls: Some((null_heap, nulls_at)), + }); + *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { + dev: dev.clone(), + cpu: sampler_heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, + heap: sampler_heap, + inc: sampler_inc, + cap: 5, + next: 1, + free: Vec::new(), + retired: VecDeque::new(), + }); + + assert!(register(0xD100, PAGE_SLOTS, 0x10_0000, 0, 32, false, true, true)); + assert!(register(0xD200, 4, 0x20_0000, 0, 16, true, true, true)); + let s_view = slot(start(0xD100).unwrap()).unwrap(); + let s_samp = slot(start(0xD200).unwrap()).unwrap(); + assert_eq!(s_view.index, base); + assert_eq!(s_samp.index, 1); + names().note(s_view.index, 0xCAFE_0001); + assert_eq!(named_by_index(s_view.index), 0xCAFE_0001); + + unregister(0xD100); + unregister(0xD200); + + // Queue is still waiting on `gate`: ranges must stay quarantined and live view names intact. + std::thread::sleep(std::time::Duration::from_millis(50)); + assert!(GLOBAL.lock().unwrap().as_ref().unwrap().free.is_empty(), "view range returned to free while queue in flight"); + assert!(GLOBAL_SAMPLER.lock().unwrap().as_ref().unwrap().free.is_empty(), "sampler range returned to free while queue in flight"); + assert_eq!(named_by_index(base), 0xCAFE_0001, "view range overwritten while queue in flight"); + + assert!(register(0xD101, PAGE_SLOTS, 0x30_0000, 0, 32, false, true, true)); + assert!(register(0xD201, 4, 0x40_0000, 0, 16, true, true, true)); + assert_eq!(slot(start(0xD101).unwrap()).unwrap().shared_srv, 0, "quarantined view range must not be reused yet"); + assert_eq!(slot(start(0xD201).unwrap()).unwrap().shared_srv, 0, "quarantined sampler range must not be reused yet"); + + // Complete the queue fence: ranges are nulled/cleared and reclaimed on subsequent allocation. + gate.Signal(1).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + let mut got_view = 0; + let mut got_samp = 0; + while (got_view == 0 || got_samp == 0) && std::time::Instant::now() < deadline { + if got_view == 0 { + let s = slot(start(0xD101).unwrap()).unwrap(); + if s.shared_srv != 0 { + got_view = s.index; + } + } + if got_samp == 0 { + let s = slot(start(0xD201).unwrap()).unwrap(); + if s.shared_srv != 0 { + got_samp = s.index; + } + } + if got_view == 0 || got_samp == 0 { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + assert_eq!(got_view, base, "view range reclaimed after fence completion"); + assert_eq!(got_samp, 1, "sampler range reclaimed after fence completion"); + assert_eq!(named_by_index(base), 0, "reclaimed view range had NAMES cleared before reuse"); + + unregister(0xD101); + unregister(0xD201); + *GLOBAL_SAMPLER.lock().unwrap() = None; + *GLOBAL.lock().unwrap() = None; + } + } + + #[test] + fn retired_descriptor_ranges_stay_quarantined_until_all_queues_complete() { + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let f1 = Arc::new(AtomicU64::new(0)); + let f2 = Arc::new(AtomicU64::new(0)); + let mut retired: VecDeque>> = VecDeque::new(); + let mut free: Vec<(u32, u32)> = Vec::new(); + retired.push_back(RetiredRange { first: 64, count: 16, marks: Some(vec![(f1.clone(), 1), (f2.clone(), 1)]) }); + retired.push_back(RetiredRange { first: 80, count: 16, marks: Some(vec![(f1.clone(), 2), (f2.clone(), 1)]) }); + retired.push_back(RetiredRange { first: 96, count: 16, marks: None }); + + let drain = |r: &mut VecDeque>>, free: &mut Vec<(u32, u32)>| { + for (first, count) in pop_ready_ranges(r, |f| f.load(Ordering::SeqCst)) { + merge_release(free, first, count); + } + }; + + // While f2 is still pending, neither range may re-enter `free`. + f1.store(1, Ordering::SeqCst); + drain(&mut retired, &mut free); + assert!(free.is_empty() && retired.len() == 3); + + // Once both queues pass mark 1, only range 1 returns; range 2 waits for f1 == 2. + f2.store(1, Ordering::SeqCst); + drain(&mut retired, &mut free); + assert_eq!(free, vec![(64, 16)]); + assert_eq!(retired.len(), 2); + + // Passing mark 2 coalesces [80, 96) with [64, 80); failed-signal range stays quarantined. + f1.store(2, Ordering::SeqCst); + drain(&mut retired, &mut free); + assert_eq!(free, vec![(64, 32)]); + assert_eq!(retired.len(), 1); + + // A failed-signal (`None`) range at the front stays quarantined without wedging later healthy ranges. + retired.push_back(RetiredRange { first: 112, count: 16, marks: Some(vec![(f1.clone(), 3), (f2.clone(), 1)]) }); + drain(&mut retired, &mut free); + assert_eq!(free, vec![(64, 32)]); + assert_eq!(retired.len(), 2); + f1.store(3, Ordering::SeqCst); + drain(&mut retired, &mut free); + assert_eq!(free, vec![(64, 32), (112, 16)]); + assert_eq!(retired.len(), 1); + } + + /// While `drain_global_retired` is running `fill_nulls` outside `GLOBAL`, `GLOBAL_RETIRED` + /// stays set and a concurrent `slot()` waits for the in-flight drain to finish merging into + /// `GLOBAL.free` instead of returning the unmapped null slot (`shared_srv == 0`). + #[test] + fn slot_waits_for_in_flight_drain_before_returning_unmapped() { + const CHILD: &str = "XCL_TEST_DRAIN_WINDOW_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::slot_waits_for_in_flight_drain_before_returning_unmapped", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + let mut dev_obj = Object { vt: vt.as_ptr() }; + let mut heap_obj = Object { vt: vt.as_ptr() }; + let mut null_obj = Object { vt: vt.as_ptr() }; + + let base = crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + let range = 2 * PAGE_SLOTS; + unsafe { + *GLOBAL.lock().unwrap() = Some(Global { + dev: ID3D12Device::from_raw(&mut dev_obj as *mut _ as *mut c_void), + heap: ID3D12DescriptorHeap::from_raw(&mut heap_obj as *mut _ as *mut c_void), + cpu: 0x10_0000, + gpu: 0x20_0000, + inc: 32, + cap: base + range, + next: base + range, + free: Vec::new(), + retired: VecDeque::from([RetiredRange { first: base, count: range, marks: Some(Vec::new()) }]), + nulls: Some((ID3D12DescriptorHeap::from_raw(&mut null_obj as *mut _ as *mut c_void), 0x90_0000)), + }); + GLOBAL_RETIRED.store(true, Release); + HEAPS.lock().unwrap().push(Heap { + obj: 0xE100, + shadow: 0x50_0000, + n: PAGE_SLOTS, + pc_cpu: 0x60_0000, + pc_gpu: 0, + inc: 32, + sampler: false, + pages: vec![UNMAPPED], + visible: true, + memory: Memory::Uma, + }); + } + + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let before_seq = GLOBAL_DRAIN_SEQ.load(Acquire); + let drainer = std::thread::spawn(move || { + drain_global_retired_with(before_seq, |_, _, _, _, _| { + entered_tx.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(80)); + }) + }); + + // Wait until `drainer` has popped `s.retired`, released `GLOBAL`, and is inside `on_nulls`. + entered_rx.recv().unwrap(); + let retired_during_nulls = GLOBAL_RETIRED.load(Acquire); + + let s = slot(0x50_0000).unwrap(); + let drained = drainer.join().unwrap(); + assert!(retired_during_nulls, "GLOBAL_RETIRED dropped before merge_release completed"); + assert!(drained); + assert_ne!(s.shared_srv, 0, "concurrent slot() got unmapped null slot during in-flight drain"); + assert_eq!(s.index, base, "concurrent slot() must receive the reclaimed descriptor range"); + assert!(!GLOBAL_RETIRED.load(Acquire)); + + // Second path: `slot()` already past its entry drain (holding `HEAPS` when the drain starts) + // hits the post-`page_of` fallback (`GLOBAL_RETIRED` -> `drain_global_retired_since`). + { + let mut g = GLOBAL.lock().unwrap(); + let gs = g.as_mut().unwrap(); + gs.free.clear(); + gs.retired.push_back(RetiredRange { first: base, count: range, marks: Some(Vec::new()) }); + GLOBAL_RETIRED.store(true, Release); + } + HEAPS.lock().unwrap()[0].pages[0] = UNMAPPED; + let (entered2_tx, entered2_rx) = std::sync::mpsc::channel(); + let before_seq2 = GLOBAL_DRAIN_SEQ.load(Acquire); + let drainer2 = std::thread::spawn(move || { + drain_global_retired_with(before_seq2, |_, _, _, _, _| { + entered2_tx.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(80)); + }) + }); + entered2_rx.recv().unwrap(); + let retired_during_nulls2 = GLOBAL_RETIRED.load(Acquire); + let fallback_drained = drain_global_retired_since(before_seq2); + let drained2 = drainer2.join().unwrap(); + assert!(retired_during_nulls2); + assert!(drained2 && fallback_drained, "drain_global_retired_since must wait for and observe in-flight merge"); + assert_eq!(reserve_global(range), Some(base)); + + HEAPS.lock().unwrap().clear(); + *GLOBAL.lock().unwrap() = None; + } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index d4298900f2..fa9940d2d5 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -386,15 +386,16 @@ fn intern_shader_blob(bytes: &[u8]) -> Arc<[u8]> { } let arc: Arc<[u8]> = Arc::from(bytes); let mut g = BASE_SHADERS.lock().unwrap(); - let pool = g.get_or_insert_with(|| ShaderPool { map: HashMap::new(), next_sweep: 8192 }); + let pool = g.get_or_insert_with(|| ShaderPool { map: HashMap::new(), next_sweep: super::real::SHADER_POOL_SWEEP }); if let Some(existing) = pool.map.get(&key).and_then(std::sync::Weak::upgrade) { if &*existing == bytes { return existing; } } + // (a dead entry keeps its shader's bytes: `real::SHADER_POOL_SWEEP`) if pool.map.len() >= pool.next_sweep { pool.map.retain(|_, w| w.strong_count() > 0); - pool.next_sweep = (pool.map.len().saturating_mul(2)).max(8192); + pool.next_sweep = pool.map.len() + super::real::SHADER_POOL_SWEEP; } pool.map.insert(key, Arc::downgrade(&arc)); arc @@ -1925,4 +1926,18 @@ mod tests { forget_base(pso_key2); assert!(weak_vs.upgrade().is_none(), "shared blob drops once all owning PSOs are released"); } + + /// Base shaders no PSO holds any more do not pile up in `BASE_SHADERS` (each dead entry keeps + /// its bytes): after 3000 short-lived ones, fewer than two sweeps' worth are left. + #[test] + fn base_shaders_that_died_are_swept() { + for i in 0u32..3000 { + let mut bytes = vec![0xB5u8; 64]; + bytes[..4].copy_from_slice(&i.to_le_bytes()); + drop(intern_shader_blob(&bytes)); + } + let g = BASE_SHADERS.lock().unwrap(); + let dead = g.as_ref().map_or(0, |p| p.map.values().filter(|w| w.strong_count() == 0).count()); + assert!(dead < 2 * super::super::real::SHADER_POOL_SWEEP, "{dead} dead entries kept"); + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 1116f8383d..12058c318b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1260,6 +1260,11 @@ fn pick_queue(last_queue: Option, device: usize, ty: D3D12_COMMAND_LIST_T g.iter().rev().find(|info| info.ty == ty && (device == 0 || info.device == 0 || info.device == device)).map(|info| info.queue) } +/// `XCL_TRACE_MS` (a diagnostic): `[va, va + size)` is read back after the list's submit. +pub(super) fn trace_read_back(list: usize, va: u64, size: u64) { + note_write(list, va, size); +} + fn note_write(list: usize, va: u64, size: u64) { crate::hle::kernelx::pagelog::note("list memory write recorded (the GPU writes it)", va as usize, 0, size as usize); recording(list).lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); @@ -1271,6 +1276,14 @@ fn note_write(list: usize, va: u64, size: u64) { /// (what the GPU writes there is its tiles', and the title reads it at the CPU view): the bytes /// come back to the CPU's view after the submit, like the lists' own memory writes. fn note_copy_into(list: usize, dst: usize, offset: u64, n: u64) { + if let Some((lo, hi)) = super::bind::trace_range_of() { + if let Some((p, _)) = real::console_buffer(dst) { + let at = p as u64 + offset; + if at < hi && at.saturating_add(n) > lo { + crate::xlog_info!("trace range: copy into {at:#x}, {n} bytes"); + } + } + } let Some(u) = crate::gpu::uma::get().filter(|u| u.shadowed() || super::bind::view_span().1 != 0) else { return }; let Some((p, bytes)) = real::console_buffer(dst).filter(|&(p, _)| (u.shadowed() && u.is_committed(p)) || u.is_view(p)) else { return }; let offset = offset.min(bytes as u64); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 932f853adf..330d0265be 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -63,9 +63,29 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl // The title can use flip statistics to decide when to reuse its buffer. // Queue our copy before reporting the flip. super::frame::mark_flipped(token); + trim_spares_now_and_then(); 0 } +/// `title_list::trim_idle_spares` every 2 s at most, from the title's presents (`XCL_TRIM_SPARES=0` +/// turns it off). +fn trim_spares_now_and_then() { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + static LAST: Mutex> = Mutex::new(None); + if !*ON.get_or_init(|| std::env::var("XCL_TRIM_SPARES").map_or(true, |v| v.trim() != "0")) { + return; + } + { + let mut last = LAST.lock().unwrap(); + let now = std::time::Instant::now(); + if last.is_some_and(|t| now.duration_since(t) < std::time::Duration::from_secs(2)) { + return; + } + *last = Some(now); + } + super::title_list::trim_idle_spares(); +} + /// `XCL_PRESENT_PLANE=`: the one plane shown (None: all of them, composed) fn present_plane_only() -> Option { static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index ef8aed8b82..bf42b142f4 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -54,6 +54,10 @@ struct Pending { warm: Mutex>, /// what its first use tells besides `used::note` (`on_first_use`) on_use: Mutex>, + /// what it draws is drawn once and kept (`kept`): its draws wait until it is built + kept: std::sync::atomic::AtomicBool, + /// its shaders' names, for the line of a late one (`named`) + name: Mutex>>, } /// Whether one of the title's threads waits for the pipeline, and the preload worker building it. @@ -793,6 +797,8 @@ impl Pending { warned: Default::default(), warm: Mutex::new(warm), on_use: Default::default(), + kept: Default::default(), + name: Default::default(), } } @@ -850,6 +856,38 @@ pub(super) fn on_first_use(standin: usize, f: OnUse) { } } +/// The graphics pipeline behind stand-in `standin` draws what the title draws once and keeps +/// (`real::drawn_once`): its draws wait until it is built, whatever the thread has waited for +/// others (`XCL_GFX_PSO_WAIT_MS`). A retail title bakes its characters' faces into textures of +/// its own with a few draws at the start of its world, among some 500 pipelines never used +/// before: with 50 ms a second to wait, the bake's draws drew nothing and the heads stayed black +/// for the run. Told before the title has the stand-in. +pub(super) fn kept(standin: usize) { + if let Some(p) = entry(standin) { + p.kept.store(true, Ordering::Release); + } +} + +/// Whether what the pipeline behind stand-in `pso` draws is drawn once and kept (`kept`). +pub(super) fn is_kept(pso: usize) -> bool { + entry(pso).is_some_and(|p| p.kept.load(Ordering::Acquire)) +} + +/// The names of the shaders of the pipeline behind stand-in `standin`, for the line of a late +/// one (`XCL_TRACE_LATE=1`). Told before the title has the stand-in. +pub(super) fn named(standin: usize, name: Arc) { + if let Some(p) = entry(standin) { + *p.name.lock().unwrap() = Some(name); + } +} + +/// `XCL_TRACE_LATE=1` (a diagnostic): every graphics pipeline whose draws go on without it is +/// logged with its shaders' names. +pub(super) fn trace_late() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_LATE").is_ok_and(|v| v.trim() == "1")) +} + /// The shaders of a pipeline's set, told when the set's key is made (`real::OwnedDesc`). pub(crate) fn shaders_of(key: u64, shaders: Vec) { used::parts(key, shaders); @@ -2432,7 +2470,11 @@ pub fn resolve_wait(pso: usize) -> usize { /// `resolve_wait` with the budget of every pipeline (`XCL_PSO_WAIT_MS`), the one of graphics /// pipelines (`XCL_GFX_PSO_WAIT_MS`) and the one of compute pipelines (`XCL_CS_PSO_WAIT_MS`). fn resolve_wait_budgets(pso: usize, all: Option, gfx: Option, cs: Option) -> usize { - let Some(compute) = entry(pso).map(|p| p.compute) else { return pso }; + let Some((compute, kept)) = entry(pso).map(|p| (p.compute, p.kept.load(Ordering::Acquire))) else { return pso }; + if kept { + // (what it draws is drawn once: no budget, the draw waits for it) + return resolve_wait_for(pso, None); + } match gfx.filter(|_| !compute) { // the graphics budget is a thread's for a second, not one for each pipeline Some(budget) => { @@ -2692,6 +2734,10 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if n < 16 || n.is_power_of_two() { crate::xlog_warn!("D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", budget.as_millis(), n + 1); } + if trace_late() { + let name = p.name.lock().unwrap().clone(); + crate::xlog_info!("D3D12.X: late pipeline #{}: {}", n + 1, name.as_deref().unwrap_or("(no names)")); + } p.stand(pso) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e4f7a3e82f..558c2a28b3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1522,11 +1522,48 @@ fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { static NON_UMA_BUFFER_VIEWS: AtomicU64 = AtomicU64::new(0); +pub(super) fn trace_preskin() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_PRESKIN").is_ok_and(|v| v.trim() == "1")) +} + +fn trace_preskin_slot(who: &str, at: usize, words: &[u32]) { + if !trace_preskin() { + return; + } + let Some(u) = crate::gpu::uma::get() else { return }; + let rel = at.wrapping_sub(u.base()); + if (0xd580_0000..0xd588_0000).contains(&rel) { + let mod_off = (rel - 0xd580_0000) % 0x1900; + if mod_off == 33 * 32 || mod_off == 84 * 32 || mod_off == 24 * 32 || mod_off == 25 * 32 { + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k < 64 { + crate::xlog_info!("trace preskin slot #{k} ({who}): rel={rel:#x} (slot {}) words={words:08x?}", mod_off / 32); + } + } + } +} + /// V# of a buffer view (raw: 4-byte elements, num_records in bytes; structured / typed: /// stride = element size, num_records in elements); empty when the buffer is not in UMA. A /// buffer placed in a GPU view asks for the tiles of the range viewed (`view_want`). fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { let Some((at, bytes)) = console_buffer(res) else { + if trace_preskin() { + static M: AtomicU64 = AtomicU64::new(0); + let k = M.fetch_add(1, Ordering::Relaxed); + if k < 64 { + let ptr = res as *mut c_void; + let rd = unsafe { ID3D12Resource::from_raw_borrowed(&ptr).map(|r| r.GetDesc()) }; + let ta = title_address(res); + crate::xlog_info!( + "trace preskin buffer_view MISS #{k}: res={res:#x} title_addr={ta:#x?} rd={:?} fmt={} first={first} n={n} stride={stride} raw={raw}", + rd.map(|d| (d.Dimension.0, d.Width, d.Height, d.Flags.0)), + format.0 + ); + } + } note_buffer_view(); return [0; 4]; }; @@ -1775,7 +1812,16 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: let u = crate::gpu::uma::get()?; let mut d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC); let bytes = d.Width as usize; - let (k, tiles) = title_buffer_window(u, va, bytes)?; + let Some((k, tiles)) = title_buffer_window(u, va, bytes) else { + if trace_preskin() { + static N: AtomicU64 = AtomicU64::new(0); + let c = N.fetch_add(1, Ordering::Relaxed); + if c < 32 { + crate::xlog_info!("trace preskin place_at_title_address MISS #{c}: title_buffer_window None for va={va:#x} bytes={bytes:#x} state={state:#x} flags={:#x} win_va={:?}", d.Flags.0, u.window_of(va)); + } + } + return None; + }; let base = u.window(k).0; // a placed PC buffer starts at 64 KiB: one at another address starts below it and XCL adds // the difference where PC methods take an offset into it (`buffer_delta`) @@ -1787,6 +1833,13 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: if tiles { let view = super::view_want::want(super::view_want::Path::PlacedBuffer, va as u64, bytes as u64); let Some((hr, delta)) = super::sparse::place_buffer(this, va, &d, state, riid, ppv) else { + if trace_preskin() { + static N: AtomicU64 = AtomicU64::new(0); + let c = N.fetch_add(1, Ordering::Relaxed); + if c < 32 { + crate::xlog_info!("trace preskin place_at_title_address MISS #{c}: sparse::place_buffer None for va={va:#x} bytes={bytes:#x} state={state:#x} flags={:#x} view={view}", d.Flags.0); + } + } if view { static ONCE: AtomicU64 = AtomicU64::new(0); if ONCE.fetch_add(1, Ordering::Relaxed) == 0 { @@ -2239,6 +2292,165 @@ pub fn skip_named_cs(pso: usize) -> bool { !list.is_empty() && pso_shaders(pso).is_some_and(|(h, _)| list.contains(&h)) } +/// `XCL_TRACE_MS=` (diagnostic): the mesh shader whose draws `bind::trace_ms_draw` +/// writes down. +pub fn trace_ms() -> Option { + static V: OnceLock> = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_TRACE_MS").ok().and_then(|v| u64::from_str_radix(v.trim(), 16).ok())) +} + +/// `XCL_TRACE_RECORD=all` (diagnostic): track PSO shaders and log MS/PS names for every mesh pipeline. +pub fn trace_record_all() -> bool { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_TRACE_RECORD").is_ok_and(|v| v.trim().eq_ignore_ascii_case("all"))) +} + +fn trace_stage_name(stage: &'static str, hash: u64, blob: &[u8]) { + if !trace_record_all() && !std::env::var("XCL_TRACE_NAMES").is_ok_and(|v| v.trim() == "1") { + return; + } + static SEEN: Mutex>> = Mutex::new(None); + if !SEEN.lock().unwrap().get_or_insert_with(HashSet::new).insert((stage, hash)) { + return; + } + let mut names: Vec = Vec::new(); + let prefixes: &[&[u8]] = &[b"MS_", b"PS_", b"VS_", b"AS_", b"GS_", b"ms_", b"ps_", b"vs_"]; + let mut i = 0; + while i + 3 < blob.len() && names.len() < 4 { + if prefixes.iter().any(|p| &blob[i..i + 3] == *p) { + let n = blob[i..].iter().take_while(|b| b.is_ascii_alphanumeric() || **b == b'_').count(); + if n >= 6 { + let name = String::from_utf8_lossy(&blob[i..i + n]).into_owned(); + if !names.contains(&name) { + names.push(name); + } + } + i += n.max(1); + } else { + i += 1; + } + } + crate::xlog_info!("trace names: {stage} {hash:016x} ({} B): {names:?}", blob.len()); +} + +/// The name a console shader's container gives its program (its debug data: a stage prefix, +/// then letters, digits and underscores – `PS_BakeDecorations_1f2e3d4c_Wrapped`), None when it +/// has none. +fn stage_name(blob: &[u8]) -> Option<&str> { + let mut i = 0; + while i + 6 <= blob.len() { + if blob[i + 2] == b'_' && blob[i + 1] == b'S' && matches!(blob[i], b'P' | b'V' | b'M' | b'A' | b'G') { + let n = blob[i..].iter().take_while(|b| b.is_ascii_alphanumeric() || **b == b'_').count(); + if n >= 6 { + return std::str::from_utf8(&blob[i..i + n]).ok(); + } + i += n.max(1); + } else { + i += 1; + } + } + None +} + +/// The names of a graphics pipeline's shaders (`stage_name`), joined with `+`; None when none +/// has one. `keys`: each shader's key (`shader_key`), by which a name is looked for once. +fn stage_names(blobs: &[std::sync::Arc<[u8]>], keys: &[u64]) -> Option> { + static NAMES: Mutex>>>> = Mutex::new(None); + let mut all = String::new(); + for (b, &key) in blobs.iter().zip(keys) { + let known = NAMES.lock().unwrap().get_or_insert_with(HashMap::new).get(&key).cloned(); + let name = match known { + Some(n) => n, + None => { + let n: Option> = stage_name(b).map(Into::into); + NAMES.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, n.clone()); + n + } + }; + if let Some(n) = name { + if !all.is_empty() { + all.push('+'); + } + all.push_str(&n); + } + } + (!all.is_empty()).then(|| all.into()) +} + +/// Whether a pipeline with shaders of these names (`stage_names`) draws what the title draws +/// once and keeps: its texture bakes (`XCL_KEPT_DRAWS`: name parts, comma-separated; +/// `Bake,DecorationBlend` unless given, empty for none – a retail title's `PS_BakeDecorations_*` +/// and `PS_DecorationBlend_*`, the faces of its characters). Such a draw left out while its +/// pipeline is built (`XCL_GFX_PSO_WAIT_MS`) is never made again. +fn drawn_once(names: &str) -> bool { + static PARTS: OnceLock> = OnceLock::new(); + let parts = PARTS.get_or_init(|| { + let v = std::env::var("XCL_KEPT_DRAWS").unwrap_or_else(|_| "Bake,DecorationBlend".into()); + v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect() + }); + parts.iter().any(|p| names.contains(p.as_str())) +} + +#[cfg(test)] +mod stage_name_tests { + #[test] + fn a_shader_is_named_by_its_container() { + let mut blob = vec![0u8, 1, 2, b'P', b'S', b'_', 7, 9]; + blob.extend_from_slice(b"\0PS_BakeDecorations_1f2e3d4c_Wrapped\0rest"); + assert_eq!(super::stage_name(&blob), Some("PS_BakeDecorations_1f2e3d4c_Wrapped")); + assert_eq!(super::stage_name(b"no name in here PS_"), None); + assert_eq!(super::stage_name(b"CS_NotAGraphicsStage_0"), None); + } + + #[test] + fn a_bake_is_drawn_once() { + assert!(super::drawn_once("VS_FullScreen_0+PS_BakeDecorations_1f2e3d4c_Wrapped")); + assert!(super::drawn_once("VS_FullScreen_0+PS_DecorationBlend_0011_Wrapped")); + assert!(!super::drawn_once("MS_VS_PedTransformPreSkinD_0+PS_PedSkin_1")); + } + + #[test] + fn names_are_joined_and_looked_for_once() { + let blobs: Vec> = vec![b"..VS_TestStage_aa..".as_slice().into(), b"plain".as_slice().into(), b"PS_TestStage_bb".as_slice().into()]; + let keys = [0x7E57_0001_0000_0001u64, 0x7E57_0001_0000_0003, 0x7E57_0001_0000_0005]; + assert_eq!(super::stage_names(&blobs, &keys).as_deref(), Some("VS_TestStage_aa+PS_TestStage_bb")); + // (the same keys: the names kept, whatever the bytes) + let other: Vec> = vec![b"x".as_slice().into(), b"y".as_slice().into(), b"z".as_slice().into()]; + assert_eq!(super::stage_names(&other, &keys).as_deref(), Some("VS_TestStage_aa+PS_TestStage_bb")); + assert_eq!(super::stage_names(&other, &[0x7E57_0001_0000_0007, 0x7E57_0001_0000_0009, 0x7E57_0001_0000_000B]), None); + } +} + +/// `XCL_TRACE_MS` / `XCL_TRACE_NAMES=1` (a diagnostic): the `CS_*` names in a compute program's +/// container (its debug data), logged once per program of record. +fn trace_cs_name(record: u64, cs: &[u8]) { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| trace_ms().is_some() || std::env::var("XCL_TRACE_NAMES").is_ok_and(|v| v.trim() == "1")) { + return; + } + static SEEN: Mutex>> = Mutex::new(None); + if !SEEN.lock().unwrap().get_or_insert_with(HashSet::new).insert(record) { + return; + } + let mut names: Vec = Vec::new(); + let mut i = 0; + while i + 3 < cs.len() && names.len() < 3 { + if &cs[i..i + 3] == b"CS_" { + let n = cs[i..].iter().take_while(|b| b.is_ascii_alphanumeric() || **b == b'_').count(); + if n >= 6 { + let name = String::from_utf8_lossy(&cs[i..i + n]).into_owned(); + if !names.contains(&name) { + names.push(name); + } + } + i += n.max(1); + } else { + i += 1; + } + } + crate::xlog_info!("trace names: compute program of record {record:016x} ({} B): {names:?}", cs.len()); +} + pub fn pso_shaders(pso: usize) -> Option<(u64, u64)> { PSO_SHADERS.lock().unwrap().as_ref()?.get(&pso).copied() } @@ -2463,6 +2675,11 @@ unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: for k in 0..n as u64 { if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) { copy_words(&s, &d); + if trace_preskin() && !d.sampler { + let mut w = [0u32; 4]; + std::ptr::copy_nonoverlapping(d.at as *const u32, w.as_mut_ptr(), 4); + trace_preskin_slot("copy_console_slots", d.at, &w); + } } } true @@ -2840,7 +3057,9 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, super::ambient::note_descriptor(slot.at, 0, 0, 0, 0, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - return super::console_heap::write_shadow(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + let w = buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + trace_preskin_slot("srv_shadow_buf", slot.at, &w); + return super::console_heap::write_shadow(&slot, &w); } } let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; @@ -2902,7 +3121,9 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + let w = buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + trace_preskin_slot("srv_buf", slot.at, &w); + return super::console_heap::write(&slot, &w); } let rdesc = r.GetDesc(); let amb_fmt = desc.as_ref().map(|v| v.Format.0).filter(|&f| f != 0).unwrap_or(rdesc.Format.0); @@ -2911,6 +3132,17 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => super::console_heap::write(&slot, &t), None => { + if trace_preskin() { + static M: AtomicU64 = AtomicU64::new(0); + let k = M.fetch_add(1, Ordering::Relaxed); + if k < 32 { + crate::xlog_info!( + "trace preskin srv_tsharp None #{k}: cpu={cpu:#x} res={res:p} rd=({},{},{},{:#x}) desc={:?}", + rdesc.Dimension.0, rdesc.Width, rdesc.Format.0, rdesc.Flags.0, + desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0)) + ); + } + } note_buffer_view(); super::console_heap::write(&slot, &[0; 8]); } @@ -2994,6 +3226,7 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); super::view_want::want(super::view_want::Path::ViewAt, at, len); + trace_preskin_slot("srv_at_buf", slot.at, &words); return super::console_heap::write_shadow(&slot, &words); } let placed = super::format_alias::placed_srv_resource(this, rdesc, va, v.Format.0 as u32); @@ -3017,6 +3250,9 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let (words, at, len) = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); super::view_want::want(super::view_want::Path::ViewAt, at, len); + // (no buffer is placed there: with `XCL_SPARSE_LAZY` its tiles would have no video memory) + super::sparse::gpu_writes(at as usize, len as usize); + trace_preskin_slot("uav_at_buf", slot.at, &words); return super::console_heap::write_shadow(&slot, &words); } let placed = super::format_alias::placed_uav_resource(this, rdesc, va, v.Format.0 as u32); @@ -3618,7 +3854,9 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, true); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; - return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + let w = buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + trace_preskin_slot("uav_buf", slot.at, &w); + return super::console_heap::write(&slot, &w); } // UAV dimensions: 1 buffer, 2 tex1d, 3 tex1d array, 4 tex2d, 5 tex2d array, 8 tex3d let (format, dim, array, mip) = match desc.as_ref() { @@ -5584,6 +5822,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } note_translated_compute(0, ppv); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (record, 0)); + trace_cs_name(record, cs); if super::gpu_profile::on() || super::gpu_times::enabled() { super::gpu_profile::note_compute(record, cs, dxil.len(), wave32_only(this)); } @@ -5626,6 +5865,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } note_translated_compute(hr, ppv); PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (record, 0)); + trace_cs_name(record, cs); if super::gpu_profile::on() || super::gpu_times::enabled() { super::gpu_profile::note_compute(record, cs, dxil.len(), wave32_only(this)); } @@ -7032,21 +7272,30 @@ enum OwnedDesc { Stream(Box<[usize; 2]>, Vec, Vec>), } +/// Entries an interning pool of shader bytecode takes between two sweeps of its dead ones: a +/// `Weak` to an `Arc<[u8]>` keeps the whole allocation, bytes and all, until it is dropped, so a +/// pool swept only at 8192 / 16384 entries held thousands of dead shaders' bytes. +pub(super) const SHADER_POOL_SWEEP: usize = 1024; + +/// `intern_shader_blob`'s pool, and its length at which the dead entries are swept next. +#[allow(clippy::type_complexity)] +static SHADER_BLOB_POOL: Mutex>, usize)>> = Mutex::new(None); + /// Share one heap copy of identical console shader bytecodes across all live `OwnedDesc`s. fn intern_shader_blob(bytes: &[u8]) -> std::sync::Arc<[u8]> { use std::sync::{Arc, Weak}; - static CACHE: Mutex>>> = Mutex::new(None); let key = (crate::gpu::shader::fnv64(bytes), bytes.len()); - let mut g = CACHE.lock().unwrap_or_else(|e| e.into_inner()); - let m = g.get_or_insert_with(HashMap::new); + let mut g = SHADER_BLOB_POOL.lock().unwrap_or_else(|e| e.into_inner()); + let (m, next_sweep) = g.get_or_insert_with(|| (HashMap::new(), SHADER_POOL_SWEEP)); if let Some(arc) = m.get(&key).and_then(Weak::upgrade) { if arc.as_ref() == bytes { return arc; } } let arc: Arc<[u8]> = Arc::from(bytes); - if m.len() >= 16_384 && m.len().is_power_of_two() { + if m.len() >= *next_sweep { m.retain(|_, w| w.strong_count() > 0); + *next_sweep = m.len() + SHADER_POOL_SWEEP; } m.insert(key, Arc::downgrade(&arc)); arc @@ -7104,6 +7353,20 @@ mod shaders_key_tests { let c = super::intern_shader_blob(&[0xDE, 0xAD, 0xBE, 0xEF, 1, 2, 3, 5]); assert!(!std::sync::Arc::ptr_eq(&a, &c)); } + + /// Shaders no pipeline holds any more do not pile up in the pool (each dead entry keeps its + /// bytes): after 3000 short-lived ones, fewer than two sweeps' worth are left. + #[test] + fn interned_shader_blobs_that_died_are_swept() { + for i in 0u32..3000 { + let mut bytes = vec![0xC3u8; 64]; + bytes[..4].copy_from_slice(&i.to_le_bytes()); + drop(super::intern_shader_blob(&bytes)); + } + let g = super::SHADER_BLOB_POOL.lock().unwrap(); + let dead = g.as_ref().map_or(0, |(m, _)| m.values().filter(|w| w.strong_count() == 0).count()); + assert!(dead < 2 * super::SHADER_POOL_SWEEP, "{dead} dead entries kept"); + } } impl OwnedDesc { @@ -7369,6 +7632,11 @@ unsafe fn go_background( }; // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); + // (a graphics pipeline's shaders by name: one that draws once and is kept is waited for) + let names = match &owned { + OwnedDesc::Graphics(_, b, ..) | OwnedDesc::Stream(_, _, b) => stage_names(b, &parts), + OwnedDesc::Compute(..) => None, + }; let owned = std::sync::Arc::new(owned); let warm: Option = matches!(*owned, OwnedDesc::Graphics(..)).then(|| { let owned = owned.clone(); @@ -7393,6 +7661,19 @@ unsafe fn go_background( if driver != 0 { super::pso_async::shared(*ppv as usize, driver); } + if let Some(names) = names { + if drawn_once(&names) { + super::pso_async::kept(*ppv as usize); + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: pipeline of {names}: what it draws is drawn once and kept – its draws wait until it is built (#{n})"); + } + } + if super::pso_async::trace_late() { + super::pso_async::named(*ppv as usize, names); + } + } if image_only { super::pso_async::image_only(*ppv as usize); } @@ -8352,6 +8633,36 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri out.raw(*ty, &p, palign == 8); continue; } + // `XCL_TRACE_MS_FORCE=1` (a diagnostic): the traced mesh shader's pipelines draw with no + // depth or stencil test (DEPTH_STENCIL / 1 / 2: DepthEnable, .., .., StencilEnable) and + // no culling (RASTERIZER / 1 / 2: FillMode, CullMode) + if trace_ms() == Some(crate::gpu::shader::fnv64(ms)) && std::env::var("XCL_TRACE_MS_FORCE").is_ok_and(|v| v.trim() == "1") { + let mut p = payload.to_vec(); + if matches!(*ty, 11 | 21 | 26) && p.len() >= 16 { + p[0..4].copy_from_slice(&0u32.to_le_bytes()); + p[12..16].copy_from_slice(&0u32.to_le_bytes()); + crate::xlog_info!("trace MS force: depth and stencil tests off (subobject {ty})"); + out.raw(*ty, &p, palign == 8); + continue; + } + if matches!(*ty, 10 | 27 | 28) && p.len() >= 8 { + p[4..8].copy_from_slice(&1u32.to_le_bytes()); + crate::xlog_info!("trace MS force: culling off (subobject {ty})"); + out.raw(*ty, &p, palign == 8); + continue; + } + } + // DEPTH_STENCIL / 1 / 2 start alike: DepthEnable, DepthWriteMask, DepthFunc + if matches!(*ty, 11 | 21 | 26) && payload.len() >= 12 { + let word = |k: usize| u32::from_le_bytes(payload[4 * k..4 * k + 4].try_into().unwrap()); + mesh_depth_diag(rt_count, [word(0), word(1), word(2)], crate::gpu::shader::fnv64(ms)); + if let Some(func) = mesh_depth_as(word(1), word(2)).filter(|_| word(0) != 0) { + let mut p = payload.to_vec(); + p[8..12].copy_from_slice(&func.to_le_bytes()); + out.raw(*ty, &p, palign == 8); + continue; + } + } out.raw(*ty, payload, palign == 8); } } @@ -8359,13 +8670,61 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri if hr >= 0 { super::ambient::note_graphics_pso(*ppv as usize, console_ps); super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); - if super::gpu_times::enabled() { - PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(ms), console_ps.map_or(0, crate::gpu::shader::fnv64))); + if super::gpu_times::enabled() || trace_ms().is_some() || trace_record_all() { + let ms_h = crate::gpu::shader::fnv64(ms); + let ps_h = console_ps.map_or(0, crate::gpu::shader::fnv64); + PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (ms_h, ps_h)); + trace_stage_name("MS", ms_h, ms); + if let Some(ps) = console_ps { + trace_stage_name("PS", ps_h, ps); + } } } Some(hr) } +/// `XCL_MESH_DEPTH_LOG=1` (diagnostic): the depth state of the title's mesh pipelines as they are +/// built – each (render targets, DepthEnable, DepthWriteMask, DepthFunc) the first time, with the +/// mesh shader that came with it, then at every power of two. +fn mesh_depth_diag(rts: u32, depth: [u32; 3], ms: u64) { + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var("XCL_MESH_DEPTH_LOG").is_ok_and(|v| v == "1")) { + return; + } + static SEEN: Mutex>> = Mutex::new(None); + let n = { + let mut g = SEEN.lock().unwrap(); + let n = g.get_or_insert_with(HashMap::new).entry((rts, depth)).or_insert(0); + *n += 1; + *n + }; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: mesh pipeline depth state: {rts} render targets, depth enable {} write {} func {}: {n} so far (MS {ms:016x})", depth[0], depth[1], depth[2]); + } +} + +/// `XCL_MESH_DEPTH_MAP=wf=[,…]` (diagnostic): a mesh pipeline with that depth +/// write mask and comparison gets the comparison on the right instead (`w0f7=8`: the ones that +/// test GREATER_EQUAL without writing always pass) – tells a colour pass that fails its depth +/// test against the pre-pass from one that draws nothing at all. +fn mesh_depth_as(write: u32, func: u32) -> Option { + static V: OnceLock> = OnceLock::new(); + V.get_or_init(|| mesh_depth_map(std::env::var("XCL_MESH_DEPTH_MAP").ok().as_deref())) + .iter() + .find(|m| (m.0, m.1) == (write, func)) + .map(|m| m.2) +} + +fn mesh_depth_map(v: Option<&str>) -> Vec<(u32, u32, u32)> { + let one = |s: &str| -> Option<(u32, u32, u32)> { + let (from, to) = s.trim().split_once('=')?; + let (w, f) = from.strip_prefix('w')?.split_once('f')?; + let to: u32 = to.parse().ok()?; + (1..=8).contains(&to).then_some((w.parse().ok()?, f.parse().ok()?, to)) + }; + v.map(|v| v.split(',').filter_map(one).collect()).unwrap_or_default() +} + /// A graphics PSO with a console VS + GS: the GS pipeline in two passes, as a mesh pipeline /// with the description's state. unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs: &[u8], gs: &[u8], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { @@ -9101,12 +9460,37 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void let hr = pipeline_state(this, desc, riid, ppv); // `XCL_CAPTURE_FRAME`: a stream the graphics and compute paths did not note (mesh) if super::capture::enabled() && hr >= 0 && !ppv.is_null() { - super::capture::note_stream(*ppv as usize); + if !note_mesh_stream_for_capture(desc, *ppv as usize) { + super::capture::note_stream(*ppv as usize); + } } note_mesh_stream_for_dump(desc, ppv, hr); hr } +/// `XCL_CAPTURE_FRAME`: a pipeline stream with a console mesh shader is noted with its MS and PS +/// and the depth state it names, so a captured frame tells its mesh pipelines apart. False: not +/// such a stream. +unsafe fn note_mesh_stream_for_capture(desc: *const c_void, pso: usize) -> bool { + if !crate::gpu::shader::readable(desc as usize, 16) { + return false; + } + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + if !crate::gpu::shader::readable(base, size) { + return false; + } + let subs = known_subobjects(std::slice::from_raw_parts(base as *const u8, size)); + let Some(m) = mesh_stream_for_dump(&subs) else { return false }; + // DEPTH_STENCIL / 1 / 2 start alike: DepthEnable, DepthWriteMask, DepthFunc + let depth = subs.iter().find(|(ty, p)| matches!(*ty, 11 | 21 | 26) && p.len() >= 12).map(|(_, p)| { + let word = |k: usize| u32::from_le_bytes(p[4 * k..4 * k + 4].try_into().unwrap()); + [word(0), word(1), word(2)] + }); + let formats: Vec = m.formats.iter().map(|f| f.0).collect(); + super::capture::note_mesh_stream(pso, &m.stages, depth, &formats); + true +} + /// `XCL_DUMP_TARGETS`: a pipeline stream with a console mesh shader (`translated_mesh_stream`) /// is noted with its MS and PS, render target 0's blend and the formats, as a graphics desc is /// (`note_pipeline_for_dump`): without it a dumped target drawn by mesh pipelines lists them as diff --git a/crates/xcl/src/hle/d3d12x/small_tex.rs b/crates/xcl/src/hle/d3d12x/small_tex.rs index 0a2ba2a855..bff211482b 100644 --- a/crates/xcl/src/hle/d3d12x/small_tex.rs +++ b/crates/xcl/src/hle/d3d12x/small_tex.rs @@ -1,8 +1,8 @@ //! Small sampled textures of the title that get no shared pages (`vram::place_pages` refuses them: //! a 1D texture cannot be a reserved resource) on 4 KiB placements in heaps of XCL's own -//! (`XCL_SMALL_TEXTURES=1`), instead of a committed resource each: a committed resource takes at -//! least 64 KiB of video memory, and a title's thousands of tiny lookup textures (a few hundred -//! bytes each) took ~300 MiB that way. +//! (on by default, `XCL_SMALL_TEXTURES=0` turns it off), instead of a committed resource each: a +//! committed resource takes at least 64 KiB of video memory, and a title's thousands of tiny +//! lookup textures (a few hundred bytes each) took ~300 MiB that way. //! //! Only what the PC itself allows: no render target, depth or UAV flags, one sample, and //! `GetResourceAllocationInfo` giving `D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT` (4 KiB) for the @@ -29,10 +29,11 @@ const UNIT: u64 = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64; const HEAP_BYTES: u64 = 4 << 20; const UNITS: usize = (HEAP_BYTES / UNIT) as usize; -/// Whether small sampled textures go on 4 KiB placements (`XCL_SMALL_TEXTURES=1`). +/// Whether small sampled textures go on 4 KiB placements: on by default (`XCL_SMALL_TEXTURES=0` +/// turns it off), off in unit tests unless they ask for it. pub(super) fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_SMALL_TEXTURES").is_ok_and(|v| v.trim() == "1")) + *ON.get_or_init(|| std::env::var("XCL_SMALL_TEXTURES").map_or(!cfg!(test), |v| v.trim() == "1")) } /// The units of one heap: first fit of a run of `n`. diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 3325cbbf6b..7094169fdd 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -718,6 +718,10 @@ struct State { /// tiles over a CPU view left without video memory for `mirror_cap`, or as none was to be had: /// given it once there is room (`retry_refused`), or once their CPU view is written refused: FxHashSet, + /// tile runs (first, end; sorted, apart) the title made unordered-access buffer views by + /// address over (`gpu_writes`): a compute program writes there with no buffer placed on it + /// and no write of the CPU's, so with `lazy_commits` a commit there maps at once + gpu_written: Vec<(usize, usize)>, /// when a tile over a CPU view last found no video memory (`take_tile`): for a moment the /// others do not try to make a heap again (each tried, and logged it), and the refused ones /// wait @@ -1218,6 +1222,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -1591,7 +1596,7 @@ impl State { let mut new = false; while t < end { if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() { - if self.parked.contains_key(&t) || self.kept.contains_key(&t) { + if self.parked.contains_key(&t) || self.kept.contains_key(&t) || in_runs(&self.gpu_written, t) { self.ensure_mapped(t, TILE, |_| 0xFFFF); } else { self.mapped.insert(t, TileEntry::with_holes(LAZY, 0xFFFF)); @@ -1659,6 +1664,16 @@ impl State { self.to_zero.extend(reused); } + /// The title made unordered-access buffer views by address over `ranges` (`gpu_writes`): + /// their tiles listed with no video memory get it now (`give_memory`), and those committed + /// later get it at the commit (`ensure_listed`). + unsafe fn gpu_written(&mut self, ranges: &[(usize, usize)]) { + for &(a, n) in ranges { + add_run(&mut self.gpu_written, a & !(TILE - 1), a.saturating_add(n).saturating_add(TILE - 1) & !(TILE - 1)); + } + self.give_memory(ranges); + } + /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_holes` supplies /// the initial 16-bit hole mask for each newly mapped 64 KiB tile. Tiles over a CPU view /// (`mirror_src`) are left to `new_mirror`. @@ -3535,6 +3550,36 @@ pub fn forget_mirrors(a: usize, n: usize) { unsafe { s.forget_mirrors_in(a, end) }; } +/// `XCL_TRACE_MS` (a diagnostic): what the window tile of GPU-view address `va` is now: asked +/// for or not, what it is linked over, its video memory (source, holes, pages sent), and +/// whether it waits or was refused. +pub fn view_tile_diag(va: usize) -> String { + let w = va & !(TILE - 1); + let asked = MIRROR_ASKED.contains(w); + let queued = MIRROR_ASKS.lock().unwrap().contains(&w); + let shows = match tile_shows(w) { + Under::Cpu(c) => format!("cpu {c:#x}"), + Under::Nothing => "nothing".to_string(), + Under::NoView => "no view".to_string(), + }; + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return format!("tile {w:#x}: no sparse state") }; + let mapped = s.mapped.get(&w).map(|e| { + let page = (va & (TILE - 1)) / PAGE; + format!("pool {:?} src {:#x} holes {:04x} sent pages {} (page {page} sent: {})", e.pool, e.src, e.holes, e.sent.iter().filter(|p| p.is_some()).count(), e.sent[page].is_some()) + }); + format!( + "tile {w:#x}: asked {asked} queued {queued} shows {shows} linked {:x?} mapped {mapped:?} later {} refused {} parked {} kept {} asks {} remaps {}", + s.mirror_src.get(&w), + s.later.iter().any(|&(t, _)| t == w), + s.refused.contains(&w), + s.parked.contains_key(&w), + s.kept.contains_key(&w), + s.asks.contains(&w), + s.remaps.contains(&w), + ) +} + /// The CPU address behind window address `va`, for what reads or writes the title's memory /// there: `va` itself, unless it lies in a GPU view of the title's CPU memory, whose tiles show /// their CPU view (`State::map_mirrors` takes them by the same rule), or where the page the @@ -4280,6 +4325,10 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let asks = std::mem::take(&mut *WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner())); s.give_memory(&asks); } + if GPU_WRITE_ASKING.swap(false, Ordering::AcqRel) { + let asks = std::mem::take(&mut GPU_WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner()).0); + s.gpu_written(&asks); + } let waited = t0.elapsed().as_micros() as u64; PHASES[0].fetch_add(waited, Ordering::Relaxed); SUBMIT_US.fetch_add(waited, Ordering::Relaxed); @@ -4378,6 +4427,48 @@ pub(super) unsafe fn cpu_waited_for_mappings(fence: &ID3D12Fence, value: u64, wh reached } +/// `[a, end)` joined to the sorted runs `runs` that lie apart; whether it added anything. +fn add_run(runs: &mut Vec<(usize, usize)>, a: usize, end: usize) -> bool { + if a >= end { + return false; + } + let first = runs.partition_point(|r| r.1 < a); + let after = runs.partition_point(|r| r.0 <= end); + if after == first + 1 && runs[first].0 <= a && end <= runs[first].1 { + return false; + } + let joined = runs[first..after].iter().fold((a, end), |j, r| (j.0.min(r.0), j.1.max(r.1))); + runs.splice(first..after, [joined]); + true +} + +/// Whether `t` lies in one of the sorted runs `runs`. +fn in_runs(runs: &[(usize, usize)], t: usize) -> bool { + let i = runs.partition_point(|r| r.1 <= t); + runs.get(i).is_some_and(|r| r.0 <= t) +} + +/// The ranges `gpu_writes` was told of that no submit has taken yet, and all of them so far as +/// tile runs (a title makes the same views again every frame: each range is queued once). +static GPU_WRITE_ASKS: Mutex<(Vec<(usize, usize)>, Vec<(usize, usize)>)> = Mutex::new((Vec::new(), Vec::new())); +static GPU_WRITE_ASKING: AtomicBool = AtomicBool::new(false); + +/// The title made an unordered-access buffer view by address over `[va, va + len)` of a sparse +/// window: no buffer is placed there and the CPU may never write it, so with `lazy_commits` its +/// tiles would have no video memory and what a compute program writes through the view would go +/// nowhere (a retail title's lighting and video planes: black rooms, wrong colours). Its tiles +/// get video memory from the next submit on (`State::gpu_written`). Never waits for the state. +pub(super) fn gpu_writes(va: usize, len: usize) { + if len == 0 || !lazy_commits() { + return; + } + let mut g = GPU_WRITE_ASKS.lock().unwrap_or_else(|e| e.into_inner()); + if add_run(&mut g.1, va & !(TILE - 1), va.saturating_add(len).saturating_add(TILE - 1) & !(TILE - 1)) { + g.0.push((va, len)); + GPU_WRITE_ASKING.store(true, Ordering::Release); + } +} + /// What the title's lists being recorded will write on the GPU in the sparse windows (address, /// bytes; `will_write`), taken by the next submit: with `lazy_commits` a tile there may have no /// video memory yet, and the write would go nowhere. @@ -5312,6 +5403,7 @@ mod tests { fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -5645,6 +5737,7 @@ mod tests { fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -5884,6 +5977,7 @@ mod tests { fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -6012,6 +6106,7 @@ mod tests { fill_pages: fill_pages(), mirrored: 0, mirror_cap: mirror_cap(), + gpu_written: Vec::new(), refused: FxHashSet::default(), no_memory: None, starved: Vec::new(), @@ -6312,6 +6407,44 @@ mod tests { drop(lazy); } + /// Memory the title made an unordered-access view by address over: a tile listed with no + /// video memory gets it when the view is made known, and one committed afterwards gets it at + /// its commit; a tile outside the view stays listed. + #[test] + fn a_lazy_tile_under_an_unordered_access_view_by_address_gets_video_memory() { + unsafe { + let lazy = Lazy::on(true); + let Some((base, mut s, _queue)) = lazy_state(4) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") }; + s.commit_range(base, TILE); + s.commit_range(base + 3 * TILE, TILE); + assert_eq!(s.mapped[&base].pool, LAZY, "listed at the commit"); + // a view of tiles 0 and 1 (bytes inside them) + s.gpu_written(&[(base + 0x100, TILE + 0x40)]); + assert_ne!(s.mapped[&base].pool, LAZY, "the listed tile under the view got memory"); + assert_eq!(s.mapped[&(base + 3 * TILE)].pool, LAZY, "the tile outside it did not"); + s.commit_range(base + TILE, TILE); + assert_ne!(s.mapped[&(base + TILE)].pool, LAZY, "committed under the view: mapped at the commit"); + s.commit_range(base + 2 * TILE, TILE); + assert_eq!(s.mapped[&(base + 2 * TILE)].pool, LAZY, "committed outside it: listed"); + drop(lazy); + } + } + + #[test] + fn runs_join_and_find() { + let mut r = Vec::new(); + assert!(add_run(&mut r, 0x30000, 0x40000)); + assert!(add_run(&mut r, 0x10000, 0x20000)); + assert!(!add_run(&mut r, 0x10000, 0x20000), "known already"); + assert!(!add_run(&mut r, 0x5000, 0x5000), "empty"); + assert_eq!(r, vec![(0x10000, 0x20000), (0x30000, 0x40000)]); + assert!(in_runs(&r, 0x10000) && in_runs(&r, 0x3ffff) && !in_runs(&r, 0x20000) && !in_runs(&r, 0x40000) && !in_runs(&r, 0)); + assert!(add_run(&mut r, 0x20000, 0x30000), "the gap between two runs joins them"); + assert_eq!(r, vec![(0x10000, 0x40000)]); + assert!(add_run(&mut r, 0x8000, 0x50000)); + assert_eq!(r, vec![(0x8000, 0x50000)]); + } + /// Decommitting a tile with no video memory frees and parks nothing; committed again it is /// listed again. With the switch off a commit maps at once, as before. #[test] diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index bf9cc74b63..fb3a9f231f 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -839,14 +839,15 @@ fn capacity(bytes: u64) -> Option { } /// The most bytes of idle upload buffers kept for the next batches (`XCL_UPLOAD_KEEP_MB`, default -/// 512): memory of the system's (upload heaps), the process's commit and RAM while kept. +/// 64): memory of the system's (upload heaps), the process's commit and RAM while kept. (A +/// retail title's world ran with 64 MB kept: ~60 MB idle, a few MB in flight.) fn free_bytes() -> u64 { static V: std::sync::OnceLock = std::sync::OnceLock::new(); *V.get_or_init(|| keep_bytes_of(std::env::var("XCL_UPLOAD_KEEP_MB").ok().as_deref())) } fn keep_bytes_of(v: Option<&str>) -> u64 { - v.and_then(|v| v.trim().parse::().ok()).map_or(512, |mb| mb.min(4096)) << 20 + v.and_then(|v| v.trim().parse::().ok()).map_or(64, |mb| mb.min(4096)) << 20 } /// Bytes of the upload buffers kept idle now. @@ -944,10 +945,10 @@ mod tests { #[test] fn the_idle_upload_buffers_kept_follow_the_switch() { - assert_eq!(keep_bytes_of(None), 512 << 20, "unset: as before"); - assert_eq!(keep_bytes_of(Some(" 64 ")), 64 << 20); + assert_eq!(keep_bytes_of(None), 64 << 20, "unset: 64 MB"); + assert_eq!(keep_bytes_of(Some(" 512 ")), 512 << 20); assert_eq!(keep_bytes_of(Some("0")), 0, "none kept"); - assert_eq!(keep_bytes_of(Some("lots")), 512 << 20); + assert_eq!(keep_bytes_of(Some("lots")), 64 << 20); assert_eq!(keep_bytes_of(Some("100000")), 4096 << 20); } diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 28f7b84d74..6065ff937e 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -180,6 +180,7 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: let mut old = std::mem::take(&mut b.extra_active); old.extend(std::mem::replace(&mut b.first, stand_in)); b.spares.extend(old.iter().copied()); + parked_anew(&old); old } else { Vec::new() @@ -293,13 +294,108 @@ pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { let mut sg = SEGMENTS.lock().unwrap(); let spares = &mut sg.as_mut()?.get_mut(&(wrapper as usize))?.spares; let k = spares.iter().rposition(|&p| !super::alloc_pool::in_flight(p))?; - Some(spares.remove(k) as *mut c_void) + let pc = spares.remove(k); + // (in use again: it is idle anew when it is parked again) + parked_anew(&[pc]); + Some(pc as *mut c_void) +} + +/// `pcs` were just parked (or taken again, or released): what `trim_idle_spares` saw at their +/// addresses before does not count. A list released with its title list, or a new list the +/// driver made at a released one's address, must not be taken for a spare idle long since – +/// a list parked at a `KickoffX` is submitted after it is parked. (SEGMENTS may be held: it is +/// taken before SPARE_SEEN everywhere.) +fn parked_anew(pcs: &[usize]) { + if let Some(m) = SPARE_SEEN.lock().unwrap().as_mut() { + for p in pcs { + m.remove(p); + } + } +} + +/// Spare PC lists `trim_idle_spares` has seen parked, and when it first saw each. +static SPARE_SEEN: Mutex>> = Mutex::new(None); +/// Spare PC lists released by `trim_idle_spares` so far. +static SPARES_RELEASED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// A spare idle this long (seen parked, not reused, its last submit done) can go. +const SPARE_IDLE: std::time::Duration = std::time::Duration::from_secs(2); +/// Spares kept per title list whatever their age (the latest parked: the next split takes them). +const SPARES_KEPT: usize = 2; + +/// Which of `spares` (oldest first) go: past the last `keep`, seen parked for `idle` at `now` +/// (`seen`; a spare not seen yet is noted as seen now) and not in flight. +fn idle_spares(spares: &[usize], seen: &mut HashMap, keep: usize, idle: std::time::Duration, now: std::time::Instant, in_flight: impl Fn(usize) -> bool) -> Vec { + let old = spares.len().saturating_sub(keep); + let mut gone = Vec::new(); + for (i, &p) in spares.iter().enumerate() { + let since = *seen.entry(p).or_insert(now); + if i < old && now.duration_since(since) >= idle && !in_flight(p) { + gone.push(p); + } + } + gone +} + +/// Releases the spare PC lists of the title's lists that have been idle for `SPARE_IDLE`, past +/// the last `SPARES_KEPT` of each. A spare holds the memory of the driver's list object and of +/// what it last recorded until it is released, and the pools grew to the largest burst of +/// splits a list ever had (AMD: 1,800–4,000 spares; xcl-dev/xcl#3110, #3122). Returns the +/// spares left and released now. +pub(super) fn trim_idle_spares() -> (usize, usize) { + let now = std::time::Instant::now(); + let mut gone: Vec<(usize, usize)> = Vec::new(); + let mut left = 0; + { + let mut sg = SEGMENTS.lock().unwrap(); + let Some(m) = sg.as_mut() else { return (0, 0) }; + let mut seen_g = SPARE_SEEN.lock().unwrap(); + let seen = seen_g.get_or_insert_with(HashMap::new); + let mut parked = std::collections::HashSet::new(); + for (&wrapper, b) in m.iter_mut() { + let go = idle_spares(&b.spares, seen, SPARES_KEPT, SPARE_IDLE, now, super::alloc_pool::in_flight); + if !go.is_empty() { + b.spares.retain(|p| !go.contains(p)); + gone.extend(go.into_iter().map(|p| (wrapper, p))); + } + left += b.spares.len(); + parked.extend(b.spares.iter().copied()); + } + seen.retain(|p, _| parked.contains(p)); + } + if gone.is_empty() { + return (left, 0); + } + { + let mut wg = WRAPPER_OF.lock().unwrap(); + if let Some(m) = wg.as_mut() { + for &(wrapper, seg) in &gone { + if m.get(&seg) == Some(&wrapper) { + m.remove(&seg); + } + } + } + } + for &(_, seg) in &gone { + let raw = seg as *mut c_void; + super::alloc_pool::forget_list(seg); + super::bind::forget(raw); + unsafe { + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(raw, 2)); + rel(raw); + } + } + let n = gone.len(); + let total = SPARES_RELEASED.fetch_add(n, std::sync::atomic::Ordering::Relaxed) + n; + crate::xlog_info!("D3D12.X: title lists: {n} idle spare PC lists released ({total} so far), {left} spares kept"); + (left, n) } /// Give back to `wrapper`'s spare pool a closed PC command list that did not become a segment. pub(super) fn put_spare(wrapper: *mut c_void, pc: *mut c_void) { let mut sg = SEGMENTS.lock().unwrap(); sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); + parked_anew(&[pc as usize]); } /// The closed PC command lists `wrapper` keeps for reuse. @@ -362,6 +458,9 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut } } book.spares.extend(extra.iter().copied()); + // (they are submitted after this, outside the lock: not idle yet whatever was seen at + // their address before) + parked_anew(&extra); (prior, extra) }; drop(sg); @@ -444,6 +543,7 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { } } if let Some(b) = book { + parked_anew(&b.spares); for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first) { let raw = seg as *mut c_void; super::alloc_pool::forget_list(seg); @@ -747,4 +847,41 @@ mod tests { drop(Box::from_raw(seg1)); } } + + /// Idle spares go once seen parked for the idle time, oldest first, past the last ones kept, + /// and never while their last submit is on the GPU; a spare seen for the first time is only + /// noted. + #[test] + fn idle_spares_go_once_seen_idle_past_the_kept_ones() { + let t0 = std::time::Instant::now(); + let idle = std::time::Duration::from_secs(2); + let spares = [10usize, 11, 12, 13, 14]; + let mut seen = HashMap::new(); + // first sight: noted, none goes + assert!(idle_spares(&spares, &mut seen, 2, idle, t0, |_| false).is_empty()); + assert_eq!(seen.len(), 5); + // not idle long enough yet + assert!(idle_spares(&spares, &mut seen, 2, idle, t0 + std::time::Duration::from_secs(1), |_| false).is_empty()); + // idle: the three oldest go, the last two stay; one still on the GPU stays too + let t = t0 + idle; + assert_eq!(idle_spares(&spares, &mut seen, 2, idle, t, |p| p == 11), vec![10, 12]); + // a spare seen only now (parked again after a reuse) waits its own idle time + seen.remove(&10); + assert_eq!(idle_spares(&spares, &mut seen, 2, idle, t, |_| false), vec![11, 12]); + // fewer than kept: nothing goes + assert!(idle_spares(&spares[..2], &mut seen, 2, idle, t + idle, |_| false).is_empty()); + } + + /// A list parked where a released spare was seen long ago (the driver reuses addresses; a + /// list parked at a KickoffX is submitted only after it is parked) starts its idle time again. + #[test] + fn a_list_parked_anew_starts_its_idle_time_again() { + let (wrapper, pc) = (0x7e57_0000_1000usize, 0x7e57_0000_2000usize); + let now = std::time::Instant::now(); + let long_ago = now.checked_sub(std::time::Duration::from_secs(60)).unwrap_or(now); + SPARE_SEEN.lock().unwrap().get_or_insert_with(HashMap::new).insert(pc, long_ago); + put_spare(wrapper as *mut c_void, pc as *mut c_void); + assert!(!SPARE_SEEN.lock().unwrap().as_ref().unwrap().contains_key(&pc)); + SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&wrapper); + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 18bad6a4b9..56757afc99 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -110,7 +110,7 @@ struct Table { by_res: BTreeMap, /// Active `(va, PC texture)` → end address (`va + size`); entries with different `(va, end)` are disjoint by_va: BTreeMap<(usize, usize), usize>, - /// Older overlapped textures kept dormant until released or uncovered when a newer one is released + /// Older overlapped textures kept dormant until sampled again or uncovered by a release shadowed: BTreeMap, /// Shadowed `(va, PC texture)` → end address (may overlap) shadowed_by_va: BTreeMap<(usize, usize), usize>, @@ -123,11 +123,25 @@ struct Table { src_pieces: BTreeMap>, /// textures whose first upload is still to come (`Entry::pending`; may name ones that went) pending_res: std::collections::BTreeSet, + /// shadowed textures `uncover` shadowed again: a draw recorded before may still sample them, + /// so their source stays linked and refreshes upload them until `Displaced::until` + displaced: BTreeMap, /// 16 MiB blocks of the textures' sources -> how many active ones cover it: the part of the /// watched ranges that textures make (cheap to rebuild from, unlike all textures) coarse: BTreeMap, } +/// A texture of `Table::displaced`. +struct Displaced { + /// the frame (`present::counters`) from which it is no longer uploaded as shadowed + until: u64, + /// its first upload is still to come (it stays `Entry::pending`, uncounted in `PENDING`) + whole: bool, +} + +/// how many frames a draw that sampled a texture `uncover` shadowed again may wait for its submit +const DISPLACED_FRAMES: u64 = 2; + /// the size of `Table::coarse`'s blocks const SRC_COARSE_SHIFT: usize = 24; @@ -154,6 +168,7 @@ impl Table { next_seq: 0, src_pieces: BTreeMap::new(), pending_res: std::collections::BTreeSet::new(), + displaced: BTreeMap::new(), coarse: BTreeMap::new(), } } @@ -202,7 +217,25 @@ impl Table { } } - /// The textures (active) whose source the dirty pages `dirty` (sorted) may touch. + /// `res` (shadowed, `e`) leaves `displaced`: its source is no longer watched for it. + fn undisplace(&mut self, res: usize, e: &Entry) { + if self.displaced.remove(&res).is_some() { + self.unlink_src(res, e.src, e.tex.size() as usize); + } + } + + /// The displaced textures kept until `frame` or before stay shadowed only. + fn expire_displaced(&mut self, frame: u64) { + let gone: Vec = self.displaced.iter().filter(|(_, d)| d.until <= frame).map(|(&r, _)| r).collect(); + for r in gone { + self.displaced.remove(&r); + if let Some((src, size)) = self.shadowed.get(&r).map(|e| (e.src, e.tex.size() as usize)) { + self.unlink_src(r, src, size); + } + } + } + + /// The textures (active and displaced) whose source the dirty pages `dirty` (sorted) may touch. fn touched_by(&self, dirty: &[usize]) -> std::collections::BTreeSet { let mut out = std::collections::BTreeSet::new(); let mut last = usize::MAX; @@ -276,6 +309,7 @@ impl Table { for (sva, sres, _) in self.shadowed_overlaps(va, end) { self.shadowed_by_va.remove(&(sva, sres)); if let Some(old) = self.shadowed.remove(&sres) { + self.undisplace(sres, &old); if old.placed && !old.unmapped { to_unmap.push(sres); } @@ -307,6 +341,7 @@ impl Table { } if let Some(old) = self.shadowed.remove(&res) { self.shadowed_by_va.remove(&(old.va, res)); + self.undisplace(res, &old); } for (ova, ores, oend) in self.active_overlaps(va, end) { if !entry.placed && ova == va && oend == end && self.by_res.get(&ores).is_some_and(|e| !e.placed) { @@ -355,11 +390,64 @@ impl Table { (pending_delta, to_unmap) } + /// Reactivate a sampled texture and return its pending-count change and whether it needs + /// remapping. Keep displaced textures mapped for work that may still be using them, and + /// uploaded until frame `until`. + fn uncover(&mut self, res: usize, until: u64) -> Option<(isize, bool)> { + let mut e = self.shadowed.remove(&res)?; + self.shadowed_by_va.remove(&(e.va, res)); + self.undisplace(res, &e); + let size = e.tex.size() as usize; + let (va, end) = (e.va, e.va.saturating_add(size)); + let mut pending_delta = 0; + for (ova, ores, oend) in self.active_overlaps(va, end) { + // Committed textures at the exact same range can coexist as format aliases. + if !e.placed && ova == va && oend == end && self.by_res.get(&ores).is_some_and(|o| !o.placed) { + continue; + } + self.by_va.remove(&(ova, ores)); + if let Some(old) = self.by_res.remove(&ores) { + if old.pending { + self.pending_res.remove(&ores); + pending_delta -= 1; + } + if old.pending || !old.gpu_written { + // (its source stays linked: what the title writes there goes up too) + self.displaced.insert(ores, Displaced { until, whole: old.pending }); + } else { + self.unlink_src(ores, old.src, old.tex.size() as usize); + } + self.max_shadowed_size = self.max_shadowed_size.max(oend.saturating_sub(ova)); + self.shadowed_by_va.insert((ova, ores), oend); + self.shadowed.insert(ores, old); + } + } + if self.shadowed.is_empty() { + self.max_shadowed_size = 0; + } + let remap = std::mem::take(&mut e.unmapped); + texture_upload::forget(&e.known); + if !e.gpu_written { + e.pending = true; + } + if e.pending { + self.pending_res.insert(res); + pending_delta += 1; + } + self.next_seq += 1; + e.seq = self.next_seq; + self.by_va.insert((va, res), end); + self.link_src(res, e.src, size); + self.by_res.insert(res, e); + Some((pending_delta, remap)) + } + /// Remove `res` on COM release, reactivating any shadowed older textures it uncovered (newest /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap)`. fn remove(&mut self, res: usize) -> (bool, isize, Vec) { if let Some(old) = self.shadowed.remove(&res) { self.shadowed_by_va.remove(&(old.va, res)); + self.undisplace(res, &old); if self.shadowed.is_empty() { self.max_shadowed_size = 0; } @@ -384,6 +472,7 @@ impl Table { } self.shadowed_by_va.remove(&(sva, sres)); if let Some(mut e) = self.shadowed.remove(&sres) { + self.undisplace(sres, &e); // (the one that lay over it may have been uploaded over the same video memory) texture_upload::forget(&e.known); if e.unmapped { @@ -445,6 +534,9 @@ static TEXTURES: Mutex = Mutex::new(Table::new()); static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static HAS_SHADOWED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// a texture of `Table::displaced` waits for its first upload (`Displaced::whole`) +static HAS_DISPLACED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// cached `watch_ranges` keyed by `watch_key` static WATCH_CACHE: Mutex>)>> = Mutex::new(None); /// the queue uploads go to, per device @@ -535,6 +627,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); clone_resources(&unmap_ptrs) }; for r in &to_unmap { @@ -840,6 +933,7 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { } adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); (retired, clone_resources(&unmap_ptrs)) }; for r in &to_unmap { @@ -858,6 +952,7 @@ pub fn forget(res: usize) { let (removed, delta, remap_ptrs) = t.remove(res); adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); (removed, unsafe { clone_resources(&remap_ptrs) }) }; for r in &to_remap { @@ -874,6 +969,67 @@ pub fn forget(res: usize) { } } +/// Whether a draw's descriptor tables might name a shadowed texture. +pub(super) fn has_shadowed() -> bool { + HAS_SHADOWED.load(Ordering::Relaxed) +} + +/// How many of `res` are shadowed now. +pub(super) fn shadowed_among(res: &[usize]) -> usize { + let t = TEXTURES.lock().unwrap(); + res.iter().filter(|r| t.shadowed.contains_key(r)).count() +} + +/// Restore sampled shadowed textures while recording so the next submit can upload them. +pub(super) fn uncover_drawn(res: &[usize]) { + if res.is_empty() { + return; + } + let until = { + let (p, b) = super::present::counters(); + p.max(b) + DISPLACED_FRAMES + }; + let (restored, remap) = { + let mut t = TEXTURES.lock().unwrap(); + let (mut restored, mut remap, mut delta) = (0, Vec::new(), 0); + for &r in res { + if let Some((d, unmapped)) = t.uncover(r, until) { + restored += 1; + delta += d; + if unmapped { + remap.push(r); + } + } + } + if restored == 0 { + return; + } + adjust_pending(delta); + TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); + if t.displaced.values().any(|d| d.whole) { + HAS_DISPLACED.store(true, Ordering::Release); + } + (restored, unsafe { clone_resources(&remap) }) + }; + for r in &remap { + unsafe { + super::vram::remap_if_unmapped(r); + // Lazy levels of a GPU-written texture cannot wait for a CPU upload to map them. + if super::vram::level_pages() && TEXTURES.lock().unwrap().get_mut(r.as_raw() as usize).is_some_and(|e| e.gpu_written) { + super::vram::map_levels(r, None); + } + } + } + TEXTURES_GEN.fetch_add(1, Ordering::Release); + static N: AtomicU64 = AtomicU64::new(0); + let before = N.fetch_add(restored, Ordering::Relaxed); + let n = before + restored; + if before == 0 || before.ilog2() != n.ilog2() { + crate::xlog_info!("D3D12.X: {n} shadowed textures sampled by draws so far were made active again ({} needed remapping in this batch)", remap.len()); + } +} + /// The title-memory address of a texture kept in step with it. pub fn address(res: usize) -> Option { let t = TEXTURES.lock().unwrap(); @@ -1760,7 +1916,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { p.max(b) }; recheck_streamed_unwatched(&ranges, recheck_frame); - if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 && AGAIN.lock().unwrap().is_empty() { + if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 && !HAS_DISPLACED.load(Ordering::Acquire) && AGAIN.lock().unwrap().is_empty() { return; } let target = upload_target(ID3D12CommandQueue::from_raw_borrowed(&queue)); @@ -1769,15 +1925,29 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { let todo: Vec = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); + t.expire_displaced(recheck_frame); let mut names = t.touched_by(&dirty); names.extend(std::mem::take(&mut t.pending_res)); + names.extend(t.displaced.iter().filter(|(_, d)| d.whole).map(|(&r, _)| r)); + HAS_DISPLACED.store(false, Ordering::Release); let waiting = std::mem::take(&mut *AGAIN.lock().unwrap()); names.extend(waiting.iter().copied()); let mut later = std::collections::BTreeSet::new(); - let todo = names + let Table { by_res, shadowed, displaced, .. } = &mut *t; + let mut todo: Vec<(bool, Due)> = names .into_iter() .filter_map(|res| { - let e = t.by_res.get_mut(&res)?; + let active = by_res.contains_key(&res); + let (e, whole) = if active { + let e = by_res.get_mut(&res)?; + let whole = e.pending; + (e, whole) + } else if let Some(d) = displaced.get_mut(&res) { + let e = shadowed.get_mut(&res).filter(|e| !e.unmapped)?; + (e, std::mem::take(&mut d.whole)) + } else { + return None; + }; let mut again = texture_upload::Change::None; if waiting.contains(&res) && !e.gpu_written { let (queue, waited) = target.on(e.device); @@ -1787,26 +1957,28 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { texture_upload::Again::Nothing => {} } } - let wanted = e.pending || again != texture_upload::Change::None || (!e.gpu_written && { + let wanted = whole || again != texture_upload::Change::None || (!e.gpu_written && { let i = dirty.partition_point(|&p| p + page as usize <= e.src); dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) }); if !wanted { return None; } - let whole = e.pending; - if e.pending { + // (a displaced one stays pending: it goes up whole again if it is uncovered) + if e.pending && active { e.pending = false; PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; // (its pages resolved once, for all reads of this upload) let pages = if e.paged { page_map(e.va, e.tex.size() as usize, true) } else { None }; - ID3D12Resource::from_raw_borrowed(&p).map(|r| Due { res: r.clone(), device: e.device, src: e.src, tex: Arc::clone(&e.tex), states: e.states.clone(), known: Arc::clone(&e.known), whole, again, target: e.target, pages }) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (active, Due { res: r.clone(), device: e.device, src: e.src, tex: Arc::clone(&e.tex), states: e.states.clone(), known: Arc::clone(&e.known), whole, again, target: e.target, pages })) }) .collect(); AGAIN.lock().unwrap().extend(later); - todo + // (displaced ones first: an active one over the same video memory goes up after them) + todo.sort_by_key(|&(active, _)| active); + todo.into_iter().map(|(_, d)| d).collect() }); seed_stream_recheck(&todo, &ranges, recheck_frame); let t_tex = std::time::Instant::now(); @@ -4122,6 +4294,158 @@ pub(super) mod tests { assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12)); } + /// Sampling a shadowed texture makes it active, mapped and pending again. + #[test] + fn a_sampled_shadowed_texture_is_active_again() { + let tex_16k = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + let tex_64k = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + let entry = |va: usize, tex: &Arc, pending: bool, placed: bool| Entry { + device: 0, + va, + src: va, + in_gpu_view: false, + paged: false, + tex: Arc::clone(tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending, + gpu_written: false, + written_call: 0, + placed, + unmapped: false, + seq: 0, + known: Default::default(), + target: false, + }; + let mut tbl = Table::new(); + assert_eq!(tbl.insert(1, entry(0x10_4000, &tex_16k, true, true)), (1, vec![])); + assert_eq!(tbl.insert(2, entry(0x10_0000, &tex_64k, true, true)), (0, vec![1])); + assert!(tbl.shadowed[&1].unmapped); + assert_eq!(tbl.uncover(2, 1), None, "an active texture is not shadowed"); + + assert_eq!(tbl.uncover(1, 1), Some((0, true))); + assert!(tbl.by_res[&1].pending && !tbl.by_res[&1].unmapped); + assert!(tbl.by_res[&1].seq > tbl.shadowed[&2].seq); + assert!(!tbl.by_res.contains_key(&2) && !tbl.shadowed[&2].unmapped); + assert_eq!(tbl.overlapping(0x10_0000, 0x1_0000), vec![(1, 0x10_4000)]); + assert_eq!(tbl.pending_res, [1].into_iter().collect()); + // (2 is displaced: a draw recorded before may still sample it, so its source stays watched) + assert!(tbl.displaced[&2].whole); + assert_eq!(tbl.touched_by(&[0x10_4000]), [1, 2].into_iter().collect()); + + assert_eq!(tbl.uncover(2, 1), Some((0, false))); + assert!(tbl.shadowed.contains_key(&1) && !tbl.shadowed[&1].unmapped); + assert!(tbl.displaced[&1].whole && tbl.shadowed[&1].pending, "1 still goes up at the next submit"); + let (removed, _, remap) = tbl.remove(2); + assert_eq!((removed, remap), (true, vec![])); + assert!(tbl.by_res.contains_key(&1)); + + let mut gpu_alias = entry(0x20_0000, &tex_16k, false, false); + gpu_alias.gpu_written = true; + assert_eq!(tbl.insert(10, entry(0x20_0000, &tex_16k, false, false)), (0, vec![])); + assert_eq!(tbl.insert(11, gpu_alias), (0, vec![])); + assert_eq!(tbl.insert(12, entry(0x20_0000, &tex_64k, false, false)), (0, vec![])); + assert_eq!(tbl.uncover(10, 1), Some((1, false))); + assert_eq!(tbl.uncover(11, 1), Some((0, false))); + assert!(tbl.by_res.contains_key(&10) && !tbl.by_res[&11].pending && tbl.shadowed.contains_key(&12)); + + // An uploaded A that B shadows again keeps its source watched, over the refreshes before + // the frame a draw that sampled it may wait for its submit to (#2956 review) + let mut dirty_tbl = Table::new(); + let mut b = entry(0x30_0000, &tex_64k, false, true); + b.src = 0x5000_0000; + let mut a = entry(0x30_4000, &tex_16k, false, true); + a.src = 0x4000_0000; + let (block_a, block_b) = (0x4000_0000 >> SRC_COARSE_SHIFT, 0x5000_0000 >> SRC_COARSE_SHIFT); + assert_eq!(dirty_tbl.insert(20, b).0, 0); + assert_eq!(dirty_tbl.insert(21, a).0, 0); + assert_eq!(dirty_tbl.uncover(20, 5), Some((1, true))); + assert!(dirty_tbl.coarse.contains_key(&block_a), "A's source stays watched"); + assert!(!dirty_tbl.displaced[&21].whole); + assert_eq!(dirty_tbl.touched_by(&[0x4000_0000]), [21].into_iter().collect(), "a write there makes A go up"); + dirty_tbl.expire_displaced(4); + assert!(dirty_tbl.coarse.contains_key(&block_a), "kept over a refresh before its frame"); + dirty_tbl.expire_displaced(5); + assert!(!dirty_tbl.displaced.contains_key(&21) && !dirty_tbl.coarse.contains_key(&block_a)); + assert!(dirty_tbl.touched_by(&[0x4000_0000]).is_empty()); + // made active again or released, a displaced texture leaves `displaced` with its watch + assert_eq!(dirty_tbl.uncover(21, 9), Some((0, false))); + assert!(dirty_tbl.displaced[&20].whole); + assert_eq!(dirty_tbl.coarse.get(&block_a), Some(&1)); + assert_eq!(dirty_tbl.uncover(20, 9), Some((0, false))); + assert_eq!((dirty_tbl.coarse.get(&block_a), dirty_tbl.coarse.get(&block_b)), (Some(&1), Some(&1)), "linked once each"); + assert_eq!(dirty_tbl.remove(21), (true, 0, vec![])); + assert!(dirty_tbl.displaced.is_empty() && !dirty_tbl.coarse.contains_key(&block_a)); + } + + /// Real GPU: one draw samples two overlapping textures, A then B. B shadows A again before + /// the submit, and A is uploaded all the same (it read its old texels before). + #[test] + fn gpu_both_overlapping_textures_a_draw_samples_go_up() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + struct Registered(usize); + impl Drop for Registered { + fn drop(&mut self) { forget(self.0); } + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let console = console_desc(3, 64, 64, 1, 1, DXGI_FORMAT_R8_UNORM.0 as u32, 1); + let size = xg::Texture::new(&console).unwrap().size() as usize; + let base = VirtualAlloc(std::ptr::null(), 2 * size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let make = || { + let mut t = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut t, + ).unwrap(); + t.unwrap() + }; + let (a, b): (ID3D12Resource, ID3D12Resource) = (make(), make()); + let (ka, kb) = (a.as_raw() as usize, b.as_raw() as usize); + std::ptr::write_bytes(base as *mut u8, 0x11, 2 * size); + register(raw_device, a.as_raw(), base, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _ra = Registered(ka); + refresh(queue.as_raw()); + // B lies over the second half of A and shadows it + register(raw_device, b.as_raw(), base + size / 2, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + let _rb = Registered(kb); + refresh(queue.as_raw()); + assert!(TEXTURES.lock().unwrap().shadowed.contains_key(&ka)); + assert_eq!(read_r8(dev, &queue, &a), vec![0x11; 64 * 64]); + // the title writes the memory under both, then one draw samples A and B + std::ptr::write_bytes(base as *mut u8, 0x33, 2 * size); + uncover_drawn(&[ka, kb]); + assert!(TEXTURES.lock().unwrap().shadowed.contains_key(&ka), "B is the active one"); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &a), vec![0x33; 64 * 64], "A goes up although B shadowed it again"); + assert_eq!(read_r8(dev, &queue, &b), vec![0x33; 64 * 64]); + // the frames the draw could wait go by and A is only shadowed while the title writes + // again; then a draw samples A and B, and B (the GPU wrote it) shadows A again + TEXTURES.lock().unwrap().expire_displaced(u64::MAX); + std::ptr::write_bytes(base as *mut u8, 0x44, 2 * size); + refresh(queue.as_raw()); + note_gpu_write(0, kb); + uncover_drawn(&[ka, kb]); + assert_eq!(PENDING.load(Ordering::Relaxed), 0); + assert!(TEXTURES.lock().unwrap().displaced[&ka].whole); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &a), vec![0x44; 64 * 64], "displaced A goes up with no written page and no pending texture"); + drop((_rb, _ra)); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + /// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased /// overlapping placements stays bounded in video memory, superseded textures never corrupt /// newer placements on shared tiles, 4 KiB-aligned neighbours never false-alias, and mip diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5433d0dbc6..126745a2ae 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -285,24 +285,27 @@ impl Levels { } } -/// `XCL_TEXTURE_LEVEL_PAGES=1` (off by default): a sampled 2D texture of one slice on the -/// shared pages gets the pages of a level when an upload first has texels for it. A retail game -/// places its streamed textures at full size and maps memory under their levels as it loads -/// them, the small ones first; with a page for every 64 KiB a texture covers most of the pages -/// are for levels that are not loaded. +/// Level pages (on by default, `XCL_TEXTURE_LEVEL_PAGES=0` turns them off): a sampled 2D texture +/// of one slice on the shared pages gets the pages of a level when an upload first has texels for +/// it. A retail game places its streamed textures at full size and maps memory under their levels +/// as it loads them, the small ones first; with a page for every 64 KiB a texture covers most of +/// the pages are for levels that are not loaded (its world: 32,000 textures standing for 18 GB +/// held 1.3 GB of pages – and video memory is charged to the system's commit like RAM). pub(super) fn level_pages() -> bool { + // (a test chooses with `LEVEL_PAGES_FOR_TEST`) #[cfg(test)] - if LEVEL_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { - return true; + return LEVEL_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_TEXTURE_LEVEL_PAGES").map_or(true, |v| v.trim() != "0"); + if !on { + crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=0 - a sampled texture gets video memory pages for all of its levels at once"); + } + on + }) } - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - let on = std::env::var("XCL_TEXTURE_LEVEL_PAGES").is_ok_and(|v| v.trim() == "1"); - if on { - crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=1 - a sampled texture's levels get their video memory pages when an upload first has texels for them"); - } - on - }) } /// `level_pages` for a test (under `VRAM_TEST_LOCK`) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 6255a9118d..0d8e1fee37 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -947,7 +947,16 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } - if alias::enabled() && addr.is_null() && t & 0x2000 != 0 && t & 0x1000 == 0 && t & MEM_64K_PAGES == MEM_64K_PAGES { + // Keep GPU write-combined 64 KiB reservations (`MEM_GRAPHICS` + `PAGE_WRITECOMBINE`, e.g. + // a title's GPU UAV/PreSkin buffer heap) in sparse UMA so `CreatePlacedResourceX` buffers + // placed in them register in `UMA_BUFFERS` and get valid shader V# descriptors. + if alias::enabled() + && addr.is_null() + && t & 0x2000 != 0 + && t & 0x1000 == 0 + && t & MEM_64K_PAGES == MEM_64K_PAGES + && !(t & MEM_GRAPHICS != 0 && p & mem::PAGE_WRITECOMBINE != 0) + { if let Some(q) = alias::reserve_space(size) { mirrors::reserved(q, size, t, p); trace_mem("VirtualAlloc (64K pages, physical page space)", 0, size, t as u64, p, q); @@ -2190,9 +2199,11 @@ unsafe fn give_back_homes(away: &mut Away) { } } +/// `XCL_DEFER_PRIVATE_HOME_TILES`: on by default (`=0` turns it off), off in unit tests unless +/// they ask for it. fn defer_private_home_tiles() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_DEFER_PRIVATE_HOME_TILES").is_ok_and(|v| v.trim() == "1")) + *ON.get_or_init(|| std::env::var("XCL_DEFER_PRIVATE_HOME_TILES").map_or(!cfg!(test), |v| v.trim() == "1")) } /// Once its home was exposed, later recommits keep the existing GPU-visible behavior. diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs index af8debe63e..e37319c0d8 100644 --- a/crates/xcl/src/hle/kernelx/alias.rs +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -335,7 +335,7 @@ unsafe fn move_to(at: usize, page: usize, home: usize) -> bool { } if committed(page) { std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PAGE); - } else { + } else if !u.is_some_and(|u| u.is_sparse(at)) { std::ptr::write_bytes(at as *mut u8, 0, PAGE); } with(|s| { diff --git a/crates/xcl/src/ram_budget.rs b/crates/xcl/src/ram_budget.rs index 7d6b4f38c0..252683f440 100644 --- a/crates/xcl/src/ram_budget.rs +++ b/crates/xcl/src/ram_budget.rs @@ -70,7 +70,8 @@ fn working_set() -> u64 { } } -fn available() -> u64 { +/// The RAM the system has available now, in bytes. +pub(crate) fn available() -> u64 { unsafe { let mut m: MEMORYSTATUSEX = std::mem::zeroed(); m.dwLength = std::mem::size_of_val(&m) as u32; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ad4b51013c..9a77dd71c7 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1895,20 +1895,24 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R } /// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title -/// starts (1: in this process, as before). Unset: the logical processors less four, and no -/// more than 3 GB of the commit the system has left for each. +/// starts (1: in this process, as before). Unset: the logical processors less four, no more +/// than 3 GB of the commit the system has left for each, and no more than 2 GB of the RAM +/// available for each with 4 GB left over (a worker held 1.4–3 GB of RAM on a retail title's +/// pack: 16 of them took a 32 GB PC to under 6 GB available before the title had started). fn prepare_workers() -> usize { if let Some(n) = std::env::var("XCL_PREPARE_WORKERS").ok().and_then(|v| v.parse::().ok()) { return n.clamp(1, 32); } let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); + // (`system_commit` is in bytes) let (used, limit) = crate::host::system_commit(); - workers_for(cores, limit.saturating_sub(used)) + workers_for(cores, limit.saturating_sub(used) >> 20, crate::ram_budget::available() >> 20) } -/// The workers for `cores` logical processors (threads, not cores) and `free_mb` of commit left. -fn workers_for(cores: usize, free_mb: u64) -> usize { - cores.saturating_sub(4).min(32).min((free_mb / 3072) as usize).max(1) +/// The workers for `cores` logical processors (threads, not cores), `free_mb` of commit left +/// and `ram_mb` of RAM available. +fn workers_for(cores: usize, free_mb: u64, ram_mb: u64) -> usize { + cores.saturating_sub(4).min(32).min((free_mb / 3072) as usize).min((ram_mb.saturating_sub(4096) / 2048) as usize).max(1) } /// The record count of a builder's progress line (` 400/26503 (12 s)`). @@ -2824,12 +2828,33 @@ mod tests { /// 3 GB of commit for each, and one where there is no room. #[test] fn preparation_workers_leave_two_processors_and_follow_the_commit_left() { - assert_eq!(workers_for(32, 100_000), 28); - assert_eq!(workers_for(8, 100_000), 4); - assert_eq!(workers_for(32, 10_000), 3); - assert_eq!(workers_for(2, 100_000), 1); - assert_eq!(workers_for(64, 1_000_000), 32); - assert_eq!(workers_for(32, 0), 1); + const RAM: u64 = 1_000_000; + assert_eq!(workers_for(32, 100_000, RAM), 28); + assert_eq!(workers_for(8, 100_000, RAM), 4); + assert_eq!(workers_for(32, 10_000, RAM), 3); + assert_eq!(workers_for(2, 100_000, RAM), 1); + assert_eq!(workers_for(64, 1_000_000, RAM), 32); + assert_eq!(workers_for(32, 0, RAM), 1); + } + + /// The workers also follow the RAM available: 2 GB for each with 4 GB left over (a 32 GB + /// PC with 18 GB available and a large page file: 6, not one for every logical processor). + #[test] + fn preparation_workers_follow_the_ram_available() { + assert_eq!(workers_for(20, 54_000, 18_000), 6); + assert_eq!(workers_for(20, 54_000, 40_000), 16); + assert_eq!(workers_for(20, 54_000, 5_000), 1); + assert_eq!(workers_for(20, 54_000, 0), 1); + } + + /// `prepare_workers` gives `workers_for` megabytes: `host::system_commit` is in bytes, and a + /// commit left in bytes divided as megabytes never limited anything. + #[test] + fn preparation_workers_are_bounded_by_this_systems_commit_in_megabytes() { + let (used, limit) = crate::host::system_commit(); + let free_mb = limit.saturating_sub(used) >> 20; + assert!(free_mb < 1 << 24, "the commit left is in megabytes here ({free_mb})"); + assert!(workers_for(64, free_mb, 1 << 20) <= (free_mb / 3072).max(1) as usize); } /// A builder's progress line gives its record count; its other lines give none. diff --git a/docs/specs/2026-11-24-direct-dxil.md b/docs/specs/2026-11-24-direct-dxil.md index 8abb513891..db0a43cce1 100644 --- a/docs/specs/2026-11-24-direct-dxil.md +++ b/docs/specs/2026-11-24-direct-dxil.md @@ -23,10 +23,6 @@ XCL is GPL-2.0-only. References used: local bitstream reader, as the layout oracle. - Mesa `src/microsoft/compiler` (MIT) may be ported with a provenance note. -**Not used:** the VIctory project (GPL-3.0-or-later, incompatible). Its -public architecture description informed the approach below; no code was -read for porting or copied. - ## Layers (done) | Module | Role | diff --git a/scripts/gen_bcpack_victory_tables.py b/scripts/gen_bcpack_victory_tables.py index 46d62cd72f..ebc9220b12 100644 --- a/scripts/gen_bcpack_victory_tables.py +++ b/scripts/gen_bcpack_victory_tables.py @@ -6,7 +6,7 @@ Layout is that of the format's constant tables: 128 x 9 u16 model frequencies, the rank tables, 512 u16 BC7 control words, then 255 dictionary entries per format. BC7 entry 0 stores all 32 signed indices directly after its two index widths; entries -1..254 repeat the two width bytes first and store 16 + 15 signed indices (VIctory PR #658). +1..254 repeat the two width bytes first and store 16 + 15 signed indices. python -I scripts/gen_bcpack_victory_tables.py """ From 27e956271490382387f686e24ceea5649d7bec03 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 00:33:03 -0800 Subject: [PATCH 027/175] D3D12.X: process 2D texture tiling in contiguous block runs The existing row-factorized detiler still visited swizzled textures one element at a time and recalculated block placement for every element. Large CPU-written textures therefore consumed milliseconds on the submit path even after persistent detile workers. Adapt raylitebull's 032c661a block-slab algorithm: cache the largest provably contiguous horizontal run for each immutable GFX10 layout, keep one 4 KiB/64 KiB block hot at a time, bulk-copy complete runs, and retain element-wise bounds checks for a truncated source. Low-bit base swizzles shorten runs safely; thick 3D single-slice helpers retain their former path. On this AMD EPYC 7R13 Linux host, an isolated release benchmark against 032c661a's parent reduced 1920x1080 R8 mode-5 detile from 8.8-10.3 ms to 0.76-0.87 ms and tile from 28-31 ms to 0.64-0.78 ms. A 2048x2048 RGBA8 mode-10 detile fell from 28-31 ms to 9.7-11.8 ms and tile from 59-67 ms to 5.8-6.9 ms. All 17 isolated pure tiling tests passed. The Windows GNU library/test cross-check passed with the existing warnings; Windows MSVC, GPU, and smoke tests were unavailable. Source algorithm: 032c661a by raylitebull, assisted by Antigravity (Gemini 4 Neon High). Assisted-by: Codex (GPT-5.6-sol) (cherry picked from commit 95f12a04d6415784840d348095838c406004808e) --- crates/xcl/src/gpu/tiling.rs | 383 +++++++++++++++++++++++++++++------ 1 file changed, 321 insertions(+), 62 deletions(-) diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index a35dda1c9e..de370cc695 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -66,6 +66,9 @@ pub struct Layout { /// XORed into every in-block byte offset: the pipe / bank swizzle a T# base address carries /// in its low bits (`base & (block_bytes - 1)`), 0 otherwise pub base_xor: usize, + /// largest power-of-two horizontal element run inside a block whose byte offsets advance + /// contiguously by `+e` with zero interference from `oy`/`oz`/`hx`/`hy`/`hz` + run_elems: usize, ox: &'static [u32], oy: &'static [u32], oz: &'static [u32], @@ -108,7 +111,7 @@ impl Layout { if mode == 0 { let bw = 256 >> elem_log2; let ox: &'static [u32] = (0..bw as u32).map(|x| x << elem_log2).collect::>().leak(); - return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: &[0], oz: &[0], hx: &[0], hy: &[0], hz: &[0] }); + return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, run_elems: bw, ox, oy: &[0], oz: &[0], hx: &[0], hy: &[0], hz: &[0] }); } let blk = block_log2(mode)?; let bits = pattern_bits(PATTERNS, mode, elem_log2, cfg)?; @@ -161,6 +164,29 @@ impl Layout { let used = bits[..blk as usize].iter().fold(0u32, |m, &b| m | ((b >> shift) & 0xFFFF) as u32) >> l.min(16); table(1 << (32 - used.leading_zeros()), shift, l) }; + let ox = table(bw, 0, 0); + let oy = table(bh, 16, 0); + let oz = table(bd, 32, 0); + let hx = high(wl, 0); + let hy = high(hl, 16); + let hz = high(dl, 32); + let other_bits = oy.iter().chain(oz).chain(hx).chain(hy).chain(hz).fold(0u32, |a, &b| a | b); + let mut run_elems = 1usize; + while run_elems * 2 <= bw { + let next = run_elems * 2; + let mask = ((next << elem_log2) - 1) as u32; + if (other_bits & mask) != 0 { + break; + } + let ok = (0..bw).all(|x| { + let base = ox[x & !(next - 1)]; + (base & mask) == 0 && ox[x] == base + (((x & (next - 1)) << elem_log2) as u32) + }); + if !ok { + break; + } + run_elems = next; + } Layout { mode, elem_log2, @@ -169,12 +195,13 @@ impl Layout { block_d: bd, block_bytes: 1 << blk, base_xor: 0, - ox: table(bw, 0, 0), - oy: table(bh, 16, 0), - oz: table(bd, 32, 0), - hx: high(wl, 0), - hy: high(hl, 16), - hz: high(dl, 32), + run_elems, + ox, + oy, + oz, + hx, + hy, + hz, } } @@ -224,34 +251,215 @@ impl Layout { block * self.block_bytes + (xor as usize ^ self.base_xor) } + /// Effective horizontal contiguous run width in elements, respecting any `base_xor` low bits. + #[inline] + fn effective_run(&self) -> usize { + if self.base_xor == 0 { + self.run_elems + } else { + let lim = (1usize << self.base_xor.trailing_zeros()) >> self.elem_log2; + self.run_elems.min(lim).max(1) + } + } + /// tiled → linear rows (`w << elem_log2` bytes each); bytes past the end of `src` read as 0 pub fn detile(&self, src: &[u8], w: usize, h: usize) -> Vec { let e = 1usize << self.elem_log2; let mut out = vec![0u8; w * h * e]; - for y in 0..h { - for x in 0..w { - let o = self.offset(x, y, w); - if let Some(s) = src.get(o..o + e) { - let d = (y * w + x) * e; - out[d..d + e].copy_from_slice(s); - } - } - } + self.detile_2d(src, &mut out, 0, w, h, w, (0, 0), 0); out } /// linear rows → tiled (the inverse of `detile`) pub fn tile(&self, linear: &[u8], w: usize, h: usize) -> Vec { - let e = 1usize << self.elem_log2; let mut out = vec![0u8; self.size(w, h)]; - for y in 0..h { - for x in 0..w { - let o = self.offset(x, y, w); - let s = (y * w + x) * e; - out[o..o + e].copy_from_slice(&linear[s..s + e]); + self.tile_2d(&mut out, linear, 0, w, h, w, (0, 0), 0); + out + } + + /// Block-slab 2D detile with contiguous horizontal run copies (`src` tiled -> `out` linear). + /// Iterating one tiled block `(by, bx)` at a time keeps each 4 KiB / 64 KiB block hot in L1 + /// cache and eliminates per-element block arithmetic and bounds checks on complete blocks. + #[allow(clippy::too_many_arguments)] + fn detile_2d(&self, src: &[u8], out: &mut [u8], base_off: usize, w: usize, h: usize, pitch: usize, origin: (usize, usize), slice: usize) { + if w == 0 || h == 0 { + return; + } + let e = 1usize << self.elem_log2; + if self.mode == 0 && self.base_xor == 0 && origin == (0, 0) { + let row = w * e; + let pitch_blocks = pitch.div_ceil(self.block_w); + for y in 0..h { + let o = base_off + (y / self.block_h) * pitch_blocks * self.block_bytes + self.oy[y % self.block_h] as usize; + let n = src.len().saturating_sub(o).min(row) / e * e; + if n > 0 { + out[y * row..][..n].copy_from_slice(&src[o..o + n]); + } + } + return; + } + let pitch_blocks = pitch.div_ceil(self.block_w); + let z = self.oz[slice % self.block_d] ^ self.hz[(slice / self.block_d) % self.hz.len()]; + let run = self.effective_run(); + let run_bytes = run * e; + let row_bytes = w * e; + let (ox0, oy0) = origin; + let bx_start = ox0 / self.block_w; + let bx_end = (ox0 + w - 1) / self.block_w; + let by_start = oy0 / self.block_h; + let by_end = (oy0 + h - 1) / self.block_h; + + for by in by_start..=by_end { + let y_lo = (by * self.block_h).max(oy0) - oy0; + let y_hi = ((by + 1) * self.block_h).min(oy0 + h) - oy0; + let hy = self.hy[by % self.hy.len()] ^ z; + let row_blocks = by * pitch_blocks; + for bx in bx_start..=bx_end { + let x_lo = (bx * self.block_w).max(ox0) - ox0; + let x_hi = ((bx + 1) * self.block_w).min(ox0 + w) - ox0; + let block_base = base_off + (row_blocks + bx) * self.block_bytes; + let b_xor = self.hx[bx % self.hx.len()] ^ hy ^ self.base_xor as u32; + let xi_lo = x_lo + ox0 - bx * self.block_w; + let xi_hi = x_hi + ox0 - bx * self.block_w; + if block_base.checked_add(self.block_bytes).is_some_and(|end| end <= src.len()) { + let blk = &src[block_base..block_base + self.block_bytes]; + if run > 1 { + let aligned_lo = (xi_lo + run - 1) & !(run - 1); + let aligned_hi = xi_hi & !(run - 1); + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + let mut xi = xi_lo; + let mut x = x_lo; + let pre = aligned_lo.min(xi_hi); + while xi < pre { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + e].copy_from_slice(&blk[o..o + e]); + xi += 1; + x += 1; + } + while xi < aligned_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + run_bytes].copy_from_slice(&blk[o..o + run_bytes]); + xi += run; + x += run; + } + while xi < xi_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + e].copy_from_slice(&blk[o..o + e]); + xi += 1; + x += 1; + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = (x_off ^ y_xor) as usize; + let d = (x_lo + dx) * e; + dst_row[d..d + e].copy_from_slice(&blk[o..o + e]); + } + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = block_base + (x_off ^ y_xor) as usize; + if let Some(s) = src.get(o..o + e) { + let d = (x_lo + dx) * e; + dst_row[d..d + e].copy_from_slice(s); + } + } + } + } + } + } + } + + /// Block-slab 2D tile with contiguous horizontal run copies (`linear` -> `dst` tiled). + #[allow(clippy::too_many_arguments)] + fn tile_2d(&self, dst: &mut [u8], linear: &[u8], base_off: usize, w: usize, h: usize, pitch: usize, origin: (usize, usize), slice: usize) { + if w == 0 || h == 0 { + return; + } + let e = 1usize << self.elem_log2; + if self.mode == 0 && self.base_xor == 0 && origin == (0, 0) { + let row = w * e; + let pitch_blocks = pitch.div_ceil(self.block_w); + for y in 0..h { + let o = base_off + (y / self.block_h) * pitch_blocks * self.block_bytes + self.oy[y % self.block_h] as usize; + dst[o..o + row].copy_from_slice(&linear[y * row..][..row]); + } + return; + } + let pitch_blocks = pitch.div_ceil(self.block_w); + let z = self.oz[slice % self.block_d] ^ self.hz[(slice / self.block_d) % self.hz.len()]; + let run = self.effective_run(); + let run_bytes = run * e; + let row_bytes = w * e; + let (ox0, oy0) = origin; + let bx_start = ox0 / self.block_w; + let bx_end = (ox0 + w - 1) / self.block_w; + let by_start = oy0 / self.block_h; + let by_end = (oy0 + h - 1) / self.block_h; + + for by in by_start..=by_end { + let y_lo = (by * self.block_h).max(oy0) - oy0; + let y_hi = ((by + 1) * self.block_h).min(oy0 + h) - oy0; + let hy = self.hy[by % self.hy.len()] ^ z; + let row_blocks = by * pitch_blocks; + for bx in bx_start..=bx_end { + let x_lo = (bx * self.block_w).max(ox0) - ox0; + let x_hi = ((bx + 1) * self.block_w).min(ox0 + w) - ox0; + let block_base = base_off + (row_blocks + bx) * self.block_bytes; + let b_xor = self.hx[bx % self.hx.len()] ^ hy ^ self.base_xor as u32; + let xi_lo = x_lo + ox0 - bx * self.block_w; + let xi_hi = x_hi + ox0 - bx * self.block_w; + let blk = &mut dst[block_base..block_base + self.block_bytes]; + if run > 1 { + let aligned_lo = (xi_lo + run - 1) & !(run - 1); + let aligned_hi = xi_hi & !(run - 1); + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let src_row = &linear[y * row_bytes..(y + 1) * row_bytes]; + let mut xi = xi_lo; + let mut x = x_lo; + let pre = aligned_lo.min(xi_hi); + while xi < pre { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + e].copy_from_slice(&src_row[x * e..x * e + e]); + xi += 1; + x += 1; + } + while xi < aligned_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + run_bytes].copy_from_slice(&src_row[x * e..x * e + run_bytes]); + xi += run; + x += run; + } + while xi < xi_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + e].copy_from_slice(&src_row[x * e..x * e + e]); + xi += 1; + x += 1; + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let src_row = &linear[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = (x_off ^ y_xor) as usize; + let s = (x_lo + dx) * e; + blk[o..o + e].copy_from_slice(&src_row[s..s + e]); + } + } + } } } - out } } @@ -417,6 +625,7 @@ impl Chain { /// element (x, y) of level `l` in array slice `slice` (from the slice's start): the slice /// is z of the 2D patterns – the XOR modes take pipe bits from it + #[cfg(test)] fn element_at(&self, l: &MipLevel, x: usize, y: usize, slice: usize) -> usize { l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch) } @@ -464,46 +673,20 @@ impl Chain { /// bytes past the end of `src` read as 0 pub fn detile_level(&self, src: &[u8], i: usize, slice: usize) -> Vec { let l = self.levels[i]; - let t = &self.layout; - let e = 1usize << t.elem_log2; + let e = 1usize << self.layout.elem_log2; let mut out = vec![0u8; l.width * l.height * e]; - if t.mode == 0 && t.base_xor == 0 && l.origin == (0, 0) { - // linear: a row's elements are contiguous, so it is copied whole (the elements that - // are all in `src`, as below) – a video plane of 3840×2160 is 2160 copies, not 8 M - let row = l.width * e; + if self.layout.block_d != 1 { for y in 0..l.height { - let o = self.element_at(&l, 0, y, slice); - let n = src.len().saturating_sub(o).min(row) / e * e; - if n > 0 { - out[y * row..][..n].copy_from_slice(&src[o..o + n]); + for x in 0..l.width { + let offset = l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch); + if let Some(bytes) = src.get(offset..offset + e) { + out[(y * l.width + x) * e..][..e].copy_from_slice(bytes); + } } } return out; } - // `element_at` (`Layout::offset_z`) split: what depends on x alone once per level, what - // depends on y (and the slice) once per row – per element only two lookups and an XOR. - // Element by element it was most of a retail game's render thread while it streamed - // textures the CPU writes. - let hi = |tab: &[u32], c: usize, b: usize| tab[(c / b) % tab.len()]; - let pitch_blocks = l.pitch.div_ceil(t.block_w); - let columns: Vec<(usize, u32)> = (0..l.width) - .map(|x| { - let x = x + l.origin.0; - (x / t.block_w, t.ox[x % t.block_w] ^ hi(&t.hx, x, t.block_w)) - }) - .collect(); - let z = t.oz[slice % t.block_d] ^ hi(&t.hz, slice, t.block_d); - for (y, row) in out.chunks_exact_mut(l.width * e).enumerate() { - let y = y + l.origin.1; - let row_blocks = (y / t.block_h) * pitch_blocks; - let yz = t.oy[y % t.block_h] ^ hi(&t.hy, y, t.block_h) ^ z; - for (&(block_x, x), dst) in columns.iter().zip(row.chunks_exact_mut(e)) { - let o = l.offset + (row_blocks + block_x) * t.block_bytes + ((x ^ yz) as usize ^ t.base_xor); - if let Some(s) = src.get(o..o + e) { - dst.copy_from_slice(s); - } - } - } + self.layout.detile_2d(src, &mut out, l.offset, l.width, l.height, l.pitch, l.origin, slice); out } @@ -656,13 +839,17 @@ impl Chain { /// linear rows of level `i` → its place in array slice `slice` (`dst`, `slice_bytes` long) pub fn tile_level(&self, dst: &mut [u8], i: usize, slice: usize, linear: &[u8]) { let l = self.levels[i]; - let e = 1usize << self.layout.elem_log2; - for y in 0..l.height { - for x in 0..l.width { - let o = self.element_at(&l, x, y, slice); - dst[o..o + e].copy_from_slice(&linear[(y * l.width + x) * e..][..e]); + if self.layout.block_d != 1 { + let e = 1usize << self.layout.elem_log2; + for y in 0..l.height { + for x in 0..l.width { + let offset = l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch); + dst[offset..offset + e].copy_from_slice(&linear[(y * l.width + x) * e..][..e]); + } } + return; } + self.layout.tile_2d(dst, linear, l.offset, l.width, l.height, l.pitch, l.origin, slice); } } @@ -1014,6 +1201,15 @@ mod tests { let cfg = PipeConfig { pipes_log2: 0, pkrs_log2: 0 }; assert_eq!(Layout::new_3d(24, 2, cfg).unwrap().block_d, 1); assert!(Layout::new_3d(10, 2, cfg).is_none() && Layout::new_3d(1, 2, cfg).is_none()); + + // The 2D block-slab fast path must not change the legacy single-slice helpers on a + // thick layout (volume callers normally use `tile_volume` / `detile_volume`). + let chain = Chain::new_3d(Layout::new_3d(5, 2, cfg).unwrap(), 19, 13, 4, 1, 1); + let level = chain.levels[0]; + let linear: Vec = (0..level.width * level.height * 4).map(|i| (i * 37) as u8).collect(); + let mut tiled = vec![0u8; chain.slice_bytes]; + chain.tile_level(&mut tiled, 0, 1, &linear); + assert_eq!(chain.detile_level(&tiled, 0, 1), linear); } /// The three volume textures of the retail TTPF archive (4 KB tiles, thick): the space each @@ -1181,5 +1377,68 @@ mod tests { assert!(!g.contains_key(&(false, 9, 5, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }))); assert!(!g.contains_key(&(true, 10, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }))); } + + #[test] + fn tile_level_matches_element_by_element_and_exploits_contiguous_runs() { + // Standard 2D modes with 1..4B elements must detect multi-element contiguous runs. + assert!(Layout::new(5, 0, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap().run_elems >= 4); + assert!(Layout::new(10, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap().run_elems >= 2); + for mode in MODES { + for e in 0..5u32 { + for cfg in configs() { + let mut lay = Layout::new(mode, e, cfg).unwrap(); + lay.base_xor = (lay.block_bytes / 2) & !((1 << e) - 1); + let c = Chain::new(lay, 77, 45, 1, 7); + let es = 1usize << e; + for (k, l) in c.levels.iter().enumerate() { + let lin: Vec = (0..l.width * l.height * es).map(|i| ((i * 53 + k * 17) % 251) as u8 | 1).collect(); + for slice in [0usize, 3] { + let mut got = vec![0u8; c.slice_bytes]; + let mut want = vec![0u8; c.slice_bytes]; + c.tile_level(&mut got, k, slice, &lin); + for y in 0..l.height { + for x in 0..l.width { + let o = c.element_at(l, x, y, slice); + want[o..o + es].copy_from_slice(&lin[(y * l.width + x) * es..][..es]); + } + } + assert!(got == want, "tile_level mismatch: mode {mode} e {e} {cfg:?} level {k} slice {slice}"); + } + } + } + } + } + } + + #[test] + fn low_base_xor_bits_bound_runs_without_changing_bytes() { + for (mode, e) in [(5, 0u32), (10, 2)] { + let es = 1usize << e; + for cfg in configs() { + let plain = Layout::new(mode, e, cfg).unwrap(); + for xor in [es, 3 * es, plain.block_bytes / 2] { + let mut layout = plain; + layout.base_xor = xor; + if xor == es { + assert_eq!(layout.effective_run(), 1, "mode {mode} e {e} {cfg:?}"); + } + let chain = Chain::new(layout, 77, 45, 1, 1); + let level = chain.levels[0]; + let linear: Vec = (0..level.width * level.height * es).map(|i| (i * 53 % 251) as u8).collect(); + let mut tiled = vec![0u8; chain.slice_bytes]; + chain.tile_level(&mut tiled, 0, 0, &linear); + let mut want = vec![0u8; chain.slice_bytes]; + for y in 0..level.height { + for x in 0..level.width { + let offset = chain.element_at(&level, x, y, 0); + want[offset..offset + es].copy_from_slice(&linear[(y * level.width + x) * es..][..es]); + } + } + assert_eq!(tiled, want, "mode {mode} e {e} {cfg:?} xor {xor:#x}"); + assert_eq!(chain.detile_level(&tiled, 0, 0), linear, "mode {mode} e {e} {cfg:?} xor {xor:#x}"); + } + } + } + } } From 51182d0175b4c25c913d82c5b6e2e441a57ff546 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 01:13:27 -0800 Subject: [PATCH 028/175] D3D12.X: cache positive mirror range lookups Every mirrored vertex or index bind and draw searched the append-only mirror table behind one global mutex. Once a title created a mirror, repeated hot-path lookups serialized even though existing entries never change. Keep a complete ordered mirror snapshot per thread and answer positive lookups locally. Misses still lock and refresh from the authoritative table, preserving first-match range selection and immediate discovery before creating a mirror; the no-mirror case rejects from the existing byte counter. Assisted-by: Codex (GPT-5.6-sol) (cherry picked from commit 66f0ea5462c03d35c52772b94ba328c8e888e24d) --- crates/xcl/src/hle/d3d12x/list_x.rs | 52 ++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 12058c318b..b7cf57bbe2 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4465,10 +4465,41 @@ unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: b static MIRRORS: Mutex> = Mutex::new(Vec::new()); /// bytes of mirrors made (never freed) static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); +/// Append generation. Incremented while `MIRRORS` is locked, before publishing a new range, so a +/// lookup that observes it refreshes under that lock and cannot retain a stale negative result. +static MIRROR_GENERATION: AtomicU64 = AtomicU64::new(0); +std::thread_local! { + /// Mirrors are append-only. A full ordered snapshot answers both hits and authoritative misses + /// without the global lock until the append generation changes. + static MIRROR_LOOKUP: std::cell::RefCell<(u64, Vec<(u64, usize, usize)>)> = const { std::cell::RefCell::new((0, Vec::new())) }; +} + +fn mirror_in(ranges: &[(u64, usize, usize)], va: u64, bytes: usize) -> Option { + ranges.iter() + .find(|&&(start, len, _)| va >= start && va + bytes as u64 <= start + len as u64) + .map(|&(start, _, mirror)| mirror + (va - start) as usize) +} + +fn cached_mirror( + cache: &mut (u64, Vec<(u64, usize, usize)>), generation: u64, va: u64, bytes: usize, + refresh: impl FnOnce() -> Vec<(u64, usize, usize)>, +) -> Option { + if cache.0 != generation { + cache.1 = refresh(); + cache.0 = generation; + } + mirror_in(&cache.1, va, bytes) +} /// Where `[va, va + bytes)` is in a mirror, if it is in one. fn mirrored(va: u64, bytes: usize) -> Option { - MIRRORS.lock().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) + let generation = MIRROR_GENERATION.load(Ordering::Acquire); + if generation == 0 { + return None; + } + MIRROR_LOOKUP.with(|cache| { + cached_mirror(&mut cache.borrow_mut(), generation, va, bytes, || MIRRORS.lock().unwrap().clone()) + }) } /// The mirror address of the title's buffer at `va`; its range's mirror is made (and filled @@ -4500,6 +4531,9 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { None => u.alloc(len, 0x1_0000)? as usize, }; std::ptr::copy_nonoverlapping(start as *const u8, p as *mut u8, len); + // Invalidate cached misses before publishing while still holding the lock. A lookup that sees + // the new generation blocks on `g` until this range is present in the refreshed snapshot. + MIRROR_GENERATION.fetch_add(1, Ordering::Release); g.push((start, len, p)); let total = MIRROR_BYTES.fetch_add(len as u64, Ordering::Relaxed) + len as u64; if g.len() <= 8 || g.len().is_power_of_two() { @@ -5647,6 +5681,22 @@ mod tests { use super::*; use std::sync::Arc; + #[test] + fn mirror_snapshot_keeps_order_and_refreshes_only_on_miss() { + let first = (100, 100, 1_000); + let second = (150, 100, 2_000); + let mut cache = (0, Vec::new()); + assert_eq!(cached_mirror(&mut cache, 1, 220, 10, || vec![first, second]), Some(2_070)); + // The complete ordered snapshot was retained, not just the range found above: where the + // ranges overlap, lookup still chooses the first global entry without refreshing. + assert_eq!(cached_mirror(&mut cache, 1, 160, 10, || panic!("positive hit locked")), Some(1_060)); + assert_eq!(cached_mirror(&mut cache, 1, 400, 10, || panic!("unchanged miss locked")), None); + + let third = (500, 50, 3_000); + assert_eq!(cached_mirror(&mut cache, 2, 510, 10, || vec![first, second, third]), Some(3_010)); + assert_eq!(mirror_in(&cache.1, 550, 1), None, "ranges are half-open"); + } + /// 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] From 5338c0ffb58dcacf94e0f7b3c5d7e5193f26285a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:21:11 +0100 Subject: [PATCH 029/175] D3D12.X: reduce unrelated write-watch scanning Port of upstream 854de859. Use an 8 MiB merge gap derived from measured GetWriteWatch call and committed-page scan costs. This keeps merging the 1 MiB-spaced sparse ranges while no longer scanning up to 64 MiB of unrelated pages between ranges. The hot-block gap (XCL_WATCH_GAP_MB) is unchanged. (cherry picked from commit 854de85921bf703d02ca08eebc890058511ef997) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 53 ++++++++++++++++++--- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 56757afc99..c3b5a8603a 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -3001,11 +3001,11 @@ unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result 0 && regions.iter().any(|&(rbase, rsize)| rbase <= base && end <= rbase + rsize), "range {base:#x}..{end:#x} is outside one allocation"); + } + for &(start, end) in &wanted { + for &(rbase, rsize) in ®ions { + let (lo, hi) = (start.max(rbase), end.min(rbase + rsize)); + if lo < hi { + assert!(ranges.iter().any(|&(base, size)| base <= lo && hi <= base + size), "wanted part {lo:#x}..{hi:#x} is not covered"); + } + } + } + } + #[test] fn small_cpu_filled_target_accepts_wide_glyph_atlas_and_rejects_large_or_depth() { assert!(is_small_cpu_filled_target(2048, 128, 1, 0x300005), "2048x128 R8 glyph atlas must sync"); From 0edced48b7a05eea3c324c8018730f88467ef656 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:38:42 +0100 Subject: [PATCH 030/175] D3D12.X: split sparse readback spin and submission out of STATE lock Port of upstream 85360b6c (same subject, part of #2688) onto this branch. On a retail title in its world (RX 9070 XT, ~4 fps) a submit's ExecuteCommandLists waited 0.7-1.9 ms for the sparse lock; with XCL_LOOK_STATS=2 title threads held it ~3.6 ms a submit for CPU reads and the copies back around them, spinning on copy-back fences and recording copies with the lock held. What upstream does, kept as is: - The copy-back queues and the staging pool move out of `State` into a leaf `ReadbackQueue` (`SharedReadbacks`: mutex + condvar, reachable without `STATE` through `READBACKS`), and the per-queue copy-back fences into `RbSubmit`. Lock order: `STATE` -> `ReadbackQueue` and `RbSubmit` -> `ReadbackQueue`; `STATE` and `RbSubmit` never nest, and the leaf is not held across fence spins, condvar waits, D3D12 calls or `RbJob` drops. - `readback_after_execute` takes `STATE` only for a snapshot (`prepare_after_execute`: tiles, generations, immediates, the windows' buffers); the Signals, the copy lists and their ExecuteCommandLists go out under `RbSubmit` (`submit_async_readback`). A prepared plan holds a submitting token (`SubmittingGuard`, counted in `RB_PENDING`) until it is published or dropped, so a settle in between waits for it (within its budget) rather than returning with stale memory. The rare synchronous fallback (no readback queue) is unchanged. - `settle_readbacks*` and `readback_now` spin for title-done copies outside all locks (one total budget), and take `STATE` only when a job finished or one is being landed; jobs land in their `seq` order under `STATE` (`land_finished_readbacks`). The readback thread looks at the leaf queue first and only tries `STATE` when something finished. - Copy-back jobs past the pool's cap of 32 are dropped outside all locks. - Six tests of the split (lock-free spin, no `STATE` when nothing finished, `seq` order under concurrent settles, recording outside `STATE` and the excess jobs, `STATE` latency under spin, unpublished-plan visibility / timeout / cancellation). Adapted here: - `before_execute_on` already hands its mapping wait (fence, value, new mappings) back for `before_execute` to do after letting go of `STATE`. It now returns that and the excess copy-back jobs, which `before_execute` drops after the lock, before the wait. - The recording test waits for the submitting token, not a `queue_fences` entry, as upstream's later dc763946 does. - `RbJob::fences` names `RbSubmit::rb_queue_fences`. The branch's own changes around it (pool packing, GPU-written runs, mapping CPU waits, pagelog notes of landed copies, XCL_SUBMIT_LOCK_FIRST, the holder sums) are unchanged. Not moved, here or upstream: `readback_now`'s own copy back (`readback_ranges` on the sparse queue and its CPU wait) still runs with `STATE` held. cargo test -p xcl --lib sparse -- --test-threads=4 (RX 9070 XT): 92 passed, 1 failed, 1 ignored; on 51182d01: 86 passed, 1 failed, 1 ignored. The failure, the same on both: private_physical_pages_reach_the_gpu_on_mapping. No SKIPPED lines. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/sparse.rs | 1478 +++++++++++++++++++++------ 1 file changed, 1187 insertions(+), 291 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 7094169fdd..57af6ced36 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; @@ -533,14 +533,17 @@ struct RbJob { copies: Vec<(usize, usize, usize, u32)>, /// the type of queue `list` is for (a copy back runs on the title's own queue) ty: D3D12_COMMAND_LIST_TYPE, - /// the title queue's fences for it (`State::rb_queue_fences`): the first reaches `rb_v` when + /// the title queue's fences for it (`RbSubmit::rb_queue_fences`): the first reaches `rb_v` when /// the lists it follows are done, the second `done_v` when the copy is. None: `rb_fence` and /// the readback queue's fence (the form before) fences: Option<(ID3D12Fence, ID3D12Fence)>, - /// place among the submissions' jobs (`State::job_seq`): copies and immediates land in it + /// place among the submissions' jobs (`ReadbackQueue::job_seq`): copies and immediates land in it seq: u64, } +// D3D12 objects and mapped readback staging pointers are free-threaded; mutated under mutexes. +unsafe impl Send for RbJob {} + /// In an immediate's byte count: the cell is a counter that the title's queues write in turn, /// with values that only rise as they are recorded. A list that runs late – a retail title's /// compute jobs, tens of frames after their recording when its submits are slow – writes an @@ -559,10 +562,158 @@ struct ImmJob { writes: Vec<(usize, u64, u8, u32)>, } +unsafe impl Send for ImmJob {} + +/// Async readback job queues and buffer pool under a pure leaf lock separate from `STATE`. +/// +/// Strict 2-level DAG lock order (mathematically deadlock-free): +/// - `STATE` -> `ReadbackQueue` (mark `submitting` on plan prep, pop finished jobs, return recycled +/// `RbJob`s up to cap 32) +/// - `RbSubmit` -> `ReadbackQueue` (pop pooled `RbJob`, push newly submitted jobs & clear `submitting`) +/// - `STATE` and `RbSubmit` never nest; `ReadbackQueue` is never held across GPU fence spins, +/// `Condvar` waits (released while waiting), D3D12 COM calls, or `RbJob` drops. +struct ReadbackQueue { + /// fallback fence signalled on title queues (when a job has `fences: None`) + rb_fence: ID3D12Fence, + /// fallback readback queue fence (when a job has `fences: None`) + rbq_done: Option, + /// submitted copies back, oldest first, and finished ones to reuse + rb_jobs: VecDeque, + rb_pool: Vec, + /// immediates of the title's submissions, oldest first, and the count that orders them + /// with `rb_jobs` + imm_jobs: VecDeque, + job_seq: u64, + /// count of async readback plans prepared under `STATE` whose jobs have not yet been + /// published (or cancelled on error) into `rb_jobs`/`imm_jobs` + submitting: usize, + /// count of finished jobs currently popped and being landed into CPU memory under `STATE` + /// (forces concurrent `settle_readbacks*` callers to synchronize on `STATE` before returning) + landing: usize, +} + +unsafe impl Send for ReadbackQueue {} + +impl ReadbackQueue { + fn new(rb_fence: ID3D12Fence, rbq_done: Option) -> Self { + Self { rb_fence, rbq_done, rb_jobs: VecDeque::new(), rb_pool: Vec::new(), imm_jobs: VecDeque::new(), job_seq: 0, submitting: 0, landing: 0 } + } +} + +impl Drop for ReadbackQueue { + fn drop(&mut self) { + let left = self.rb_jobs.len() + self.imm_jobs.len(); + if left > 0 { + RB_PENDING.fetch_sub(left, Ordering::Release); + } + } +} + +/// Shared `ReadbackQueue` plus a `Condvar` notified whenever an in-flight `prepare_after_execute` +/// plan finishes publishing or cancels, so settling callers observe the transition within their +/// existing wait budget without polling or holding `STATE`. +struct SharedReadbacks { + queue: Mutex, + published: std::sync::Condvar, +} + +impl SharedReadbacks { + fn new(rb_fence: ID3D12Fence, rbq_done: Option) -> Self { + Self { + queue: Mutex::new(ReadbackQueue::new(rb_fence, rbq_done)), + published: std::sync::Condvar::new(), + } + } + + fn lock(&self) -> std::sync::LockResult> { + self.queue.lock() + } +} + +/// Tracks one prepared `AsyncReadbackPlan` from `prepare_after_execute` (while `STATE` is still +/// held) until `submit_async_readback` either publishes its jobs or bails/drops. Holds a strong +/// `Arc` so `ReadbackQueue::drop` cannot run while a submission is in flight. +struct SubmittingGuard { + readbacks: Arc, + active: bool, +} + +impl SubmittingGuard { + fn begin(readbacks: &Arc) -> Self { + let mut rq = readbacks.lock().unwrap(); + rq.submitting += 1; + RB_PENDING.fetch_add(1, Ordering::Release); + Self { readbacks: Arc::clone(readbacks), active: true } + } + + /// Atomically replace the pending submission token with `added` queued jobs under `rq`. + fn finish(mut self, rq: &mut ReadbackQueue, added: usize) { + rq.submitting -= 1; + self.active = false; + if added > 1 { + RB_PENDING.fetch_add(added - 1, Ordering::Release); + } else if added == 0 { + RB_PENDING.fetch_sub(1, Ordering::Release); + } + } +} + +impl Drop for SubmittingGuard { + fn drop(&mut self) { + if self.active { + let mut rq = self.readbacks.lock().unwrap(); + rq.submitting -= 1; + RB_PENDING.fetch_sub(1, Ordering::Release); + drop(rq); + self.readbacks.published.notify_all(); + } + } +} + +/// Per-queue async readback submission state, locked outside `STATE` so `readback_after_execute` +/// records `CopyBufferRegion` / `pc_execute` / `Signal` without blocking `STATE`. +struct RbSubmit { + dev: ID3D12Device, + /// title queue -> the two fences it signals around a copy back, and the last value. One set + /// a queue: with one fence for all, a queue that got to its Signal first let the copies of a + /// queue still waiting run early + rb_queue_fences: FxHashMap, +} + +unsafe impl Send for RbSubmit {} + +impl RbSubmit { + fn new(dev: ID3D12Device) -> Self { + Self { dev, rb_queue_fences: FxHashMap::default() } + } +} + +enum ReadyJob { + Imm(ImmJob), + Rb(RbJob), +} + +struct RbChunk { + win: usize, + va: usize, + len: usize, + gen: u32, +} + +struct AsyncReadbackPlan { + rb_submit: Arc>, + readbacks: Arc, + windows: Vec<(usize, ID3D12Resource)>, + batches: Vec>, + imm: Vec<(usize, u64, u8, u32)>, + submitting: SubmittingGuard, +} + /// How far `drain_readbacks` goes #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Drain { /// only copies the GPU has finished + #[cfg(test)] Finished, /// also those whose title work is done (waiting for the copy itself): before a CPU read /// the title made sure of, e.g. after its wait for the value a list wrote @@ -587,10 +738,6 @@ struct State { /// fence signalled on title queues after their lists, so a copy back waits for them rb_fence: ID3D12Fence, rb_value: u64, - /// title queue -> the two fences it signals around a copy back, and the last value. One set - /// a queue: with one fence for all, a queue that got to its Signal first let the copies of a - /// queue still waiting run early - rb_queue_fences: FxHashMap, /// copies back after the title's submissions (`readback_after_execute`): on a queue of their /// own (`rbq`, None: on `queue`, waited for on the CPU), landing in the title's memory once /// done (`drain_readbacks`). The title's queues can wait for work the title submits after @@ -598,13 +745,10 @@ struct State { /// on `queue`, every upload behind it (`before_execute` waiting for ring room). rbq: Option<(ID3D12CommandQueue, ID3D12Fence)>, rbq_value: u64, - /// submitted copies back, oldest first, and finished ones to reuse - rb_jobs: VecDeque, - rb_pool: Vec, - /// immediates of the title's submissions, oldest first, and the count that orders them - /// with `rb_jobs` - imm_jobs: VecDeque, - job_seq: u64, + /// async readback job queues and reusable staging pool (leaf lock separate from `STATE`) + readbacks: Arc, + /// async readback recorder and per-queue fence map (locked outside `STATE`) + rb_submit: Arc>, /// (window start, reserved buffer) of each sparse window windows: Vec<(usize, ID3D12Resource)>, /// video-memory pool heaps (None: given back, its index free for the next one) @@ -1048,6 +1192,14 @@ static STATE: Mutex> = Mutex::new(None); /// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other. static QUEUE: Mutex> = Mutex::new(None); +/// The active state's async readback queue, reachable without locking `STATE` (`settle_readbacks*`, +/// `start_readback_thread`). Only locked briefly to clone the `Arc` (never nested with other locks). +static READBACKS: Mutex>> = Mutex::new(None); + +fn readbacks_arc() -> Option> { + READBACKS.lock().unwrap().clone() +} + /// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` pub fn pool_bytes() -> (usize, usize) { let g = lock_state(); @@ -1163,6 +1315,8 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); let _ = queue.SetName(windows::core::w!("xcl sparse queue")); + let readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), rbq.as_ref().map(|(_, f)| f.clone()))); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); Ok(State { dev: dev.clone(), queue, @@ -1171,13 +1325,10 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - event, rb_fence, rb_value: 0, - rb_queue_fences: FxHashMap::default(), rbq, rbq_value: 0, - rb_jobs: VecDeque::new(), - rb_pool: Vec::new(), - imm_jobs: VecDeque::new(), - job_seq: 0, + readbacks, + rb_submit, windows, pools: Vec::new(), free: FreePools::new(), @@ -1315,8 +1466,10 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { // its last buffers reaches `forget_buffer`, which takes the lock (#344) // (the queue first: `queue()` never answers with one older than the state's) let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); + let old_rb = READBACKS.lock().unwrap().replace(Arc::clone(&s.readbacks)); let old = STATE.lock().unwrap().replace(s); drop(old); + drop(old_rb); drop(old_queue); for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { committed(a, b - a); @@ -2047,177 +2200,121 @@ impl State { } } - /// A copy back's list and a readback buffer of at least `need` bytes (reused when one fits) - unsafe fn rb_job(&mut self, need: usize, ty: D3D12_COMMAND_LIST_TYPE) -> Option { - if let Some(i) = self.rb_pool.iter().enumerate().filter(|(_, j)| j.cap >= need && j.ty == ty).min_by_key(|(_, j)| j.cap).map(|(i, _)| i) { - return Some(self.rb_pool.swap_remove(i)); - } - let cap = need.max(64 << 10).next_power_of_two().min(READBACK_STAGING); - let alloc: ID3D12CommandAllocator = self.dev.CreateCommandAllocator(ty).ok()?; - let list: ID3D12GraphicsCommandList = self.dev.CreateCommandList(0, ty, &alloc, None).ok()?; - list.Close().ok()?; - let _ = list.SetName(windows::core::w!("xcl sparse readback list")); - let mut d = buffer_desc(cap as u64); - d.Flags = D3D12_RESOURCE_FLAG_NONE; - let mut r: Option = None; - self.dev - .CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r) - .ok()?; - let buf = r?; - let mut p: *mut c_void = std::ptr::null_mut(); - buf.Map(0, None, Some(&mut p)).ok()?; - Some(RbJob { alloc, list, buf, ptr: p as *mut u8, cap, rb_v: 0, done_v: 0, copies: Vec::new(), ty, fences: None, seq: 0 }) - } - - /// Land submitted copies back in the title's memory as far as `how` says: every job that is - /// done, a queue's own in their order (a job of a queue that waits does not hold back the - /// other queues' jobs). - unsafe fn drain_readbacks(&mut self, how: Drain) { - self.drain_readbacks_spin(how, 2000); - } - - /// `drain_readbacks`, waiting for a finished list's copy for `spin_us` at most. - unsafe fn drain_readbacks_spin(&mut self, how: Drain, spin_us: u128) { - let rbq_done = self.rbq.as_ref().map(|(_, f)| f.clone()); - let mut i = 0; - let mut k = 0; - loop { - // the immediates of submissions before the next copy back first - while k < self.imm_jobs.len() && self.rb_jobs.get(i).is_none_or(|j| self.imm_jobs[k].seq < j.seq) { - if super::real::fence_completed(&self.imm_jobs[k].fence) < self.imm_jobs[k].value { - k += 1; - continue; - } - let Some(job) = self.imm_jobs.remove(k) else { break }; - for &(va, value, bytes, gen) in &job.writes { - self.store_imm(va, value, bytes, gen); - } - RB_PENDING.fetch_sub(1, Ordering::Release); - } - if i >= self.rb_jobs.len() { - break; - } - let (title_f, done_f, rb_v, done_v) = { - let j = &self.rb_jobs[i]; - match (&j.fences, &rbq_done) { - (Some((a, b)), _) => (a.clone(), b.clone(), j.rb_v, j.done_v), - (None, Some(d)) => (self.rb_fence.clone(), d.clone(), j.rb_v, j.done_v), - (None, None) => { - i += 1; + /// A copy back's list and a readback buffer of at least `need` bytes (reused when one fits). + #[cfg(test)] + unsafe fn rb_job(&self, need: usize, ty: D3D12_COMMAND_LIST_TYPE) -> Option { + take_or_alloc_rb_job(&self.dev, &self.readbacks, need, ty) + } + + /// Pop every finished `imm_job` and `rb_job` from `self.readbacks` in strict ascending `seq` + /// order, land them into CPU memory under `&mut self` (`STATE`), recycle finished `RbJob`s up + /// to cap 32, and return any excess `RbJob`s so the caller drops them outside all locks. + unsafe fn land_finished_readbacks(&mut self) -> Vec { + let ready: Vec = { + let mut rq = self.readbacks.lock().unwrap(); + let rbq_done = rq.rbq_done.clone(); + let mut out = Vec::new(); + let mut i = 0; + let mut k = 0; + loop { + // the immediates of submissions before the next copy back first + while k < rq.imm_jobs.len() && rq.rb_jobs.get(i).is_none_or(|j| rq.imm_jobs[k].seq < j.seq) { + if super::real::fence_completed(&rq.imm_jobs[k].fence) < rq.imm_jobs[k].value { + k += 1; continue; } + let Some(job) = rq.imm_jobs.remove(k) else { break }; + out.push(ReadyJob::Imm(job)); } - }; - if super::real::fence_completed(&done_f) < done_v { - if how == Drain::Finished || super::real::fence_completed(&title_f) < rb_v { - i += 1; - continue; - } - // the title's lists are done: only the copy itself is left - // (for 2 ms at most: the state's lock is held here, and every submit needs it; a copy - // that stands behind something else on its queue lands when it is done) - // (no event: `self.event` is the tile queue's, see `wait_for`) - let t0 = std::time::Instant::now(); - while super::real::fence_completed(&done_f) < done_v && t0.elapsed().as_micros() < spin_us { - std::thread::yield_now(); + if i >= rq.rb_jobs.len() { + break; } - if super::real::fence_completed(&done_f) < done_v { - static LATE: AtomicU64 = AtomicU64::new(0); - let k = LATE.fetch_add(1, Ordering::Relaxed) + 1; - if k.is_power_of_two() { - crate::xlog_warn!("sparse: {k} copies back so far not finished 2 ms after the title's work they follow – left for later"); + let done = { + let j = &rq.rb_jobs[i]; + match (&j.fences, &rbq_done) { + (Some((_, b)), _) => super::real::fence_completed(b) >= j.done_v, + (None, Some(d)) => super::real::fence_completed(d) >= j.done_v, + (None, None) => false, } + }; + if !done { i += 1; continue; } + let Some(job) = rq.rb_jobs.remove(i) else { break }; + out.push(ReadyJob::Rb(job)); } - let Some(mut job) = self.rb_jobs.remove(i) else { break }; - let copies = std::mem::take(&mut job.copies); - for &(dst, off, len, gen) in &copies { - self.copy_back(job.ptr, dst, off, len, gen); - } - TILE_WORK[3].fetch_add(copies.iter().map(|c| c.2 as u64).sum(), Ordering::Relaxed); - RB_PENDING.fetch_sub(1, Ordering::Release); - job.copies = copies; - job.copies.clear(); - // (a burst of copies back does not keep its buffers for good: each is up to 16 MiB of - // host memory) - if self.rb_pool.len() < 32 { - self.rb_pool.push(job); + if !out.is_empty() { + rq.landing += out.len(); } + out + }; + if ready.is_empty() { + return Vec::new(); } - } - - /// `readback_ranges` without a CPU wait: the copies are recorded on the title's own `queue`, - /// right behind the lists that wrote `ranges` (so they wait for those lists and for nothing - /// else), and land in the title's memory in `drain_readbacks` once `fences.1` reaches `v`. - unsafe fn readback_async(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], fences: &(ID3D12Fence, ID3D12Fence), v: u64) { - let ty = queue.GetDesc().Type; - // the mapped parts, in readback-buffer sized batches: (window, address, bytes, - // `TileEntry::gen` of its tile) - let mut batches: Vec> = vec![Vec::new()]; - let mut used = 0usize; - for &(a, n) in ranges { - let mut at = 0usize; - while at < n { - let cur = a + at; - let tile = cur & !(TILE - 1); - let Some(wi) = self.window_index(cur) else { break }; - let to_tile_end = (tile + TILE) - cur; - // (a tile with no video memory has nothing to copy back, like one not mapped) - let Some(gen) = self.mapped.get(&tile).filter(|e| e.pool != LAZY).map(|e| e.gen) else { - at += (n - at).min(to_tile_end); - continue; - }; - if used == READBACK_STAGING { - batches.push(Vec::new()); - used = 0; + let landed_n = ready.len(); + let mut recycled: Vec = Vec::new(); + for item in ready { + match item { + ReadyJob::Imm(job) => { + for &(va, value, bytes, gen) in &job.writes { + self.store_imm(va, value, bytes, gen); + } + RB_PENDING.fetch_sub(1, Ordering::Release); + } + ReadyJob::Rb(mut job) => { + let copies = std::mem::take(&mut job.copies); + for &(dst, off, len, gen) in &copies { + self.copy_back(job.ptr, dst, off, len, gen); + } + TILE_WORK[3].fetch_add(copies.iter().map(|c| c.2 as u64).sum(), Ordering::Relaxed); + RB_PENDING.fetch_sub(1, Ordering::Release); + job.copies = copies; + job.copies.clear(); + recycled.push(job); } - let to_win_end = (self.windows[wi].0 + crate::gpu::uma::WINDOW) - cur; - let chunk = (n - at).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); - batches.last_mut().expect("batch").push((wi, cur, chunk, gen)); - used += chunk; - at += chunk; } } - for batch in batches.into_iter().filter(|b| !b.is_empty()) { - let need = batch.iter().map(|c| c.2).sum::(); - let Some(mut job) = self.rb_job(need, ty) else { - crate::xlog_warn!("sparse: no readback buffer for a copy back of {need} bytes – left out"); - // (the Signal after the loop still goes out: what was recorded for it stands) - break; - }; - let _ = job.alloc.Reset(); - let _ = job.list.Reset(&job.alloc, None); - let mut off = 0usize; - for (wi, cur, chunk, gen) in batch { - let (base, res) = (self.windows[wi].0, self.windows[wi].1.clone()); - job.list.CopyBufferRegion(&job.buf, off as u64, &res, (cur - base) as u64, chunk as u64); - job.copies.push((cur, off, chunk, gen)); - off += chunk; - } - if job.list.Close().is_ok() { - pc_execute(queue, &job.list); + let mut excess = Vec::new(); + { + let mut rq = self.readbacks.lock().unwrap(); + rq.landing -= landed_n; + for job in recycled { + // (a burst of copies back does not keep its buffers for good: each is up to 16 MiB of + // host memory; excess jobs drop outside all locks) + if rq.rb_pool.len() < 32 { + rq.rb_pool.push(job); + } else { + excess.push(job); + } } - job.rb_v = v; - job.done_v = v; - job.fences = Some(fences.clone()); - self.job_seq += 1; - job.seq = self.job_seq; - self.rb_jobs.push_back(job); - RB_PENDING.fetch_add(1, Ordering::Release); - RB_ASYNC.store(true, Ordering::Relaxed); } - let _ = queue.Signal(&fences.1, v); + excess + } + + /// Land submitted copies back in the title's memory as far as `how` says (test helper on a + /// standalone `State` without global `STATE`). + #[cfg(test)] + unsafe fn drain_readbacks(&mut self, how: Drain) -> Vec { + self.drain_readbacks_spin(how, 2000) + } + + #[cfg(test)] + unsafe fn drain_readbacks_spin(&mut self, how: Drain, spin_us: u128) -> Vec { + if wait_and_check_ready(&self.readbacks, how, spin_us, None) != ReadyCheck::LandNow { + return Vec::new(); + } + self.land_finished_readbacks() } /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. - unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { + /// Returns any excess recycled `RbJob`s for the caller to drop outside `STATE`. + unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) -> Vec { self.flush_pending(); // copies back of earlier submissions first: their data is older than this one's - self.drain_readbacks(Drain::TitleDone); - let Some((rb, p)) = self.readback_buf() else { return }; + let excess = self.land_finished_readbacks(); + let Some((rb, p)) = self.readback_buf() else { return excess }; let mut pending: Vec<(usize, usize, usize, u32)> = Vec::new(); // (va, rb_off, chunk, gen of its tile) let mut used = 0usize; let mut open = false; @@ -2279,6 +2376,7 @@ impl State { if open { flush_and_copy(self, &mut open, &mut pending, &mut used, p); } + excess } /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` @@ -2598,19 +2696,258 @@ pub fn queue() -> Option { QUEUE.lock().unwrap().clone() } -pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { +/// Pop a pooled `RbJob` of at least `need` bytes for `ty` under the leaf `readbacks` lock, or +/// allocate a new one on `dev` outside both `STATE` and `readbacks`. +unsafe fn take_or_alloc_rb_job(dev: &ID3D12Device, readbacks: &SharedReadbacks, need: usize, ty: D3D12_COMMAND_LIST_TYPE) -> Option { + { + let mut rq = readbacks.lock().unwrap(); + if let Some(i) = rq.rb_pool.iter().enumerate().filter(|(_, j)| j.cap >= need && j.ty == ty).min_by_key(|(_, j)| j.cap).map(|(i, _)| i) { + return Some(rq.rb_pool.swap_remove(i)); + } + } + let cap = need.max(64 << 10).next_power_of_two().min(READBACK_STAGING); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).ok()?; + list.Close().ok()?; + let _ = list.SetName(windows::core::w!("xcl sparse readback list")); + let mut d = buffer_desc(cap as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut r).ok()?; + let buf = r?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + Some(RbJob { alloc, list, buf, ptr: p as *mut u8, cap, rb_v: 0, done_v: 0, copies: Vec::new(), ty, fences: None, seq: 0 }) +} + +/// Whether `rq` holds at least one finished unpopped `ImmJob` or `RbJob`. +unsafe fn rq_has_unpopped_finished(rq: &ReadbackQueue) -> bool { + if rq.imm_jobs.iter().any(|j| super::real::fence_completed(&j.fence) >= j.value) { + return true; + } + rq.rb_jobs.iter().any(|j| { + let done_f = match (&j.fences, &rq.rbq_done) { + (Some((_, b)), _) => b, + (None, Some(d)) => d, + (None, None) => return false, + }; + super::real::fence_completed(done_f) >= j.done_v + }) +} + +/// Whether any finished unpopped readback job exists (used by the background thread so it skips +/// `STATE` whenever nothing is ready to land or another thread is already landing). +unsafe fn has_unpopped_finished_jobs(rb: &SharedReadbacks) -> bool { + let rq = rb.lock().unwrap(); + rq_has_unpopped_finished(&rq) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum ReadyCheck { + NothingReady, + LandNow, + TimedOut, +} + +/// Wait outside `STATE` and outside `READBACKS` for any already-prepared `prepare_after_execute` +/// plan (`rq.submitting > 0`) to publish or cancel within `deadline`, and then for any +/// `Drain::TitleDone` readback job whose title lists are already done on the GPU (up to `spin_us` +/// total across all such jobs). +/// +/// Returns `ReadyCheck::LandNow` iff at least one job is finished or currently being landed under +/// `STATE` (meaning the caller must acquire `STATE` to land or synchronize with an in-flight land), +/// `ReadyCheck::TimedOut` if `deadline` expired while a submission was still publishing, or +/// `ReadyCheck::NothingReady` if no work is ready to land. +unsafe fn wait_and_check_ready(rb: &SharedReadbacks, how: Drain, spin_us: u128, deadline: Option) -> ReadyCheck { + { + let mut rq = rb.lock().unwrap(); + while rq.submitting > 0 { + if let Some(dl) = deadline { + let Some(rem) = dl.checked_duration_since(std::time::Instant::now()) else { + return ReadyCheck::TimedOut; + }; + if rem.is_zero() { + return ReadyCheck::TimedOut; + } + let (g, res) = rb.published.wait_timeout(rq, rem).unwrap(); + rq = g; + if rq.submitting > 0 && res.timed_out() { + return ReadyCheck::TimedOut; + } + } else { + rq = rb.published.wait(rq).unwrap(); + } + } + } + if how == Drain::TitleDone && spin_us > 0 { + let to_wait: Vec<(ID3D12Fence, u64)> = { + let rq = rb.lock().unwrap(); + let mut out = Vec::new(); + for j in &rq.rb_jobs { + let (title_f, done_f, rb_v, done_v) = match (&j.fences, &rq.rbq_done) { + (Some((a, b)), _) => (a, b, j.rb_v, j.done_v), + (None, Some(d)) => (&rq.rb_fence, d, j.rb_v, j.done_v), + (None, None) => continue, + }; + if super::real::fence_completed(done_f) < done_v && super::real::fence_completed(title_f) >= rb_v { + out.push((done_f.clone(), done_v)); + } + } + out + }; + if !to_wait.is_empty() { + // Single total spin budget across all title-done copies, completely outside all locks. + let t0 = std::time::Instant::now(); + let mut timed_out = 0u64; + for (done_f, done_v) in &to_wait { + while super::real::fence_completed(done_f) < *done_v && t0.elapsed().as_micros() < spin_us { + std::thread::yield_now(); + } + if super::real::fence_completed(done_f) < *done_v { + timed_out += 1; + } + } + if timed_out > 0 { + static LATE: AtomicU64 = AtomicU64::new(0); + let prev = LATE.fetch_add(timed_out, Ordering::Relaxed); + for n in 1..=timed_out { + let k = prev + n; + if k.is_power_of_two() { + crate::xlog_warn!("sparse: {k} copies back so far not finished after the title's work they follow – left for later"); + } + } + } + } + } + let rq = rb.lock().unwrap(); + if rq.landing > 0 || rq_has_unpopped_finished(&rq) { + ReadyCheck::LandNow + } else { + ReadyCheck::NothingReady + } +} + +/// Record and submit async readback copies + fences on `queue` under `plan.rb_submit` (outside +/// `STATE`), then push the resulting `ImmJob` and `RbJob`s to `plan.readbacks` once both fences +/// have been signalled on `queue`. +unsafe fn submit_async_readback(queue: &ID3D12CommandQueue, plan: AsyncReadbackPlan) { + submit_async_readback_inner( + queue, + plan, + #[cfg(test)] + None, + ); +} + +#[cfg(test)] +type PublishHook<'a> = &'a dyn Fn(&ID3D12Fence, u64); + +unsafe fn submit_async_readback_inner( + queue: &ID3D12CommandQueue, + plan: AsyncReadbackPlan, + #[cfg(test)] before_publish: Option>, +) { + let AsyncReadbackPlan { rb_submit, readbacks, windows, batches, imm, submitting } = plan; + let mut sub = rb_submit.lock().unwrap(); + // on this queue: [the title's lists] Signal(first, v) [the copies] Signal(second, v) + let key = queue.as_raw() as usize; + if !sub.rb_queue_fences.contains_key(&key) { + let (Ok(a), Ok(b)) = (sub.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE), sub.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE)) else { + return; + }; + sub.rb_queue_fences.insert(key, (a, b, 0)); + } + let (fences, v) = { + let e = sub.rb_queue_fences.get_mut(&key).expect("fences"); + e.2 += 1; + ((e.0.clone(), e.1.clone()), e.2) + }; + let _ = queue.Signal(&fences.0, v); + + let mut submitted: Vec = Vec::with_capacity(batches.len()); + if !batches.is_empty() { + let ty = queue.GetDesc().Type; + for batch in batches { + let need = batch.iter().map(|c| c.len).sum::(); + let Some(mut job) = take_or_alloc_rb_job(&sub.dev, &readbacks, need, ty) else { + crate::xlog_warn!("sparse: no readback buffer for a copy back of {need} bytes – left out"); + // (the Signal after the loop still goes out: what was recorded for it stands) + break; + }; + let _ = job.alloc.Reset(); + let _ = job.list.Reset(&job.alloc, None); + let mut off = 0usize; + for c in batch { + let (base, ref res) = windows[c.win]; + job.list.CopyBufferRegion(&job.buf, off as u64, res, (c.va - base) as u64, c.len as u64); + job.copies.push((c.va, off, c.len, c.gen)); + off += c.len; + } + if job.list.Close().is_ok() { + pc_execute(queue, &job.list); + } + job.rb_v = v; + job.done_v = v; + job.fences = Some(fences.clone()); + submitted.push(job); + } + let _ = queue.Signal(&fences.1, v); + } + + #[cfg(test)] + if let Some(hook) = before_publish { + hook(&fences.0, v); + } + + let mut rq = readbacks.lock().unwrap(); + let mut added = 0usize; + if !imm.is_empty() { + rq.job_seq += 1; + let seq = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq, fence: fences.0.clone(), value: v, writes: imm }); + added += 1; + } + for mut job in submitted { + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + added += 1; + } + submitting.finish(&mut rq, added); + if added > 0 { + RB_ASYNC.store(true, Ordering::Relaxed); + } + drop(rq); + readbacks.published.notify_all(); +} + +unsafe fn readback_after_execute_with(state_lock: &Mutex>, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { if ranges.is_empty() && imms.is_empty() { return; } - let t0 = super::look_stats::deep().then(std::time::Instant::now); - let mut g = lock_for_submit(); - let _held = holding(Holder::After); - if let Some(t0) = t0 { - HELD.add(HELD_AFTER_WAIT, t0.elapsed().as_micros() as u64); + let is_global = std::ptr::eq(state_lock, &STATE); + let (plan, excess) = { + let t0 = (is_global && super::look_stats::deep()).then(std::time::Instant::now); + let mut g = if is_global { lock_for_submit() } else { state_lock.lock().unwrap() }; + let _held = is_global.then(|| holding(Holder::After)); + if let Some(t0) = t0 { + HELD.add(HELD_AFTER_WAIT, t0.elapsed().as_micros() as u64); + } + let Some(s) = g.as_mut() else { return }; + s.note_queue(queue); + s.prepare_after_execute(queue, ranges, imms) + }; + drop(excess); + if let Some(plan) = plan { + submit_async_readback(queue, plan); + if is_global { + start_readback_thread(); + } } - let Some(s) = g.as_mut() else { return }; - s.note_queue(queue); - s.after_execute(queue, ranges, imms); +} + +pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { + readback_after_execute_with(&STATE, queue, ranges, imms); } /// The PC `ExecuteCommandLists` of `queue` for `list` (an adopted title queue's own method, @@ -2633,39 +2970,68 @@ pub fn readbacks_async() -> bool { RB_ASYNC.load(Ordering::Relaxed) } +unsafe fn settle_readbacks_with(state_lock: &Mutex>, rb: &Arc, how: Drain, spin_us: u128, lock_ms: Option) -> bool { + let deadline = lock_ms.map(|ms| std::time::Instant::now() + std::time::Duration::from_millis(ms)); + match wait_and_check_ready(rb, how, spin_us, deadline) { + ReadyCheck::NothingReady => return true, + ReadyCheck::TimedOut => return false, + ReadyCheck::LandNow => {} + } + let is_global = std::ptr::eq(state_lock, &STATE); + let excess = match deadline { + None => { + let mut g = state_lock.lock().unwrap(); + let _held = is_global.then(|| holding(Holder::Settle)); + if let Some(s) = g.as_mut().filter(|s| Arc::ptr_eq(&s.readbacks, rb)) { + s.land_finished_readbacks() + } else { + Vec::new() + } + } + Some(dl) => { + let rem = dl.saturating_duration_since(std::time::Instant::now()); + let Some(mut g) = try_lock_giving_way(state_lock, &SUBMITS_WAITING, rem, is_global && submit_lock_first()) else { + return false; + }; + let _held = is_global.then(|| holding(Holder::Settle)); + if let Some(s) = g.as_mut().filter(|s| Arc::ptr_eq(&s.readbacks, rb)) { + s.land_finished_readbacks() + } else { + Vec::new() + } + } + }; + drop(excess); + true +} + /// Copies back that are done on the GPU, into the title's memory, and those whose title work /// is done (waiting for the copy): before a CPU read of memory the title's lists wrote. pub unsafe fn settle_readbacks() { if RB_PENDING.load(Ordering::Acquire) == 0 { return; } - let mut g = STATE.lock().unwrap(); - let _held = holding(Holder::Settle); - if let Some(s) = g.as_mut() { - s.drain_readbacks(Drain::TitleDone); - } + let Some(rb) = readbacks_arc() else { return }; + let _ = settle_readbacks_with(&STATE, &rb, Drain::TitleDone, 2000, None); } -/// `settle_readbacks` from a fence observation: the state's lock is only tried (for ~2 ms), as +/// `settle_readbacks` from a fence observation: the state's lock is only tried (for ~5 ms), as /// XCL may be waiting on a fence of its own with the lock held. pub unsafe fn settle_readbacks_try() { settle_readbacks_within(5); } /// `settle_readbacks` with the state's lock waited for `ms` ms at most (false: it was not had: -/// what is pending stays pending). A copy back whose title work is done is waited for 0.3 ms. +/// what is pending stays pending). A copy back whose title work is done is waited for 0.3 ms +/// outside all locks; if no job finished yet, `STATE` is not locked at all. pub unsafe fn settle_readbacks_within(ms: u64) -> bool { if RB_PENDING.load(Ordering::Acquire) == 0 { return true; } // (`XCL_LOOK_STATS=2`: the time a title's thread spends here when it looks at a fence) let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::FenceSettle)); - let Some(mut g) = try_lock_giving_way(&STATE, &SUBMITS_WAITING, std::time::Duration::from_millis(ms), submit_lock_first()) else { return false }; - let _held = holding(Holder::Settle); - if let Some(s) = g.as_mut() { - s.drain_readbacks_spin(Drain::TitleDone, 300); - } - true + let Some(rb) = readbacks_arc() else { return true }; + settle_readbacks_with(&STATE, &rb, Drain::TitleDone, 300, Some(ms)) } /// The thread that moves finished copies back into the title's memory, so it sees what its @@ -2675,23 +3041,41 @@ fn start_readback_thread() { STARTED.call_once(|| { let _ = std::thread::Builder::new().name("xcl-sparse-readback".into()).spawn(|| loop { std::thread::sleep(std::time::Duration::from_micros(500)); - // (`XCL_SUBMIT_LOCK_FIRST=1`: nothing to land, or a submit waits for the lock: not now) - if submit_lock_first() && (RB_PENDING.load(Ordering::Acquire) == 0 || SUBMITS_WAITING.load(Ordering::Acquire) > 0) { + if RB_PENDING.load(Ordering::Acquire) == 0 { continue; } - if let Ok(mut g) = STATE.try_lock() { - let _held = holding(Holder::ReadbackThread); - if let Some(s) = g.as_mut().filter(|s| !s.rb_jobs.is_empty() || !s.imm_jobs.is_empty()) { - unsafe { s.drain_readbacks(Drain::Finished) }; - } + // (`XCL_SUBMIT_LOCK_FIRST=1`: a submit waits for the lock: not now) + if submit_lock_first() && SUBMITS_WAITING.load(Ordering::Acquire) > 0 { + continue; + } + let Some(rb) = readbacks_arc() else { continue }; + if unsafe { !has_unpopped_finished_jobs(&rb) } { + continue; } + if submit_lock_first() && SUBMITS_WAITING.load(Ordering::Acquire) > 0 { + continue; + } + let excess = { + if let Ok(mut g) = STATE.try_lock() { + let _held = holding(Holder::ReadbackThread); + if let Some(s) = g.as_mut().filter(|s| Arc::ptr_eq(&s.readbacks, &rb)) { + unsafe { s.land_finished_readbacks() } + } else { + Vec::new() + } + } else { + Vec::new() + } + }; + drop(excess); }); }); } impl State { - /// `readback_after_execute` on this state - unsafe fn after_execute(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { + /// Snapshot mapped tiles and immediates under `&mut self` (`STATE`) for async readback, or + /// execute the rare synchronous `rbq.is_none()` fallback inline. + unsafe fn prepare_after_execute(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) -> (Option, Vec) { let s = self; let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); // immediates: stored by XCL when the lists are done. One that another write of these @@ -2712,7 +3096,7 @@ impl State { } } if filtered.is_empty() && imm.is_empty() { - return; + return (None, Vec::new()); } filtered.sort_unstable(); let mut merged: Vec<(usize, usize)> = Vec::with_capacity(filtered.len()); @@ -2726,29 +3110,56 @@ impl State { } } if s.rbq.is_some() { - // on this queue: [the title's lists] Signal(first, v) [the copies] Signal(second, v) - let key = queue.as_raw() as usize; - if !s.rb_queue_fences.contains_key(&key) { - let (Ok(a), Ok(b)) = (s.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE), s.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE)) else { return }; - s.rb_queue_fences.insert(key, (a, b, 0)); - } - let (fences, v) = { - let e = s.rb_queue_fences.get_mut(&key).expect("fences"); - e.2 += 1; - ((e.0.clone(), e.1.clone()), e.2) - }; - let _ = queue.Signal(&fences.0, v); - if !imm.is_empty() { - s.job_seq += 1; - s.imm_jobs.push_back(ImmJob { seq: s.job_seq, fence: fences.0.clone(), value: v, writes: imm }); - RB_PENDING.fetch_add(1, Ordering::Release); - RB_ASYNC.store(true, Ordering::Relaxed); - } - if !merged.is_empty() { - s.readback_async(queue, &merged, &fences, v); + let mut windows: Vec<(usize, ID3D12Resource)> = Vec::new(); + let mut win_slot: Vec = vec![usize::MAX; s.windows.len()]; + let mut batches: Vec> = Vec::new(); + let mut used = 0usize; + for &(a, n) in &merged { + let mut at = 0usize; + while at < n { + let cur = a + at; + let tile = cur & !(TILE - 1); + let Some(wi) = s.window_index(cur) else { break }; + let to_tile_end = (tile + TILE) - cur; + // (a tile with no video memory has nothing to copy back, like one not mapped) + let Some(gen) = s.mapped.get(&tile).filter(|e| e.pool != LAZY).map(|e| e.gen) else { + at += (n - at).min(to_tile_end); + continue; + }; + if batches.is_empty() || used == READBACK_STAGING { + batches.push(Vec::new()); + used = 0; + } + let lwi = if win_slot[wi] != usize::MAX { + win_slot[wi] + } else { + let idx = windows.len(); + windows.push((s.windows[wi].0, s.windows[wi].1.clone())); + win_slot[wi] = idx; + idx + }; + let to_win_end = (s.windows[wi].0 + crate::gpu::uma::WINDOW) - cur; + let chunk = (n - at).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); + batches.last_mut().expect("batch").push(RbChunk { win: lwi, va: cur, len: chunk, gen }); + used += chunk; + at += chunk; + } } - start_readback_thread(); - return; + if imm.is_empty() && batches.is_empty() { + return (None, Vec::new()); + } + let submitting = SubmittingGuard::begin(&s.readbacks); + return ( + Some(AsyncReadbackPlan { + rb_submit: Arc::clone(&s.rb_submit), + readbacks: Arc::clone(&s.readbacks), + windows, + batches, + imm, + submitting, + }), + Vec::new(), + ); } s.rb_value += 1; let v = s.rb_value; @@ -2756,7 +3167,17 @@ impl State { let _ = s.queue.Wait(&s.rb_fence, v); super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); } - s.readback_ranges(&merged); + (None, s.readback_ranges(&merged)) + } + + /// `readback_after_execute` on a standalone `State` (tests only). + #[cfg(test)] + unsafe fn after_execute(&mut self, queue: &ID3D12CommandQueue, ranges: &[(usize, usize)], imms: &[(usize, u64, u8)]) { + let (plan, excess) = self.prepare_after_execute(queue, ranges, imms); + drop(excess); + if let Some(plan) = plan { + submit_async_readback(queue, plan); + } } } @@ -2768,44 +3189,52 @@ pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; } - let mut g = lock_state(); - let _held = holding(Holder::CpuRead); - let Some(s) = g.as_mut() else { return }; - if s.window_index(va).is_none() { - return; - } - let zeroed = zero_runs(std::mem::take(&mut s.to_zero)); - if !zeroed.is_empty() { - for &(a, n) in &zeroed { - s.clear_sent_range(a, n); + if RB_PENDING.load(Ordering::Acquire) != 0 { + if let Some(rb) = readbacks_arc() { + wait_and_check_ready(&rb, Drain::TitleDone, 2000, None); } - s.upload_zeros(&zeroed); } - // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` - let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); - let mut pg = va & !(PAGE - 1); - let end = va + len; - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = (t + TILE).min(end); - if let Some(entry) = s.mapped.get_mut(&t) { - let cpu = entry.cpu(t); - let mut p = pg; - while p < tile_end { - let idx = (p - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts((cpu + (p - t)) as *const u8, PAGE); - scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); + let excess = { + let mut g = lock_state(); + let _held = holding(Holder::CpuRead); + let Some(s) = g.as_mut() else { return }; + if s.window_index(va).is_none() { + return; + } + let zeroed = zero_runs(std::mem::take(&mut s.to_zero)); + if !zeroed.is_empty() { + for &(a, n) in &zeroed { + s.clear_sent_range(a, n); + } + s.upload_zeros(&zeroed); + } + // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` + let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); + let mut pg = va & !(PAGE - 1); + let end = va + len; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = s.mapped.get_mut(&t) { + let cpu = entry.cpu(t); + let mut p = pg; + while p < tile_end { + let idx = (p - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts((cpu + (p - t)) as *const u8, PAGE); + scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); + } + p += PAGE; } - p += PAGE; } + pg = tile_end; } - pg = tile_end; - } - if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); - } - s.readback_ranges(&[(va, len)]); + if !dirty_runs.is_empty() { + s.upload_dirty(&dirty_runs); + } + s.readback_ranges(&[(va, len)]) + }; + drop(excess); } /// Submits waiting for the state's lock. A thread that takes it again and again – a title mapping @@ -4337,9 +4766,11 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: LOCK_SPLIT.add(LS_ALL, waited); HELD.add(HOLDERS + behind, (t_got - t0).as_micros() as u64); } - let wait = s.before_execute_on(queue, dirty, page); + let (wait, excess) = s.before_execute_on(queue, dirty, page); drop(_held); drop(g); + // (recycled copy-back jobs past the pool's cap drop outside all locks) + drop(excess); if let Some((fence, value, mappings)) = wait { let q = queue.as_raw() as usize; if !(mappings && cpu_waited_for_mappings(&fence, value, "sparse uploads and tile mappings")) { @@ -4617,8 +5048,8 @@ fn lock_split_line(x: &[u64; 11]) -> String { impl State { /// `before_execute` with the state locked; returns `(fence, value, has_new_mappings)` to wait - /// for after releasing the lock. - unsafe fn before_execute_on(&mut self, queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) -> Option<(ID3D12Fence, u64, bool)> { + /// for after releasing the lock, and excess recycled `RbJob`s to drop outside `STATE`. + unsafe fn before_execute_on(&mut self, queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) -> (Option<(ID3D12Fence, u64, bool)>, Vec) { let t0 = std::time::Instant::now(); let s = self; // (`XCL_LOOK_STATS=2`: the time after each step, and the work counted so far) @@ -4636,7 +5067,7 @@ impl State { }); // (copies back done before the tiles change below: a page that stops being a hole there // would take what the GPU had in it) - s.drain_readbacks(Drain::Finished); + let excess = s.land_finished_readbacks(); let t_back = stamp(); // tiles whose page the queue's page mappings changed (after the copies back: one for the // old link lands nowhere), tiles asked to show CPU views, and the CPU writes that change @@ -4837,13 +5268,14 @@ impl State { } let q = queue.as_raw() as usize; let waited_before = s.waited.get(&q).copied().unwrap_or(0); - if s.value > 0 && waited_before < s.value { + let wait = if s.value > 0 && waited_before < s.value { let mappings = s.mapped_value > waited_before; s.waited.insert(q, s.value); Some((s.fence.clone(), s.value, mappings)) } else { None - } + }; + (wait, excess) } } @@ -5344,6 +5776,8 @@ mod tests { let rbq_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("readback queue"); let rbq_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("readback fence"); + let rb_readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), Some(rbq_fence.clone()))); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); let mut s = State { dev: dev.clone(), queue, @@ -5352,13 +5786,10 @@ mod tests { event, rb_fence, rb_value: 0, - rb_queue_fences: FxHashMap::default(), rbq: Some((rbq_queue, rbq_fence)), rbq_value: 0, - rb_jobs: VecDeque::new(), - rb_pool: Vec::new(), - imm_jobs: VecDeque::new(), - job_seq: 0, + readbacks: rb_readbacks, + rb_submit, windows: vec![(base, reserved.clone())], pools: Vec::new(), free: FreePools::new(), @@ -5461,8 +5892,8 @@ mod tests { for i in 0..64u32 { assert_eq!(*(base as *const u32).add(i as usize), 0xC0DE_0000 | i, "dword {i} after the copy back"); } - assert!(s.rb_jobs.is_empty(), "the copy back was consumed"); - assert_eq!(s.rb_pool.len(), 1, "its buffer is kept for the next one"); + assert!(s.readbacks.lock().unwrap().rb_jobs.is_empty(), "the copy back was consumed"); + assert_eq!(s.readbacks.lock().unwrap().rb_pool.len(), 1, "its buffer is kept for the next one"); drop(s); VirtualFree(base as *mut c_void, 0, MEM_RELEASE); } @@ -5678,6 +6109,8 @@ mod tests { let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); rb_list.Close().expect("rb_list close"); + let readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), None)); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); let mut s = State { dev, queue, @@ -5686,13 +6119,10 @@ mod tests { event, rb_fence, rb_value: 0, - rb_queue_fences: FxHashMap::default(), rbq: None, rbq_value: 0, - rb_jobs: VecDeque::new(), - rb_pool: Vec::new(), - imm_jobs: VecDeque::new(), - job_seq: 0, + readbacks, + rb_submit, windows: Vec::new(), pools: Vec::new(), free: FreePools::new(), @@ -5918,6 +6348,8 @@ mod tests { let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); rb_list.Close().expect("rb_list close"); + let readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), None)); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); let mut s = State { dev, queue, @@ -5926,13 +6358,10 @@ mod tests { event, rb_fence, rb_value: 0, - rb_queue_fences: FxHashMap::default(), rbq: None, rbq_value: 0, - rb_jobs: VecDeque::new(), - rb_pool: Vec::new(), - imm_jobs: VecDeque::new(), - job_seq: 0, + readbacks, + rb_submit, windows: vec![(base, reserved)], pools: Vec::new(), free: FreePools::new(), @@ -6047,6 +6476,8 @@ mod tests { let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); rb_list.Close().expect("rb_list close"); + let readbacks = Arc::new(SharedReadbacks::new(rb_fence.clone(), None)); + let rb_submit = Arc::new(Mutex::new(RbSubmit::new(dev.clone()))); let mut s = State { dev, queue, @@ -6055,13 +6486,10 @@ mod tests { event, rb_fence, rb_value: 0, - rb_queue_fences: FxHashMap::default(), rbq: None, rbq_value: 0, - rb_jobs: VecDeque::new(), - rb_pool: Vec::new(), - imm_jobs: VecDeque::new(), - job_seq: 0, + readbacks, + rb_submit, windows: vec![(base, reserved)], pools: Vec::new(), free: FreePools::new(), @@ -6829,7 +7257,7 @@ mod tests { /// A submit of the title, with the CPU pages `dirty` written since the last. unsafe fn submit(&mut self, dirty: &[usize]) { let title = self.title.clone(); - self.s.before_execute_on(&title, dirty, PAGE); + let _ = self.s.before_execute_on(&title, dirty, PAGE); } /// `len` bytes at `off` of `res` as the GPU has them, after what was sent to it. @@ -7688,9 +8116,9 @@ mod tests { if v.s.rbq.is_some() { let title = v.title.clone(); v.s.after_execute(&title, &[], &[(w + 0x100, 0x77, 8)]); - assert_eq!(v.s.imm_jobs.back().map(|j| j.writes[0].3), Some(v.s.mapped[&w].gen)); + assert_eq!(v.s.readbacks.lock().unwrap().imm_jobs.back().map(|j| j.writes[0].3), Some(v.s.mapped[&w].gen)); let t = std::time::Instant::now(); - while !v.s.imm_jobs.is_empty() { + while !v.s.readbacks.lock().unwrap().imm_jobs.is_empty() { v.s.drain_readbacks(Drain::TitleDone); assert!(t.elapsed() < std::time::Duration::from_secs(5), "the immediate did not land"); std::thread::sleep(std::time::Duration::from_millis(1)); @@ -8140,20 +8568,488 @@ mod tests { job.copies.push((w, 0, TILE, v.s.mapped[&w].gen)); let fence = || v.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).expect("fence"); job.fences = Some((fence(), fence())); - v.s.job_seq += 1; - job.seq = v.s.job_seq; - v.s.rb_jobs.push_back(job); + { + let mut rq = v.s.readbacks.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } RB_PENDING.fetch_add(1, Ordering::Release); // a page committed and written in part since let p = c + 9 * PAGE; assert!(!VirtualAlloc(p as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); *(p as *mut u64) = 0x600D; v.submit(&[p]); - assert!(v.s.rb_jobs.is_empty(), "the copy landed"); + assert!(v.s.readbacks.lock().unwrap().rb_jobs.is_empty(), "the copy landed"); assert_eq!(*((c + 0x40) as *const u8), 0xAB, "in the pages committed then"); assert_eq!(v.s.mapped[&w].holes, 0xFF00 & !(1 << 9)); assert_eq!(*(p as *const u64), 0x600D); assert!(std::slice::from_raw_parts((p + 8) as *const u8, PAGE - 8).iter().all(|&b| b == 0), "not in the page committed since"); } } + + struct SendQueue(ID3D12CommandQueue); + unsafe impl Send for SendQueue {} + + struct IsolatedAsyncState { + dev: ID3D12Device, + base: usize, + gen: u32, + state: Arc>>, + rb: Arc, + rb_submit: Arc>, + } + + impl IsolatedAsyncState { + unsafe fn new() -> Self { + let (base, mut s) = test_state_with_reserved(1); + assert!(!VirtualAlloc(base as *const c_void, TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + s.commit_range(base, TILE); + s.flush_pending(); + std::ptr::write_bytes(base as *mut u8, 0, TILE); + let dev = s.dev.clone(); + let gen = s.mapped[&base].gen; + let rb = Arc::clone(&s.readbacks); + let rb_submit = Arc::clone(&s.rb_submit); + assert!(s.rbq.is_some(), "async readback queue required"); + Self { dev, base, gen, state: Arc::new(Mutex::new(Some(s))), rb, rb_submit } + } + + unsafe fn make_job(&self, byte: u8, len: usize, title_f: ID3D12Fence, done_f: ID3D12Fence, rb_v: u64, done_v: u64) -> RbJob { + let mut job = take_or_alloc_rb_job(&self.dev, &self.rb, len, D3D12_COMMAND_LIST_TYPE_DIRECT).expect("readback job"); + std::ptr::write_bytes(job.ptr, byte, len); + job.copies.clear(); + job.copies.push((self.base, 0, len, self.gen)); + job.rb_v = rb_v; + job.done_v = done_v; + job.fences = Some((title_f, done_f)); + job + } + } + + impl Drop for IsolatedAsyncState { + fn drop(&mut self) { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + let mut old = self.state.lock().unwrap().take(); + if let Some(s) = old.as_mut() { + unsafe { + s.wait_for(s.value); + } + } + drop(old); + unsafe { + let _ = VirtualFree(self.base as *mut c_void, 0, MEM_RELEASE); + } + } + } + + /// `settle_readbacks_with` spins on a title-done / copy-pending fence completely outside + /// `STATE`: another thread acquires `STATE` immediately throughout the GPU copy spin. + #[test] + fn settle_readbacks_waits_for_copy_fence_without_holding_state() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title_f: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("title fence"); + let done_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("done fence"); + let _unblock = SignalOnDrop(done_f.clone(), 1); + let mut job = iso.make_job(0xAB, 256, title_f, done_f.clone(), 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } + RB_PENDING.fetch_add(1, Ordering::Release); + + let state_c = Arc::clone(&iso.state); + let rb_c = Arc::clone(&iso.rb); + let settled = std::thread::spawn(move || settle_readbacks_with(&state_c, &rb_c, Drain::TitleDone, 200_000, None)); + + // Give the settler a moment to enter the fence spin loop. + std::thread::sleep(std::time::Duration::from_millis(5)); + for _ in 0..10 { + let g = iso.state.try_lock(); + assert!(g.is_ok(), "STATE was held during GPU copy fence spin"); + drop(g); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + done_f.Signal(1).expect("signal copy done"); + assert!(settled.join().unwrap()); + assert_eq!(*(iso.base as *const u8), 0xAB, "copy landed after done_f signalled"); + assert!(iso.rb.lock().unwrap().rb_jobs.is_empty()); + } + } + + /// When pending jobs have not finished on the GPU yet, `settle_readbacks_with` returns + /// promptly without acquiring `STATE` even while another thread holds `STATE`. + #[test] + fn settle_readbacks_skips_state_lock_when_no_job_finished() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("title fence"); + let done_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("done fence"); + let imm_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("imm fence"); + let mut job = iso.make_job(0xCD, 256, title_f, done_f, 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + rq.job_seq += 1; + let seq = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq, fence: imm_f, value: 1, writes: vec![(iso.base + 0x100, 0x99, 8, iso.gen)] }); + } + RB_PENDING.fetch_add(2, Ordering::Release); + + let held = iso.state.lock().unwrap(); + let state_c = Arc::clone(&iso.state); + let rb_c = Arc::clone(&iso.rb); + let (tx, rx) = std::sync::mpsc::channel(); + let t0 = std::time::Instant::now(); + let worker = std::thread::spawn(move || { + let ok = settle_readbacks_with(&state_c, &rb_c, Drain::TitleDone, 300, Some(5000)); + let _ = tx.send(ok); + }); + let outcome = rx.recv_timeout(std::time::Duration::from_millis(500)); + let took = t0.elapsed(); + drop(held); + worker.join().unwrap(); + + let ok = outcome.expect("settle blocked on held STATE despite no finished jobs"); + assert!(ok, "unfinished jobs should return true without blocking on STATE"); + assert!(took < std::time::Duration::from_millis(500), "settle waited {took:?} on held STATE despite no finished jobs"); + assert_eq!(iso.rb.lock().unwrap().rb_jobs.len(), 1); + assert_eq!(iso.rb.lock().unwrap().imm_jobs.len(), 1); + } + } + + /// Concurrent settlers racing on overlapping finished `imm_jobs` and `rb_jobs` land every job + /// in strict ascending `seq` order and never overwrite a newer `seq` with an older one. + #[test] + fn concurrent_settle_lands_jobs_in_strict_seq_order() { + unsafe { + let iso = IsolatedAsyncState::new(); + let done: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("done fence"); + for round in 0..16u64 { + *(iso.base as *mut u64) = 0; + let v1 = 0x1111_0000_0000_0000 | round; + let v3 = 0x3333_0000_0000_0000 | round; + let v5 = 0x5555_0000_0000_0000 | round; + let mut j2 = iso.make_job(0x22, 8, done.clone(), done.clone(), 1, 1); + let mut j4 = iso.make_job(0x44, 8, done.clone(), done.clone(), 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + let s1 = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq: s1, fence: done.clone(), value: 1, writes: vec![(iso.base, v1, 8, iso.gen)] }); + rq.job_seq += 1; + j2.seq = rq.job_seq; + rq.rb_jobs.push_back(j2); + rq.job_seq += 1; + let s3 = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq: s3, fence: done.clone(), value: 1, writes: vec![(iso.base, v3, 8, iso.gen)] }); + rq.job_seq += 1; + j4.seq = rq.job_seq; + rq.rb_jobs.push_back(j4); + rq.job_seq += 1; + let s5 = rq.job_seq; + rq.imm_jobs.push_back(ImmJob { seq: s5, fence: done.clone(), value: 1, writes: vec![(iso.base, v5, 8, iso.gen)] }); + } + RB_PENDING.fetch_add(5, Ordering::Release); + + let bar = Arc::new(std::sync::Barrier::new(4)); + let handles: Vec<_> = (0..4) + .map(|_| { + let s = Arc::clone(&iso.state); + let r = Arc::clone(&iso.rb); + let b = Arc::clone(&bar); + std::thread::spawn(move || { + b.wait(); + assert!(settle_readbacks_with(&s, &r, Drain::TitleDone, 300, None)); + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + assert_eq!(*(iso.base as *const u64), v5, "round {round}: final seq must win"); + let rq = iso.rb.lock().unwrap(); + assert!(rq.rb_jobs.is_empty() && rq.imm_jobs.is_empty() && rq.landing == 0); + } + + // In-flight landing visibility check: `landing > 0` forces `wait_and_check_ready` to + // synchronize on `STATE` even after the queues are empty, while the background thread + // check `has_unpopped_finished_jobs` stays false. + iso.rb.lock().unwrap().landing = 1; + assert!(wait_and_check_ready(&iso.rb, Drain::Finished, 0, None) == ReadyCheck::LandNow); + assert!(!has_unpopped_finished_jobs(&iso.rb)); + iso.rb.lock().unwrap().landing = 0; + } + } + + /// `readback_after_execute_with` releases `STATE` before acquiring `RB_SUBMIT` and recording + /// D3D12 copy commands, and `land_finished_readbacks` returns excess `RbJob`s beyond the 32-job + /// pool cap so callers drop them outside all locks. + #[test] + fn readback_after_execute_records_outside_state_lock_and_drops_excess_outside_locks() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title: ID3D12CommandQueue = iso.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let mut up: Option = None; + let mut d = buffer_desc(256); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + iso.dev + .CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up) + .expect("upload buffer"); + let up = up.expect("upload buffer"); + let mut p: *mut c_void = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("Map"); + for i in 0..64u32 { + *(p as *mut u32).add(i as usize) = 0xC0DE_0000 | i; + } + let win_res = iso.state.lock().unwrap().as_ref().unwrap().windows[0].1.clone(); + let alloc: ID3D12CommandAllocator = iso.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = iso.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&win_res, 0, &up, 0, 256); + list.Close().expect("close"); + { + let g = iso.state.lock().unwrap(); + let s = g.as_ref().unwrap(); + title.Wait(&s.fence, s.value).expect("wait mapping"); + } + title.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + + // Hold `rb_submit` before spawning `readback_after_execute_with`: the worker must finish + // its `STATE` snapshot (which takes the submitting token, `SubmittingGuard`), release + // `STATE`, and park on `rb_submit` while the main thread acquires `STATE` cleanly. + let sub_held = iso.rb_submit.lock().unwrap(); + let state_c = Arc::clone(&iso.state); + let q_send = SendQueue(title.clone()); + let base = iso.base; + let worker = std::thread::spawn(move || { + readback_after_execute_with(&state_c, &q_send.0, &[(base, 256)], &[(base + 0x800, 0xCAFE_BABE_1234_5678, 8)]); + }); + let t0 = std::time::Instant::now(); + loop { + // (in the code's order: `STATE`, then the readback queue) + let state = iso.state.lock().unwrap(); + let snapshot_taken = iso.rb.lock().unwrap().submitting > 0; + drop(state); + if snapshot_taken { + break; + } + assert!(t0.elapsed() < std::time::Duration::from_secs(5), "readback_after_execute_with did not release STATE while rb_submit was held"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + drop(sub_held); + worker.join().unwrap(); + + // Settle until the submitted copy back and immediate both land. + let t1 = std::time::Instant::now(); + loop { + if std::ptr::read_volatile(base as *const u32) == 0xC0DE_0000 && std::ptr::read_volatile((base + 0x800) as *const u64) == 0xCAFE_BABE_1234_5678 { + break; + } + assert!(settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 2000, None)); + assert!(t1.elapsed() < std::time::Duration::from_secs(5), "async readback did not land"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(*((base + 0x800) as *const u64), 0xCAFE_BABE_1234_5678); + + // Part B: excess RbJobs above pool cap (32) are returned to be dropped outside all locks. + let done: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("done"); + let mut extra_pool = std::mem::take(&mut iso.rb.lock().unwrap().rb_pool); + while extra_pool.len() < 32 { + extra_pool.push(take_or_alloc_rb_job(&iso.dev, &iso.rb, 64 << 10, D3D12_COMMAND_LIST_TYPE_DIRECT).expect("pool job")); + } + let mut f1 = iso.make_job(0x77, 64, done.clone(), done.clone(), 1, 1); + let mut f2 = iso.make_job(0x88, 64, done.clone(), done.clone(), 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.rb_pool.extend(extra_pool); + assert_eq!(rq.rb_pool.len(), 32); + rq.job_seq += 1; + f1.seq = rq.job_seq; + rq.rb_jobs.push_back(f1); + rq.job_seq += 1; + f2.seq = rq.job_seq; + rq.rb_jobs.push_back(f2); + } + RB_PENDING.fetch_add(2, Ordering::Release); + + let excess = { + let mut g = iso.state.lock().unwrap(); + g.as_mut().unwrap().land_finished_readbacks() + }; + assert_eq!(iso.rb.lock().unwrap().rb_pool.len(), 32); + assert_eq!(excess.len(), 2, "excess RbJobs must be returned for drop outside STATE and READBACKS"); + drop(excess); + } + } + + /// Contention micro-bench: repeated `STATE` acquisitions stay unblocked while another thread + /// continuously spins in `settle_readbacks_with` on a title-done / copy-pending fence. + #[test] + fn state_lock_latency_stays_unblocked_under_readback_spin_contention() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title_f: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("title fence"); + let done_f: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("done fence"); + let _unblock = SignalOnDrop(done_f.clone(), 1); + let mut job = iso.make_job(0x5A, 256, title_f, done_f.clone(), 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } + RB_PENDING.fetch_add(1, Ordering::Release); + + let stop = Arc::new(AtomicBool::new(false)); + let state_c = Arc::clone(&iso.state); + let rb_c = Arc::clone(&iso.rb); + let stop_c = Arc::clone(&stop); + let spinner = std::thread::spawn(move || { + let mut spins = 0u32; + while !stop_c.load(Ordering::Acquire) { + assert!(settle_readbacks_with(&state_c, &rb_c, Drain::TitleDone, 2000, None)); + spins += 1; + } + spins + }); + + std::thread::sleep(std::time::Duration::from_millis(5)); + let mut waits_us = Vec::with_capacity(50); + for _ in 0..50 { + let t0 = std::time::Instant::now(); + let g = iso.state.lock().unwrap(); + waits_us.push(t0.elapsed().as_micros() as u64); + drop(g); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + stop.store(true, Ordering::Release); + done_f.Signal(1).expect("signal done"); + let spins = spinner.join().unwrap(); + assert!(settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 2000, None)); + + waits_us.sort_unstable(); + let p50 = waits_us[waits_us.len() / 2]; + let p99 = waits_us[(waits_us.len() * 99) / 100]; + let max = *waits_us.last().unwrap(); + eprintln!("sparse lock-split contention bench ({spins} spin calls): STATE lock wait p50={p50} us, p99={p99} us, max={max} us"); + assert!(spins >= 5, "spinner ran too few iterations ({spins})"); + assert!(p99 < 1000, "STATE lock p99={p99} us exceeded 1000 us under readback spin contention"); + } + } + + /// An async readback plan prepared under `STATE` remains visible to concurrent settling + /// callers via `ReadbackQueue::submitting` until `submit_async_readback` publishes or cancels + /// it: even when an unrelated unfinished readback is already queued, a fence observer waits + /// within its budget instead of returning early with a stale CPU value, returns `false` if its + /// budget expires before publication, and wakes immediately on plan cancellation. + #[test] + fn settle_waits_for_in_flight_plan_publication_and_handles_cancellation() { + unsafe { + let iso = IsolatedAsyncState::new(); + let title_q: ID3D12CommandQueue = iso.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let dst = iso.base + 0x800; + std::ptr::write_volatile(dst as *mut u64, 0x1111_2222_3333_4444); + + // Push an unrelated GPU-unfinished job first so `RB_PENDING > 0` already holds. + let unfin_title: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("unfin title"); + let unfin_done: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("unfin done"); + let mut unfin_job = iso.make_job(0xEE, 64, unfin_title, unfin_done, 1, 1); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + unfin_job.seq = rq.job_seq; + rq.rb_jobs.push_back(unfin_job); + } + RB_PENDING.fetch_add(1, Ordering::Release); + + // Submitter prepares an immediate write under `STATE`, drops `STATE`, signals the + // title fence, waits until that GPU fence completes, then pauses right before + // publishing into `ReadbackQueue`. + let (paused_tx, paused_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let state_c = Arc::clone(&iso.state); + let q_send = SendQueue(title_q.clone()); + let submitter = std::thread::spawn(move || { + let (plan, excess) = { + let mut g = state_c.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.note_queue(&q_send.0); + s.prepare_after_execute(&q_send.0, &[], &[(dst, 0xDEAD_BEEF_CAFE_BABE, 8)]) + }; + drop(excess); + let plan = plan.expect("immediate write must produce an async readback plan"); + let hook = move |title_f: &ID3D12Fence, v: u64| { + let t0 = std::time::Instant::now(); + while crate::hle::d3d12x::real::fence_completed(title_f) < v { + assert!(t0.elapsed() < std::time::Duration::from_secs(5), "title fence did not complete"); + std::thread::yield_now(); + } + let _ = paused_tx.send(()); + let _ = release_rx.recv(); + }; + submit_async_readback_inner(&q_send.0, plan, Some(&hook)); + }); + + paused_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("submitter did not reach publication pause"); + assert_eq!(iso.rb.lock().unwrap().submitting, 1); + assert!(iso.state.try_lock().is_ok(), "STATE must already be released during publication pause"); + + // Bounded settle that expires while publication is still paused returns `false` + // instead of claiming success before the immediate is published. + assert!(!settle_readbacks_with(&iso.state, &iso.rb, Drain::TitleDone, 300, Some(20))); + assert_eq!(std::ptr::read_volatile(dst as *const u64), 0x1111_2222_3333_4444); + + // A fence observer with sufficient budget waits for publication, then lands the + // completed immediate before reporting success. + let (obs_tx, obs_rx) = std::sync::mpsc::channel(); + let obs_state = Arc::clone(&iso.state); + let obs_rb = Arc::clone(&iso.rb); + let observer = std::thread::spawn(move || { + let ok = settle_readbacks_with(&obs_state, &obs_rb, Drain::TitleDone, 300, Some(2000)); + let _ = obs_tx.send(ok); + }); + assert!( + obs_rx.recv_timeout(std::time::Duration::from_millis(25)).is_err(), + "observer returned early before paused plan published" + ); + release_tx.send(()).expect("release publication"); + let ok = obs_rx.recv_timeout(std::time::Duration::from_secs(2)).expect("observer did not wake after publication"); + assert!(ok, "observer should settle and return true once plan publishes"); + assert_eq!( + std::ptr::read_volatile(dst as *const u64), + 0xDEAD_BEEF_CAFE_BABE, + "CPU destination must hold the immediate value when observer returns" + ); + observer.join().unwrap(); + submitter.join().unwrap(); + assert_eq!(iso.rb.lock().unwrap().submitting, 0); + + // Plan cancellation (e.g. bail on fence allocation failure): dropping `AsyncReadbackPlan` + // decrements `submitting`, balances `RB_PENDING`, and wakes waiting observers cleanly. + let (cancelled_plan, excess) = { + let mut g = iso.state.lock().unwrap(); + g.as_mut().unwrap().prepare_after_execute(&title_q, &[], &[(dst, 0x5555, 8)]) + }; + drop(excess); + let cancelled_plan = cancelled_plan.expect("plan for cancellation test"); + assert_eq!(iso.rb.lock().unwrap().submitting, 1); + let (w_tx, w_rx) = std::sync::mpsc::channel(); + let rb_c = Arc::clone(&iso.rb); + let waiter = std::thread::spawn(move || { + let r = wait_and_check_ready(&rb_c, Drain::TitleDone, 0, Some(std::time::Instant::now() + std::time::Duration::from_secs(2))); + let _ = w_tx.send(r); + }); + std::thread::sleep(std::time::Duration::from_millis(10)); + drop(cancelled_plan); + let ready = w_rx.recv_timeout(std::time::Duration::from_secs(1)).expect("waiter did not wake on plan drop"); + waiter.join().unwrap(); + assert!(ready == ReadyCheck::NothingReady); + assert_eq!(iso.rb.lock().unwrap().submitting, 0); + } + } } From f2f02bd0db0de6700f2b8d5a6d670f3d197e85c5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:39:33 +0100 Subject: [PATCH 031/175] D3D12.X: omit sparse tiles with no committed page from write-watch ranges Ports the sparse half of upstream PR #2754: 60bc047f ("omit VRAM-only sparse tiles and GPU-written textures from write-watch ranges") and its follow-up 891c97a5 ("invalidate sparse watch ranges when commit_range unmasks a VRAM-only tile"). A tile of a sparse window whose 16 pages are all holes (holes == 0xFFFF) has no page the CPU can write: the title has not committed one there. The upload before a submit already skips hole pages, so watching such a tile only had the looks for CPU writes walk memory nothing could have written. In this tree such tiles stay in `mapped` for a buffer placed over reserved memory (`buffer_tiles` maps its tiles with the holes Windows reports), and for a moment in each commit (`ensure_listed`, a tile over a CPU view committed at its own address). `State::runs` (what `mapped_ranges` returns for the window's own tiles) now holds only tiles with a page committed: `ensure_mapped` and `ensure_listed` leave an all-holes tile out, and `commit_range` clears holes through `unmask_committed_holes`, which puts a tile that had none committed into `runs` and bumps MAPPED_GEN, so the next submit makes its watched ranges again (`watch_key`). Write-watch bits outside the watched ranges are never reset, so what the CPU writes after the commit is found by the next look; `committed` also makes the blocks hot (`mark_hot`). A tile that becomes all holes on a decommit already left `mapped` and `runs` (`decommit_tiles`). Adapted, not cherry-picked: upstream rebuilds its runs from all of `mapped` when they are asked for and filters there; this tree keeps `runs` up to date incrementally (a retail title has ~150,000 tiles), so the filter sits where tiles are listed and committed. The two upstream commits are one here: with only the first, a commit on an all-holes tile would never be watched. Upstream's lazy VEH commit queue (`drain_lazy_commits`, `alloc_vram_only`) does not exist in this tree, so that part does not apply: holes are only cleared by `commit_range`. Ranges under WATCH_GAP (64 MiB) apart are still scanned as one, so this shrinks the looks only where the tiles left out open such a gap. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/sparse.rs | 135 +++++++++++++++++++++------- 1 file changed, 101 insertions(+), 34 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 57af6ced36..f866cbca39 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -823,7 +823,9 @@ struct State { /// the fence value of the last `signal` that came after tile mappings mapped_value: u64, /// `mapped` as runs of neighbouring tiles (start -> end), kept with it: sorted out of all of - /// them again (a retail title has 150,000) for each look behind a commit + /// them again (a retail title has 150,000) for each look behind a commit. A tile with no page + /// committed (all holes: a placed buffer's over reserved memory) is left out – the CPU cannot + /// write there – until a commit clears a hole of it (`unmask_committed_holes`) runs: BTreeMap, /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) scratch_runs: Vec<(usize, usize)>, @@ -1264,10 +1266,12 @@ fn early_remove(early: &mut BTreeMap, a: usize, b: usize) { } } } -/// generation counter incremented whenever the set of mapped tiles changes (for watch_ranges cache) +/// generation counter incremented whenever the set of mapped tiles changes, or a tile with no page +/// committed gets one (for watch_ranges cache) static MAPPED_GEN: AtomicU64 = AtomicU64::new(0); -/// Generation counter of `mapped_ranges()` (changes only when tiles are mapped or unmapped). +/// Generation counter of `mapped_ranges()` (changes only when tiles are mapped or unmapped, or +/// become writable by the CPU). pub fn mapped_gen() -> u64 { MAPPED_GEN.load(Ordering::Acquire) } @@ -1741,8 +1745,9 @@ impl State { } /// `ensure_mapped` for a commit with `lazy_commits`: the tiles of `[a, a + n)` are listed - /// (watched, scanned, their holes kept) with no video memory (`LAZY`). A tile still mapped - /// from before (parked, or kept for a buffer) is taken back as it is. + /// (watched once the commit clears their holes, scanned, their holes kept) with no video + /// memory (`LAZY`). A tile still mapped from before (parked, or kept for a buffer) is taken + /// back as it is. unsafe fn ensure_listed(&mut self, a: usize, n: usize) { let end = a.saturating_add(n); let mut t = a & !(TILE - 1); @@ -1753,7 +1758,6 @@ impl State { self.ensure_mapped(t, TILE, |_| 0xFFFF); } else { self.mapped.insert(t, TileEntry::with_holes(LAZY, 0xFFFF)); - early_add(&mut self.runs, t, t + TILE); new = true; } } @@ -1828,8 +1832,8 @@ impl State { } /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_holes` supplies - /// the initial 16-bit hole mask for each newly mapped 64 KiB tile. Tiles over a CPU view - /// (`mirror_src`) are left to `new_mirror`. + /// the initial 16-bit hole mask for each newly mapped 64 KiB tile (one with all holes is not + /// watched, `runs`). Tiles over a CPU view (`mirror_src`) are left to `new_mirror`. unsafe fn ensure_mapped(&mut self, a: usize, n: usize, mut initial_holes: impl FnMut(usize) -> u16) { if n == 0 { return; @@ -1843,14 +1847,20 @@ impl State { if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() { // still mapped there: no new mapping, what it held is cleared if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) { - self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); - early_add(&mut self.runs, t, t + TILE); + let holes = initial_holes(t); + self.mapped.insert(t, TileEntry::with_holes(tile, holes)); + if holes != 0xFFFF { + early_add(&mut self.runs, t, t + TILE); + } self.to_zero.insert((t, TILE)); unparked = true; } else { let Some((tile, reused)) = self.take_tile() else { break }; - self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); - early_add(&mut self.runs, t, t + TILE); + let holes = initial_holes(t); + self.mapped.insert(t, TileEntry::with_holes(tile, holes)); + if holes != 0xFFFF { + early_add(&mut self.runs, t, t + TILE); + } if reused { self.to_zero.insert((t, TILE)); } @@ -3430,6 +3440,41 @@ pub fn send_pending() { } } +/// The pages of `[a, a + n)` committed: their hole bits cleared in the tiles of `mapped` there. A +/// tile of the window's own that had no page committed (all holes, so not in `runs`) can be written +/// by the CPU from now on: it joins `runs`, and `MAPPED_GEN` goes up so the watched ranges are +/// made again (true). +fn unmask_committed_holes(mapped: &mut FxHashMap, runs: &mut BTreeMap, a: usize, n: usize) -> bool { + let mut pg = a & !(PAGE - 1); + let end = a.saturating_add(n); + let mut unmasked = false; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = t.saturating_add(TILE).min(end); + if let Some(entry) = mapped.get_mut(&t) { + let was_all_holes = entry.holes == 0xFFFF; + let mut p = pg; + while p < tile_end { + entry.holes &= !(1u16 << ((p - t) / PAGE)); + p += PAGE; + } + // (a tile over a CPU view is never in `runs`: its own address is not the CPU's) + if was_all_holes && entry.holes != 0xFFFF && entry.src == 0 { + early_add(runs, t, t + TILE); + unmasked = true; + } + } + if tile_end <= pg { + break; + } + pg = tile_end; + } + if unmasked { + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + unmasked +} + impl State { /// `committed` with the state locked unsafe fn commit_range(&mut self, a: usize, n: usize) { @@ -3440,11 +3485,10 @@ impl State { if self.unlink_mirror(t) { if let Some(e) = self.mapped.get_mut(&t).filter(|e| e.src != 0) { // (what it held was the CPU view's: cleared, and the pages committed here - // are no holes below) + // are no holes below, where it joins `runs`) *e = TileEntry::with_holes(e.pool, 0xFFFF); self.to_zero.insert((t, TILE)); self.mirrored -= 1; - early_add(&mut self.runs, t, t + TILE); MAPPED_GEN.fetch_add(1, Ordering::Release); } } @@ -3459,23 +3503,7 @@ impl State { } else { self.ensure_mapped(a, n, |_| 0xFFFF); } - let mut pg = a & !(PAGE - 1); - let end = a.saturating_add(n); - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = t.saturating_add(TILE).min(end); - if let Some(entry) = self.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - entry.holes &= !(1u16 << ((p - t) / PAGE)); - p += PAGE; - } - } - if tile_end <= pg { - break; - } - pg = tile_end; - } + unmask_committed_holes(&mut self.mapped, &mut self.runs, a, n); } /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps @@ -4596,7 +4624,7 @@ impl State { /// The sparse windows' tiles listed (with video memory, or to get it at their first use, /// `LAZY`) as sorted (start, end) runs, and the CPU memory /// tiles of GPU views show (never the views' own addresses): where a CPU write has to reach the -/// GPU. +/// GPU. A tile with no page committed is not among them (`State::runs`). pub fn mapped_ranges() -> Vec<(usize, usize)> { let t0 = super::look_stats::deep().then(std::time::Instant::now); let g = lock_for_submit(); @@ -5536,9 +5564,9 @@ mod tests { } /// The runs of the tiles mapped, made from all of them (but those over a CPU view: their - /// own addresses are no CPU memory). + /// own addresses are no CPU memory, and those with no page committed). fn runs_of(s: &State) -> BTreeMap { - let mut tiles: Vec = s.mapped.iter().filter(|(_, e)| e.src == 0).map(|(&t, _)| t).collect(); + let mut tiles: Vec = s.mapped.iter().filter(|(_, e)| e.src == 0 && e.holes != 0xFFFF).map(|(&t, _)| t).collect(); tiles.sort_unstable(); let mut runs: Vec<(usize, usize)> = Vec::new(); for t in tiles { @@ -6419,6 +6447,7 @@ mod tests { s.ensure_mapped(base, 2 * TILE, |t| query_tile_holes(t)); assert_eq!(s.mapped[&base].holes, 0xFF0F, "uncommitted prefix and suffix pages must stay holes"); assert_eq!(s.mapped[&(base + TILE)].holes, 0xFFFF, "fully reserved tile must have all 16 holes set"); + assert_eq!(s.runs, BTreeMap::from([(base, base + TILE)]), "a tile with no page committed is not watched"); // Reading back the full 2-tile span must not fault on uncommitted pages. s.readback_ranges(&[(base, 2 * TILE)]); @@ -6438,12 +6467,50 @@ mod tests { scan_page(page0, base, &mut entry.sent[0], &mut dirty); assert_eq!(dirty, vec![(base, CHUNK)]); + // a page of the second tile committed: the CPU can write there, so it is watched + assert!(!VirtualAlloc((base + TILE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + let gen = mapped_gen(); + s.commit_range(base + TILE, PAGE); + assert_eq!(s.mapped[&(base + TILE)].holes, 0xFFFE); + assert_eq!(s.runs, BTreeMap::from([(base, base + 2 * TILE)])); + assert!(mapped_gen() > gen, "the watched ranges are made again"); + s.wait_for(s.value); drop(s); assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } } + /// A tile with no page committed (a placed buffer's over reserved memory) is left out of the + /// watched runs; the commit of one of its pages puts it there and makes the watched ranges + /// again, once (#2754). + #[test] + fn a_tile_with_no_page_committed_is_watched_from_its_first_commit() { + let t0 = 0x2000_0000usize; + let mut mapped: FxHashMap = FxHashMap::default(); + mapped.insert(t0, TileEntry::with_holes((0, 0), 0)); + mapped.insert(t0 + TILE, TileEntry::with_holes((0, 1), 0xFFFF)); + mapped.insert(t0 + 2 * TILE, TileEntry::with_holes((0, 2), 0x00FF)); + // a tile over a CPU view: its holes are the CPU view's pages, and it is never in `runs` + mapped.insert(t0 + 3 * TILE, TileEntry { src: 0x3000_0000, ..TileEntry::with_holes((0, 3), 0xFFFF) }); + let mut runs = BTreeMap::from([(t0, t0 + TILE), (t0 + 2 * TILE, t0 + 3 * TILE)]); + + let gen = mapped_gen(); + assert!(unmask_committed_holes(&mut mapped, &mut runs, t0 + TILE, PAGE)); + assert_eq!(mapped[&(t0 + TILE)].holes, 0xFFFE); + assert_eq!(runs, BTreeMap::from([(t0, t0 + 3 * TILE)])); + assert!(mapped_gen() > gen, "the watched ranges are made again"); + + // a page of a tile watched already, and of one over a CPU view: nothing new to watch + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + TILE + PAGE, PAGE)); + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + 2 * TILE, 8 * PAGE)); + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + 3 * TILE, PAGE)); + assert_eq!((mapped[&(t0 + TILE)].holes, mapped[&(t0 + 2 * TILE)].holes, mapped[&(t0 + 3 * TILE)].holes), (0xFFFC, 0, 0xFFFE)); + assert_eq!(runs, BTreeMap::from([(t0, t0 + 3 * TILE)])); + // a range over unmapped addresses changes nothing + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + 8 * TILE, 2 * TILE)); + } + /// A tile decommitted and committed again before the next submit gets its pool tile back /// with no new tile mapping (cleared instead). One that is not is unmapped and freed by /// `flush_parked` (before a submit), or when the free list runs out; a placed buffer's From fe5260b6f985c518f9158530e0aa03f7b7c4a2c7 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:40:29 +0100 Subject: [PATCH 032/175] D3D12.X: leave GPU-written textures out of the write-watch ranges Ports the texture half of upstream PR #2754 (60bc047f, "omit VRAM-only sparse tiles and GPU-written textures from write-watch ranges"). A texture the title's GPU work wrote (`gpu_written`) is never uploaded for a CPU write again, so watching its source only cost the looks for CPU writes. Upstream builds the textures' part of the watched ranges from every texture that is not GPU-written (`watchable_ranges`). Here that part is `Table::coarse`, 16 MiB blocks -> how many linked textures cover them, so the count now leaves GPU-written textures out: `link_src` and `unlink_src` are told whether the texture counts, `Table::mark_gpu_written` (from `note_gpu_write` and `submitted`) takes a linked one out, and one that `mapping_changed` gives back to the CPU counts again. A block whose count reaches 0 bumps COARSE_GEN, which is in `watch_key`, so the ranges are made again at the next submit; upstream's TEXTURES_GEN bump has no reader here. `src_pieces` is unchanged: a GPU-written texture is still found by its written pages and skipped there, as before. In this tree GPU-written textures were already skipped before the compare, so the saving is in the looks, not in the texture compare and upload. A block stays watched while a texture there that is not GPU-written, a sparse tile with a committed page, or a shown page lies in it, and ranges under WATCH_GAP apart are still one scan. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 169 ++++++++++++++++---- 1 file changed, 135 insertions(+), 34 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index c3b5a8603a..677e6f33fe 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -80,7 +80,7 @@ struct Entry { /// not uploaded yet (made since the last submit) pending: bool, /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from - /// then on and no longer uploaded + /// then on and no longer uploaded, nor watched for (`Table::coarse`) gpu_written: bool, /// the calls of the queue's page mappings made when a list that writes it was last submitted /// (`kernelx::mirrors::calls`): a mapping changed under it by a later call is newer than the @@ -126,8 +126,9 @@ struct Table { /// shadowed textures `uncover` shadowed again: a draw recorded before may still sample them, /// so their source stays linked and refreshes upload them until `Displaced::until` displaced: BTreeMap, - /// 16 MiB blocks of the textures' sources -> how many active ones cover it: the part of the - /// watched ranges that textures make (cheap to rebuild from, unlike all textures) + /// 16 MiB blocks of the textures' sources -> how many active ones cover it (and displaced + /// ones; not GPU-written ones, which no CPU write there sends up): the part of the watched + /// ranges that textures make (cheap to rebuild from, unlike all textures) coarse: BTreeMap, } @@ -173,10 +174,19 @@ impl Table { } } - fn link_src(&mut self, res: usize, src: usize, size: usize) { + /// `watched`: the texture is not GPU-written, so its source's blocks of `coarse` are watched + /// for it too (`unlink_src` is told the same). + fn link_src(&mut self, res: usize, src: usize, size: usize, watched: bool) { for p in (src >> SRC_PIECE_SHIFT)..=((src + size.max(1) - 1) >> SRC_PIECE_SHIFT) { self.src_pieces.entry(p).or_default().push(res); } + if watched { + self.watch_blocks(src, size); + } + } + + /// One texture more has its source `[src, src + size)` watched (`coarse`). + fn watch_blocks(&mut self, src: usize, size: usize) { if in_view_window(src) { return; } @@ -189,7 +199,7 @@ impl Table { } } - fn unlink_src(&mut self, res: usize, src: usize, size: usize) { + fn unlink_src(&mut self, res: usize, src: usize, size: usize, watched: bool) { for p in (src >> SRC_PIECE_SHIFT)..=((src + size.max(1) - 1) >> SRC_PIECE_SHIFT) { if let Some(v) = self.src_pieces.get_mut(&p) { v.retain(|&r| r != res); @@ -198,6 +208,13 @@ impl Table { } } } + if watched { + self.unwatch_blocks(src, size); + } + } + + /// One texture fewer has its source `[src, src + size)` watched. + fn unwatch_blocks(&mut self, src: usize, size: usize) { if in_view_window(src) { return; } @@ -217,10 +234,25 @@ impl Table { } } + /// The title's GPU work writes `res` (`note_gpu_write`, `submitted`): what the CPU writes over + /// it never goes up again, so its source is no longer watched for it – a block of `coarse` + /// only GPU-written textures lie in is left out of the looks for CPU writes. Whether it was + /// not GPU-written before. + fn mark_gpu_written(&mut self, res: usize) -> bool { + let linked = self.by_res.contains_key(&res) || self.displaced.contains_key(&res); + let Some(e) = self.get_mut(res).filter(|e| !e.gpu_written) else { return false }; + e.gpu_written = true; + let (src, size) = (e.src, e.tex.size() as usize); + if linked { + self.unwatch_blocks(src, size); + } + true + } + /// `res` (shadowed, `e`) leaves `displaced`: its source is no longer watched for it. fn undisplace(&mut self, res: usize, e: &Entry) { if self.displaced.remove(&res).is_some() { - self.unlink_src(res, e.src, e.tex.size() as usize); + self.unlink_src(res, e.src, e.tex.size() as usize, !e.gpu_written); } } @@ -229,8 +261,8 @@ impl Table { let gone: Vec = self.displaced.iter().filter(|(_, d)| d.until <= frame).map(|(&r, _)| r).collect(); for r in gone { self.displaced.remove(&r); - if let Some((src, size)) = self.shadowed.get(&r).map(|e| (e.src, e.tex.size() as usize)) { - self.unlink_src(r, src, size); + if let Some((src, size, watched)) = self.shadowed.get(&r).map(|e| (e.src, e.tex.size() as usize, !e.gpu_written)) { + self.unlink_src(r, src, size, watched); } } } @@ -296,7 +328,7 @@ impl Table { for (ova, ores, _) in self.active_overlaps(va, end) { self.by_va.remove(&(ova, ores)); if let Some(old) = self.by_res.remove(&ores) { - self.unlink_src(ores, old.src, old.tex.size() as usize); + self.unlink_src(ores, old.src, old.tex.size() as usize, !old.gpu_written); if old.pending { pending_delta -= 1; } @@ -333,7 +365,7 @@ impl Table { let mut pending_delta = 0isize; let mut to_unmap = Vec::new(); if let Some(old) = self.by_res.remove(&res) { - self.unlink_src(res, old.src, old.tex.size() as usize); + self.unlink_src(res, old.src, old.tex.size() as usize, !old.gpu_written); self.by_va.remove(&(old.va, res)); if old.pending { pending_delta -= 1; @@ -349,7 +381,7 @@ impl Table { } self.by_va.remove(&(ova, ores)); if let Some(mut old) = self.by_res.remove(&ores) { - self.unlink_src(ores, old.src, old.tex.size() as usize); + self.unlink_src(ores, old.src, old.tex.size() as usize, !old.gpu_written); if old.pending { pending_delta -= 1; } @@ -385,7 +417,7 @@ impl Table { } self.by_va.insert((va, res), end); let (src, size) = (entry.src, entry.tex.size() as usize); - self.link_src(res, src, size); + self.link_src(res, src, size, !entry.gpu_written); self.by_res.insert(res, entry); (pending_delta, to_unmap) } @@ -415,7 +447,7 @@ impl Table { // (its source stays linked: what the title writes there goes up too) self.displaced.insert(ores, Displaced { until, whole: old.pending }); } else { - self.unlink_src(ores, old.src, old.tex.size() as usize); + self.unlink_src(ores, old.src, old.tex.size() as usize, !old.gpu_written); } self.max_shadowed_size = self.max_shadowed_size.max(oend.saturating_sub(ova)); self.shadowed_by_va.insert((ova, ores), oend); @@ -437,7 +469,7 @@ impl Table { self.next_seq += 1; e.seq = self.next_seq; self.by_va.insert((va, res), end); - self.link_src(res, e.src, size); + self.link_src(res, e.src, size, !e.gpu_written); self.by_res.insert(res, e); Some((pending_delta, remap)) } @@ -454,7 +486,7 @@ impl Table { return (true, 0, Vec::new()); } let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new()) }; - self.unlink_src(res, old.src, old.tex.size() as usize); + self.unlink_src(res, old.src, old.tex.size() as usize, !old.gpu_written); self.by_va.remove(&(old.va, res)); let mut pending_delta = if old.pending { -1 } else { 0 }; let va = old.va; @@ -487,7 +519,7 @@ impl Table { } self.by_va.insert((sva, sres), send); let (src, size) = (e.src, e.tex.size() as usize); - self.link_src(sres, src, size); + self.link_src(sres, src, size, !e.gpu_written); if e.pending { self.pending_res.insert(sres); } @@ -757,15 +789,17 @@ fn recheck_gpu_view_sources() { s.extend(remapped.keys().copied()); s }); - let mut moved: Vec<(usize, usize, usize, usize, bool)> = Vec::new(); + let mut moved: Vec<(usize, usize, usize, usize, bool, bool)> = Vec::new(); + // (textures `mapping_changed` gave back to the CPU: their source is watched for them again) + let mut regained: Vec = Vec::new(); let mut again: Vec = Vec::new(); let Table { by_res, shadowed, .. } = t; let mut look = |res: usize, e: &mut Entry, active: bool| { - let (old, size) = (e.src, e.tex.size() as usize); + let (old, size, watched) = (e.src, e.tex.size() as usize, !e.gpu_written); if recheck_source(e) { changed = true; if active { - moved.push((res, old, e.src, size, e.pending)); + moved.push((res, old, e.src, size, e.pending, watched)); } } if let Some((call, parts)) = remapped.remove(&res) { @@ -773,6 +807,9 @@ fn recheck_gpu_view_sources() { again.push(res); } } + if !watched && !e.gpu_written { + regained.push(res); + } }; match &names { Some(s) => { @@ -793,13 +830,21 @@ fn recheck_gpu_view_sources() { } } } - for (res, old, new, size, pending) in moved { - t.unlink_src(res, old, size); - t.link_src(res, new, size); + for (res, old, new, size, pending, watched) in moved { + t.unlink_src(res, old, size, watched); + t.link_src(res, new, size, watched); if pending { t.pending_res.insert(res); } } + for res in regained { + if !t.by_res.contains_key(&res) && !t.displaced.contains_key(&res) { + continue; + } + if let Some((src, size)) = t.get_mut(res).map(|e| (e.src, e.tex.size() as usize)) { + t.watch_blocks(src, size); + } + } drop(g); if !again.is_empty() { AGAIN.lock().unwrap().extend(again); @@ -867,19 +912,13 @@ pub fn note_gpu_write(list: usize, res: usize) { } } } - let (mut marked, mut kept) = (false, false); - { + let (marked, kept) = { let mut t = TEXTURES.lock().unwrap(); - if let Some(e) = t.get_mut(res) { - kept = true; - if !e.gpu_written { - e.gpu_written = true; - GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); - marked = true; - } - } - } + let kept = t.get_mut(res).is_some(); + (t.mark_gpu_written(res), kept) + }; if marked { + GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); STREAM_RECHECK.lock().unwrap().remove(&res); } // (the stamp is for the queue's page mappings: with them off, a submit takes no lock for it) @@ -1107,8 +1146,9 @@ pub fn submitted(lists: &[*mut c_void]) { if !writes.is_empty() { let call = crate::hle::kernelx::mirrors::calls(); for res in writes { + t.mark_gpu_written(res); if let Some(e) = t.get_mut(res) { - (e.gpu_written, e.written_call) = (true, call); + e.written_call = call; } } } @@ -4418,6 +4458,67 @@ pub(super) mod tests { assert!(dirty_tbl.displaced.is_empty() && !dirty_tbl.coarse.contains_key(&block_a)); } + /// A GPU-written texture has its source watched no more (#2754): what the CPU writes there + /// never goes up for it, so a 16 MiB block only such textures lie in is left out of the looks + /// for CPU writes. Marked once, active or displaced, and released after, it takes nothing + /// from the count of the others. + #[test] + fn a_gpu_written_texture_keeps_no_block_watched() { + let tex_16k = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + let tex_64k = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + let entry = |va: usize, src: usize, tex: &Arc, gpu_written: bool| Entry { + device: 0, + va, + src, + in_gpu_view: false, + paged: false, + tex: Arc::clone(tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written, + written_call: 0, + placed: false, + unmapped: false, + seq: 0, + known: Default::default(), + target: false, + }; + let block = |src: usize| src >> SRC_COARSE_SHIFT; + let (a, b) = (0x4000_0000usize, 0x5000_0000usize); + let mut t = Table::new(); + t.insert(1, entry(0x10_0000, a, &tex_16k, false)); + t.insert(2, entry(0x20_0000, b, &tex_16k, true)); + assert_eq!(t.coarse, BTreeMap::from([(block(a), 1)]), "a GPU-written texture is not watched for"); + assert_eq!(t.touched_by(&[b]), [2].into_iter().collect(), "its pages still find it"); + // the GPU writes one of two textures in a block: the block stays for the other + t.insert(3, entry(0x30_0000, a + 0x10_0000, &tex_16k, false)); + assert!(t.mark_gpu_written(1)); + assert!(!t.mark_gpu_written(1), "once"); + assert_eq!(t.coarse, BTreeMap::from([(block(a), 1)])); + let gen = COARSE_GEN.load(Ordering::Acquire); + assert!(t.mark_gpu_written(3)); + assert!(t.coarse.is_empty()); + assert!(COARSE_GEN.load(Ordering::Acquire) > gen, "the watched ranges are made again"); + // released, a GPU-written texture takes nothing from another's count + t.insert(4, entry(0x40_0000, a, &tex_16k, false)); + assert_eq!(t.remove(1), (true, 0, vec![])); + assert_eq!(t.coarse, BTreeMap::from([(block(a), 1)])); + + // a displaced texture the GPU writes leaves its block, and takes nothing more once it is no + // longer displaced + let mut d = Table::new(); + assert_eq!(d.insert(20, entry(0x30_0000, b, &tex_64k, false)).0, 0); + assert_eq!(d.insert(21, entry(0x30_4000, a, &tex_16k, false)).0, 0); + assert_eq!(d.uncover(20, 5), Some((1, false))); + assert!(d.displaced.contains_key(&21)); + assert_eq!(d.coarse, BTreeMap::from([(block(a), 1), (block(b), 1)])); + assert!(d.mark_gpu_written(21)); + assert_eq!(d.coarse, BTreeMap::from([(block(b), 1)])); + d.expire_displaced(5); + assert!(!d.displaced.contains_key(&21)); + assert_eq!(d.coarse, BTreeMap::from([(block(b), 1)])); + } + /// Real GPU: one draw samples two overlapping textures, A then B. B shadows A again before /// the submit, and A is uploaded all the same (it read its old texels before). #[test] From 1be2221e82832f4167b26f671723f1eb0ee78e39 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:35:19 +0100 Subject: [PATCH 033/175] D3D12.X: texture uploads keep their lists when their buffers go Ports the command-list pooling of upstream PR #2989 (7dece6b4) to the upload path of this branch. Upstream's submit_batch made a new allocator and list for every batch and kept staging buffers of at most 8 MiB. Here 73fc616f had already replaced that path: an upload job (allocator, list and mapped buffer) is kept in FREE and used again once its fence has passed. But a job was kept or let go as a whole: a batch that none of the kept buffers fits made a new allocator and list along with its buffer, and a job let go for XCL_UPLOAD_KEEP_MB took its list with it. Now a job let go leaves its list and allocator in SPARE (at most 16 a device, upstream's CMD_POOL_MAX_PER_DEV), and a new job takes one of those before it makes one. Only give_back feeds SPARE, and it is called only once the GPU is done with the job (reclaim's fence, upload_and_wait's wait), so a spare list is never reset while the GPU runs it. The buffers let go are released out of FREE's lock. Measured on an RX 9070 XT (debug test build, three runs): making an allocator and list took 0.09-0.35 ms, resetting a kept one 3-11 us; making and mapping an upload buffer took 0.3-0.6 ms at 1 MiB, 1.2-5 ms at 16 MiB, 2-10 ms at 32 MiB, and releasing one 0.1-4.6 ms. A job made anew costs mostly its buffer; this takes the list's part off it. Not measured in a title. Not ported: - STAGING_POOL_MAX_ITEM 8 -> 32 MiB: there is no per-buffer limit here. Buffers of up to 64 MiB (powers of two) are kept, XCL_UPLOAD_KEEP_MB (64 MB) of them in all, which stays as it is. - PARALLEL_BYTES 1 MiB -> 256 KiB: hash_and_detile_all is not in this branch. Uploads of 192 KiB and more (SHARE_FROM) are compared and detiled by the standing workers in 64 KiB pieces, already below upstream's new threshold. Uploads detile with detile_blocks' runs (73fc616f); 27e95627 sped up detile_level, which uploads do not use, so nothing asks for a lower threshold. - Clearing the lists on low commit (trim_idle_staging): FREE has no such trim here, and the spare lists are small next to its buffers. - The XCL_UPLOAD_CMD_POOL switch and the #[ignore] benchmark. Tests: upstream's pool test as spares_are_kept_by_device_newest_first_up_to_the_most, and its GPU test as gpu_a_list_whose_buffer_went_goes_on_with_a_new_one (a job let go leaves its list, a job made next takes it with a bigger buffer, read back texel for texel); it keys its job to a device of its own so the other tests' uploads cannot take its spare. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/texture_upload.rs | 148 ++++++++++++++++++-- 1 file changed, 137 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index fb3a9f231f..d758c87351 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -825,6 +825,43 @@ unsafe impl Send for Job {} static FREE: Mutex> = Mutex::new(Vec::new()); /// the smallest upload buffer made, and the most bytes of them kept const BUFFER_MIN: u64 = 1 << 20; +/// the lists of jobs whose buffers went (`give_back`), the GPU done with them too: a batch that +/// none of the kept buffers fits makes a buffer, not a list as well (on an RX 9070 XT a list with +/// its allocator took 0.1-0.35 ms to make, 3-11 µs to reset). Kept whatever `XCL_UPLOAD_KEEP_MB` +/// is: they are small next to the buffers +static SPARE: Mutex> = Mutex::new(Spares::new(SPARE_MAX)); +/// the most spare lists kept of one device +const SPARE_MAX: usize = 16; + +/// A list and its allocator. +type Lists = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// Things kept for later by device, the newest taken first, at most `max` of one device. +struct Spares { + kept: Vec<(usize, T)>, + max: usize, +} + +impl Spares { + const fn new(max: usize) -> Self { + Spares { kept: Vec::new(), max } + } + + /// The newest kept of `dev`'s. + fn take(&mut self, dev: usize) -> Option { + let i = self.kept.iter().rposition(|(d, _)| *d == dev)?; + Some(self.kept.remove(i).1) + } + + /// `x` is kept, unless `dev` has `max` kept already: then it comes back. + fn keep(&mut self, dev: usize, x: T) -> Option { + if self.kept.iter().filter(|(d, _)| *d == dev).count() >= self.max { + return Some(x); + } + self.kept.push((dev, x)); + None + } +} /// The size of the buffer made for `bytes`: up to 64 MiB a power of two (few sizes, so one fits /// again), then the next 16 MiB. @@ -865,12 +902,14 @@ unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { return Ok(g.swap_remove(i)); } } + let spare = SPARE.lock().unwrap().take(key); + make_job(dev, bytes, spare) +} + +/// A job with a new buffer for `bytes` bytes, and `lists` (the GPU done with them) or new ones. +unsafe fn make_job(dev: &ID3D12Device, bytes: u64, lists: Option) -> Result { let e = |x: windows::core::Error| format!("texture upload: {x}"); let cap = capacity(bytes).ok_or("texture upload buffer size overflow")?; - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; - list.Close().map_err(e)?; - let _ = list.SetName(windows::core::w!("xcl texture upload list")); let mut buf: Option = None; dev.CreateCommittedResource( &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, @@ -893,17 +932,34 @@ unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { let buf = buf.ok_or("texture upload buffer")?; let mut p: *mut c_void = std::ptr::null_mut(); buf.Map(0, None, Some(&mut p)).map_err(e)?; - Ok(Job { dev: key, alloc, list, buf, ptr: p as *mut u8, bytes: cap }) + let (alloc, list) = match lists { + Some(l) => l, + None => { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; + list.Close().map_err(e)?; + let _ = list.SetName(windows::core::w!("xcl texture upload list")); + (alloc, list) + } + }; + Ok(Job { dev: dev.as_raw() as usize, alloc, list, buf, ptr: p as *mut u8, bytes: cap }) } /// The GPU is done with `job`. pub(super) fn give_back(job: Job) { - let mut g = FREE.lock().unwrap(); - g.push(job); - // (the biggest goes first: one burst does not keep its buffers for good) - while g.iter().map(|j| j.bytes).sum::() > free_bytes() { - let Some(i) = g.iter().enumerate().max_by_key(|(_, j)| j.bytes).map(|(i, _)| i) else { break }; - g.swap_remove(i); + let mut gone = Vec::new(); + { + let mut g = FREE.lock().unwrap(); + g.push(job); + // (the biggest goes first: one burst does not keep its buffers for good) + while g.iter().map(|j| j.bytes).sum::() > free_bytes() { + let Some(i) = g.iter().enumerate().max_by_key(|(_, j)| j.bytes).map(|(i, _)| i) else { break }; + gone.push(g.swap_remove(i)); + } + } + // (their buffers go, out of the lock: that can take milliseconds; their lists stay) + for j in gone { + let _ = SPARE.lock().unwrap().keep(j.dev, (j.alloc, j.list)); } } @@ -1343,6 +1399,76 @@ mod tests { assert_eq!(capacity(u64::MAX), None); } + /// Spares: none kept when the most is 0, the newest of a device first, no more of one device + /// than the most (the one past it comes back), and each device's apart. + #[test] + fn spares_are_kept_by_device_newest_first_up_to_the_most() { + let mut none = Spares::::new(0); + assert_eq!(none.keep(1, 10), Some(10)); + assert_eq!(none.take(1), None); + + let mut s = Spares::::new(2); + assert_eq!(s.take(1), None); + assert_eq!(s.keep(1, 10), None); + assert_eq!(s.keep(2, 99), None); + assert_eq!(s.keep(1, 20), None); + assert_eq!(s.keep(1, 30), Some(30), "past the most of a device it comes back, to go"); + assert_eq!(s.keep(2, 98), None, "another device's are counted apart"); + assert_eq!(s.take(1), Some(20)); + assert_eq!(s.take(1), Some(10)); + assert_eq!(s.take(1), None); + assert_eq!(s.take(2), Some(98)); + assert_eq!(s.take(2), Some(99)); + assert_eq!(s.take(2), None); + } + + /// A job whose buffer goes (more is kept than `XCL_UPLOAD_KEEP_MB`) leaves its list, and a job + /// made next for the device takes it with a new buffer, not a new list: what goes up through it + /// is the texture's texels. + #[test] + fn gpu_a_list_whose_buffer_went_goes_on_with_a_new_one() { + unsafe { + let Some(dev) = test_device() else { return }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let m = make(&dev, KINDS[1]); + let size = m.tex.size() as usize; + // all of the texture through `job` as `submit` sends it, waited for and read back + let up = |job: &Job, seed: u64| { + let mem = random_bytes(size, seed); + let items = [Item { res: m.res.clone(), src: mem.as_ptr() as usize, tex: Arc::clone(&m.tex), states: vec![D3D12_RESOURCE_STATE_COMMON], changed: None, known: None, pages: None }]; + let (mut pieces, mut bytes) = (Vec::new(), 0u64); + plan_item(&dev, 0, &items[0], &mut bytes, &mut pieces).unwrap(); + assert!(bytes <= job.bytes, "{bytes} B in a {} B buffer", job.bytes); + fill(&items, &pieces, job.ptr, bytes); + job.alloc.Reset().unwrap(); + job.list.Reset(&job.alloc, None).unwrap(); + record(&job.list, &items, &pieces, &job.buf); + job.list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(job.list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let want = super::super::title_textures::subresources(mem.as_ptr() as usize, &m.tex); + assert!(read_back(&dev, &queue, &m.res, want.len()) == want.iter().map(|w| w.data.clone()).collect::>(), "upload {seed}"); + }; + let mut first = make_job(&dev, 1, None).unwrap(); + assert_eq!(first.bytes, BUFFER_MIN); + up(&first, 1); + let list = first.list.as_raw() as usize; + // (taken for a device of its own, and for more than is ever kept: it goes at once, + // whatever the other tests keep, and its list is that device's only spare) + let own = Box::new(0u8); + let key = &*own as *const u8 as usize; + first.dev = key; + first.bytes = 1 << 62; + give_back(first); + let lists = SPARE.lock().unwrap().take(key).expect("its list stays"); + assert_eq!(lists.1.as_raw() as usize, list); + let second = make_job(&dev, 4 << 20, Some(lists)).unwrap(); + assert_eq!((second.list.as_raw() as usize, second.bytes), (list, 4 << 20), "the spare list, with a new buffer"); + up(&second, 2); + dev.GetDeviceRemovedReason().unwrap(); + } + } + /// A page the title decommits while it is read (or that never was committed) reads as zeros. #[test] fn memory_that_is_not_there_reads_as_zeros() { From 512b0bbccc2358214115550ea64ff594074725af Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:35:19 +0100 Subject: [PATCH 034/175] D3D12.X: retain a texture upload job whose fallback wait fails Ports upstream PR #2989's d1167f8d. A job given back is reset and written by the next batch, and a job dropped releases a buffer the GPU may still read: neither may happen until a wait has said the GPU is done with it. submit_on already kept the job (std::mem::forget) when the wait after a failed Signal failed; it now goes through release_after_upload_wait, as upstream's submit_on_title_queue does, with the same behaviour. upload_and_wait returned on a failed wait and so dropped the job: it now keeps it. In this branch the fence is made before the batch is submitted, so upstream's other site (a failed CreateFence after the submit) does not exist here. Unlike upstream's, the helper takes what to do with the job, since a job here is given back explicitly (give_back) rather than on drop. Test: upstream's failed_upload_wait_retains_submitted_resources, which also checks that the job is not given back when the wait fails. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 46 ++++++++++++++++++--- 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 677e6f33fe..ac79fa874c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2333,6 +2333,16 @@ unsafe fn reclaim(q: &mut QueueUploads, cap: u64, wait_ms: u64) { } } +/// `job` goes (`release`) only once `wait` says the GPU is done with it. When the wait fails it is +/// kept for good: the GPU may still run its list and read its buffer, which a job given back would +/// reset and write again. +fn release_after_upload_wait(job: T, wait: impl FnOnce() -> Result<(), String>, release: impl FnOnce(T)) -> Result<(), String> { + let job = std::mem::ManuallyDrop::new(job); + wait()?; + release(std::mem::ManuallyDrop::into_inner(job)); + Ok(()) +} + /// Drop tracked upload state for a released command queue so its fence and staging buffers do not /// leak and a later queue at the same address cannot reuse a stale fence. pub(super) fn on_queue_release(queue_key: usize) { @@ -2389,10 +2399,7 @@ unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[tex let Some(f) = f else { return Ok((failed, 0, None)) }; if let Err(e) = queue.Signal(&q.fence, q.value + 1) { // the GPU may still run the list and read the buffer: they stay when it does not get there - match texture::wait(dev, queue) { - Ok(()) => drop(f), - Err(_) => std::mem::forget(f), - } + let _ = release_after_upload_wait(f, || texture::wait(dev, queue), drop); return Err(e.to_string()); } q.value += 1; @@ -2635,8 +2642,7 @@ pub unsafe fn upload_and_wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue, re } let item = texture_upload::Item { res: res.clone(), src: mem.as_ptr() as usize, tex, states, changed, known: None, pages: None }; let (failed, job, _) = own_work(|| texture_upload::submit(dev, queue, &[item]))?; - texture::wait(dev, queue)?; - job.into_iter().for_each(texture_upload::give_back); + release_after_upload_wait(job, || texture::wait(dev, queue), |job| job.into_iter().for_each(texture_upload::give_back))?; failed.into_iter().next().map_or(Ok(()), |(_, e)| Err(e)) } @@ -5723,4 +5729,32 @@ pub(super) mod tests { VirtualFree(base as *mut c_void, 0, MEM_RELEASE); } } + + /// An upload job whose wait failed is neither given back nor dropped (the GPU may still read + /// it); one whose wait came back is, once. + #[test] + fn failed_upload_wait_retains_submitted_resources() { + use std::cell::Cell; + use std::rc::Rc; + + struct Probe(Rc>); + impl Drop for Probe { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + + let (drops, released) = (Rc::new(Cell::new(0)), Cell::new(0)); + let release = |p: Probe| { + released.set(released.get() + 1); + drop(p); + }; + let err = release_after_upload_wait(Probe(Rc::clone(&drops)), || Err("wait timed out".into()), release); + assert!(err.is_err()); + assert_eq!((drops.get(), released.get()), (0, 0), "failed wait must retain submitted resources without recycling"); + + let ok = release_after_upload_wait(Probe(Rc::clone(&drops)), || Ok(()), release); + assert!(ok.is_ok()); + assert_eq!((drops.get(), released.get()), (1, 1), "successful wait must drop and recycle submitted resources"); + } } From 15a72ce5d6e386b039a12fee61d2323686adf3a9 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:37:04 +0100 Subject: [PATCH 035/175] D3D12.X: XCL_UMA_DRIVER=mixed keeps part of the coherent window in VRAM Port of upstream dbaa3b24. With XCL_UMA_DRIVER=mixed::[,...] the coherent window becomes several driver heaps instead of one CUSTOM heap: each listed range a GPU_UPLOAD heap (video memory the CPU writes through the BAR) and the rest CUSTOM write-back L0 heaps. Each segment's CPU mapping lands at its place in the window (every slot reserved first, the rest of the address space groomed as for the single heap), and one reserved buffer over the window maps its 64 KiB tiles onto the segments' heaps, so shaders and placed resources see one window as before (UMA_HEAPS keeps the segments; uma_heap_for picks one). - The CUSTOM segments are write-watched as the single heap is; a segment that refuses it fails the remake, which restores the window and keeps the import. The GPU_UPLOAD segments are not write-watched (upstream: their write-combined pages refused a watch trap's read-only protection). Uma::watch_regions lists only the watched segments. - CPU reads of the GPU_UPLOAD segments through the BAR ran at 12-84 MiB/s upstream, so the title texture code reads them by a copy on a COPY queue into a readback buffer (read_vram_bytes). Upstream measured 11.99 -> 24-25 fps in a retail title on an RTX 5070 Ti with mixed:1536:1792; nothing is measured here. Adapted to this tree: - remake_with_after_release, the restore that stops the process and its test were here already. groom keeps this tree's window-sized stretches and margin (groom_with takes them, as upstream resolved it in its merge into main). - open_uma keeps allow_driver_remap. - range_any_nonzero, a reader of the window in place that upstream's base did not have, goes through read_vram_bytes too: a level of zeros is read to its end. - The adapter check of upstream 2fc61b64 (gpu_upload_heaps, asked before the window is released) is in this commit: without it the mixed test stopped the test process on an RX 9070 XT. The inbox D3D12 of Windows 11 22631 does not know D3D12_OPTIONS16 (E_INVALIDARG), so CreateHeap(GPU_UPLOAD) failed with E_INVALIDARG after the first CUSTOM segment was mapped, and the window could not be reserved again (Windows error 487). The warning names the runtime as well as Resizable BAR; the test makes its device through the Agility SDK when there is one and is skipped without GPU_UPLOAD heaps. - The test runs again in a process of its own (ran_alone, as this file's grooming test does): a remake reserves every other free stretch of the process, and beside the other GPU tests of `uma` with 4 threads their allocations failed and a segment's CreateHeap failed after another was mapped, which stops the process. Unset or custom, the single CUSTOM heap is made as before; only a value that starts with "mixed:" takes the new path. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/uma.rs | 25 +- crates/xcl/src/hle/d3d12x/real.rs | 43 +- crates/xcl/src/hle/d3d12x/texture_upload.rs | 5 + crates/xcl/src/hle/d3d12x/title_textures.rs | 10 + crates/xcl/src/hle/d3d12x/uma_driver.rs | 526 +++++++++++++++++++- 5 files changed, 586 insertions(+), 23 deletions(-) diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7b12ec9b0d..14db3ec3ef 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -753,7 +753,11 @@ impl Uma { match self.kinds[k] { WindowKind::None | WindowKind::View => k += 1, WindowKind::Committed(s) => { - out.push((self.base + k * WINDOW, s)); + if let Some(segs) = driver_watch_segments(k) { + out.extend(segs); + } else { + out.push((self.base + k * WINDOW, s)); + } k += 1; } WindowKind::Sparse => { @@ -1166,6 +1170,25 @@ impl Uma { } } +/// Per-window write-watched sub-ranges of mixed driver windows (`XCL_UMA_DRIVER=mixed:...`): only +/// their CUSTOM segments are write-watched, not the GPU_UPLOAD one. +static DRIVER_WATCH_SEGMENTS: Mutex)>> = Mutex::new(Vec::new()); + +/// Window `k` was remade as several driver-heap segments; only `segs` are write-watched. +pub fn set_driver_watch_segments(k: usize, segs: Vec<(usize, usize)>) { + let mut g = DRIVER_WATCH_SEGMENTS.lock().unwrap(); + if let Some(entry) = g.iter_mut().find(|(wk, _)| *wk == k) { + entry.1 = segs; + } else { + g.push((k, segs)); + } +} + +fn driver_watch_segments(k: usize) -> Option> { + let g = DRIVER_WATCH_SEGMENTS.lock().unwrap(); + g.iter().find(|(wk, _)| *wk == k).map(|(_, segs)| segs.clone()) +} + /// The title's graphics memory (created on first use; `XCL_UMA_MB`, default 2048; /// `XCL_UMA_WINDOWS=4|8|16`, default 4, with 8/16 requiring `XCL_HEAP_WINDOWS=1`). pub fn get() -> Option<&'static Uma> { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 558c2a28b3..eba34d11ce 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -184,8 +184,23 @@ pub fn abi_root_signature() -> Option { /// `mem`, `mem1`.. of recompiled shaders. (buffer, GPU VA) per window, kept for the process /// lifetime. static UMA_BUFFER: Mutex> = Mutex::new(Vec::new()); -/// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows) -static UMA_HEAPS: Mutex>> = Mutex::new(Vec::new()); +/// Window heaps for `CreatePlacedResource` inside coherent UMA windows: for each window `k`, +/// contiguous `(seg_offset, seg_len, heap_raw)` segments (1 entry for single-heap windows, N for +/// `XCL_UMA_DRIVER=mixed:...`; none for sparse windows). +static UMA_HEAPS: Mutex>> = Mutex::new(Vec::new()); + +/// The heap of window `k` that holds `[offset, offset + len)` (an offset in the window), and the +/// offset in that heap. +fn uma_heap_for(k: usize, offset: usize, len: usize) -> Option<(usize, usize)> { + let g = UMA_HEAPS.lock().unwrap(); + let segs = g.get(k)?; + for &(seg_off, seg_len, heap_raw) in segs { + if offset >= seg_off && offset.saturating_add(len) <= seg_off.saturating_add(seg_len) { + return Some((heap_raw, offset - seg_off)); + } + } + None +} /// console buffers placed in unified memory: resource → (address, bytes) /// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX) type UmaBuffer = (usize, usize, bool); @@ -396,7 +411,7 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { }; let n = u.shader_windows(); let mut bufs: Vec<(usize, u64)> = vec![(0, 0); n]; - let mut heaps: Vec> = vec![None; n]; + let mut heaps: Vec> = vec![Vec::new(); n]; let mut shadows: Vec<(usize, ID3D12Resource)> = Vec::new(); for k in 0..n { if !u.is_committed_window(k) { @@ -404,12 +419,14 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { } if allow_driver_remap && shadow_choice() != Some(true) && super::uma_driver::wanted(device) { let (base, size) = u.window(k); - match super::uma_driver::remake(device, base, size) { - Ok((heap, buf)) => { - let (raw, va, heap) = super::uma_driver::raw(heap, buf); + match super::uma_driver::remake_window(device, base, size) { + Ok(remade) => { u.set_driver_window(k); - bufs[k] = (raw, va); - heaps[k] = Some(heap); + if let Some(segs) = remade.watched_regions { + crate::gpu::uma::set_driver_watch_segments(k, segs); + } + bufs[k] = (remade.buf_raw, remade.gpu_va); + heaps[k] = remade.heaps; continue; } Err(e) => crate::xlog_warn!("D3D12.X: coherent window {k} stays imported: {e}"), @@ -434,7 +451,7 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { match made { Ok((buf_raw, va, heap_raw)) => { bufs[k] = (buf_raw, va); - heaps[k] = Some(heap_raw); + heaps[k] = vec![(0, u.window(k).1, heap_raw)]; } Err(e) => { crate::xlog_warn!("D3D12.X: UMA not available to the GPU: {e}"); @@ -1750,8 +1767,8 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta // the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state let k = u.window_of(p)?; let (d, st) = sanitize_coherent_buffer(&d, state, !u.is_driver_window(k)); - let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; - let hr = dev_create_placed_resource(this, heap, p - u.window(k).0, &d as *const _ as usize, st as usize, clear, riid, ppv); + let (heap, heap_off) = uma_heap_for(k, p - u.window(k).0, d.Width as usize)?; + let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, st as usize, clear, riid, ppv); if hr < 0 || (*ppv).is_null() { u.free(p); static ONCE: AtomicU64 = AtomicU64::new(0); @@ -1854,14 +1871,14 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: } return Some(hr); } - let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; + let (heap, heap_off) = uma_heap_for(k, start - base, delta + bytes)?; if !u.is_driver_window(k) && !u.shadowed() { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; } d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; d.Width = (delta + bytes) as u64; - let hr = dev_create_placed_resource(this, heap, start - base, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); + let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { return None; } diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index d758c87351..f53d9e8604 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -448,6 +448,11 @@ unsafe fn read(pages: Option<&PageMap>, at: usize, len: usize, f: impl FnOnce f(&s[..len]) }); } + // a GPU_UPLOAD segment of a mixed driver window: by the GPU's copy (CPU reads of that video + // memory through the BAR are slow) + if let Some(bytes) = super::uma_driver::read_vram_bytes(at, len) { + return f(&bytes); + } if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { return f(std::slice::from_raw_parts(at as *const u8, len)); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ac79fa874c..eb9f190e01 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2658,6 +2658,11 @@ unsafe fn range_any_nonzero(va: usize, off: usize, end: usize, pages: Option<&te } static SAFE: std::sync::OnceLock = std::sync::OnceLock::new(); let safe = *SAFE.get_or_init(|| std::env::var("XCL_TEXTURE_SAFE_READ").is_ok_and(|v| v.trim() == "1")); + // (a GPU_UPLOAD segment of a mixed driver window: by the GPU's copy, as `title_bytes` reads it; + // a level of zeros is read to its end, through the BAR slowly) + if let Some(bytes) = super::uma_driver::read_vram_bytes(at, len) { + return !all_zero(&bytes); + } if !safe && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { return !all_zero(std::slice::from_raw_parts(at as *const u8, len)); } @@ -3273,6 +3278,11 @@ unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> // submits make the race likely); the copy goes through the kernel, which gives zeros for it. static SAFE: std::sync::OnceLock = std::sync::OnceLock::new(); let safe = *SAFE.get_or_init(|| std::env::var("XCL_TEXTURE_SAFE_READ").is_ok_and(|v| v.trim() == "1")); + // a GPU_UPLOAD segment of a mixed driver window: by the GPU's copy (CPU reads of that video + // memory through the BAR are slow) + if let Some(bytes) = super::uma_driver::read_vram_bytes(at, len) { + return std::borrow::Cow::Owned(bytes); + } if !safe && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { std::borrow::Cow::Borrowed(std::slice::from_raw_parts(at as *const u8, len)) } else { diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs index e4c4b8b7ee..662c6378cc 100644 --- a/crates/xcl/src/hle/d3d12x/uma_driver.rs +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -9,9 +9,20 @@ //! stays in `Uma::watch_regions` and the title's CPU writes reach its textures as before; a driver //! that refuses it, or whose mapping `GetWriteWatch` cannot read, keeps the import. //! -//! `XCL_UMA_DRIVER`: `custom` or `1` on, `0` off; unset: on for an NVIDIA adapter outside Wine. +//! `mixed::[,...]` makes the window several driver heaps instead of one: each +//! range a `GPU_UPLOAD` heap (video memory the CPU writes through the BAR; on NVIDIA it stays in +//! video memory up to 2 GiB) and the rest CUSTOM write-back L0 heaps, each segment's CPU mapping at +//! its place in the window and one reserved buffer over all of them on the GPU +//! (`UpdateTileMappings`). The `GPU_UPLOAD` segments are not write-watched (write-combined pages +//! refuse a watch trap's read-only protection); the title texture code reads them through a copy +//! on the GPU (`read_vram_bytes`). +//! +//! `XCL_UMA_DRIVER`: `custom` or `1` on, `mixed:...` on with the ranges above, `0` off; unset: on +//! (one CUSTOM heap) for an NVIDIA adapter outside Wine. use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -21,6 +32,7 @@ use windows_sys::Win32::System::Memory::{ }; const MEM_WRITE_WATCH: u32 = 0x20_0000; +const TILE: usize = 0x1_0000; #[link(name = "kernel32")] extern "system" { @@ -36,11 +48,32 @@ pub(super) fn wanted(device: &ID3D12Device) -> bool { fn decide(switch: Option<&str>, wine: impl FnOnce() -> bool, vendor: impl FnOnce() -> Option) -> bool { match switch.map(str::trim) { Some("custom" | "1") => true, + Some(s) if s.starts_with("mixed:") => true, Some("0") => false, _ => !wine() && vendor() == Some(0x10DE), } } +/// `XCL_UMA_DRIVER=mixed::[,...]`: the window's `GPU_UPLOAD` ranges +/// `(start, len)` in bytes, in order; None for any other value. +fn mixed_ranges() -> Option> { + parse_mixed(&std::env::var("XCL_UMA_DRIVER").ok()?) +} + +fn parse_mixed(raw: &str) -> Option> { + let list = raw.trim().strip_prefix("mixed:")?; + let mut ranges = Vec::new(); + for part in list.split(',') { + let (a, b) = part.trim().split_once(':')?; + let (start_mb, size_mb): (usize, usize) = (a.trim().parse().ok()?, b.trim().parse().ok()?); + if size_mb != 0 { + ranges.push((start_mb << 20, size_mb << 20)); + } + } + ranges.sort_by_key(|r| r.0); + (!ranges.is_empty()).then_some(ranges) +} + /// PCI vendor id of `device`'s adapter. fn vendor(device: &ID3D12Device) -> Option { use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; @@ -82,8 +115,12 @@ unsafe fn written_pages(base: usize, size: usize) -> Result) /// outside `[hole, hole + len)`. A window under 1 GiB (512 MB with the 16-window layout) found a /// stretch between its size and 1 GiB unreserved, and the driver mapped its heap there. unsafe fn groom(hole: usize, len: usize) -> Vec { + groom_with(hole, len, len.min(1 << 30), (256usize << 20).min(len / 2) & !0xFFFF) +} + +/// `groom` for stretches of `min_region` or more, leaving `headroom` at the start of each. +unsafe fn groom_with(hole: usize, len: usize, min_region: usize, headroom: usize) -> Vec { let (top, mut a, mut got) = (0x7FFF_FFFE_0000usize, 0x1_0000usize, Vec::new()); - let (least, margin) = (len.min(1 << 30), (256usize << 20).min(len / 2) & !0xFFFF); while a < top { let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of::()) == 0 { @@ -91,10 +128,10 @@ unsafe fn groom(hole: usize, len: usize) -> Vec { } let (base, end) = (m.BaseAddress as usize, (m.BaseAddress as usize + m.RegionSize).min(top)); a = end; - if m.State != MEM_FREE || m.RegionSize < least { + if m.State != MEM_FREE || m.RegionSize < min_region { continue; } - let s = ((base + 0xFFFF) & !0xFFFF) + margin; + let s = ((base + 0xFFFF) & !0xFFFF).saturating_add(headroom); for (s, e) in [(s, end.min(hole)), (s.max(hole + len), end)] { let mut s = s; while s < e { @@ -222,15 +259,410 @@ unsafe fn remake_with_after_release( } } -/// `heap` and `buf` as the raw pointers `open_uma` keeps. -pub(super) fn raw(heap: ID3D12Heap, buf: ID3D12Resource) -> (usize, u64, usize) { - let va = unsafe { buf.GetGPUVirtualAddress() }; - (buf.into_raw() as usize, va, heap.into_raw() as usize) +/// A coherent window remade as driver heap(s): the buffer shaders bind, the heaps `(offset, len, +/// heap)` that resources placed in the window go to, and the write-watched parts `(va, len)` when +/// they are not the whole window (a mixed window's CUSTOM segments). +pub(super) struct Remade { + pub buf_raw: usize, + pub gpu_va: u64, + pub heaps: Vec<(usize, usize, usize)>, + pub watched_regions: Option>, +} + +/// `remake`, or `remake_mixed` with `XCL_UMA_DRIVER=mixed:...` on an adapter with `GPU_UPLOAD` +/// heaps. +pub(super) unsafe fn remake_window(device: &ID3D12Device, base: usize, size: usize) -> Result { + if let Some(ranges) = mixed_ranges() { + if gpu_upload_heaps(device) { + return remake_mixed(device, base, size, &ranges); + } + crate::xlog_warn!("D3D12.X: XCL_UMA_DRIVER=mixed: the adapter has no GPU_UPLOAD heaps (Resizable BAR off, or a D3D12 runtime without them: Agility SDK 1.613+), so the coherent window is one CUSTOM heap"); + } + let (heap, buf) = remake(device, base, size)?; + let gpu_va = buf.GetGPUVirtualAddress(); + Ok(Remade { buf_raw: buf.into_raw() as usize, gpu_va, heaps: vec![(0, size, heap.into_raw() as usize)], watched_regions: None }) +} + +/// Whether the adapter makes `GPU_UPLOAD` heaps (`D3D12_OPTIONS16`; needs Resizable BAR and a +/// runtime that knows them, the Agility SDK on Windows 11 23H2). Asked before the window is +/// released: a segment's mapping stays with the driver after its heap is dropped, so a window +/// cannot be made whole again once a segment has been mapped. +unsafe fn gpu_upload_heaps(device: &ID3D12Device) -> bool { + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default(); + device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS16, &mut opts as *mut _ as *mut c_void, std::mem::size_of::() as u32) + .is_ok() + && opts.GPUUploadHeapSupported.as_bool() +} + +fn heap_props(upload: bool) -> D3D12_HEAP_PROPERTIES { + if upload { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_GPU_UPLOAD, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + } + } +} + +fn buffer_desc(size: usize) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size as u64, + 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() + } +} + +/// One segment of a mixed window: a heap of `size` bytes (write-watched when `watch`), a buffer +/// over all of it and where the driver mapped it for the CPU. +unsafe fn mapped_segment(device: &ID3D12Device, size: usize, upload: bool, watch: bool) -> Result<(ID3D12Heap, ID3D12Resource, usize), String> { + let flags = if watch { D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH } else { D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; + let desc = D3D12_HEAP_DESC { SizeInBytes: size as u64, Properties: heap_props(upload), Alignment: 0x1_0000, Flags: flags }; + let mut heap: Option = None; + device.CreateHeap(&desc, &mut heap).map_err(|e| format!("CreateHeap{}: {e}", if watch { " (write-watched)" } else { "" }))?; + let heap = heap.ok_or("CreateHeap")?; + let mut buf: Option = None; + device.CreatePlacedResource(&heap, 0, &buffer_desc(size), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; + let buf = buf.ok_or("CreatePlacedResource")?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, Some(&D3D12_RANGE::default()), Some(&mut p)).map_err(|e| format!("Map: {e}"))?; + Ok((heap, buf, p as usize)) +} + +/// `[0, size)` as contiguous `(offset, len, upload)` segments: `vram_ranges` (sorted) on 64 KiB +/// tiles as `GPU_UPLOAD` segments, the rest CUSTOM. +fn build_segments(size: usize, vram_ranges: &[(usize, usize)]) -> Result, String> { + let mut segs = Vec::new(); + let mut cur = 0usize; + for &(start, len) in vram_ranges { + let s = start.min(size) & !(TILE - 1); + let e = start.saturating_add(len).min(size) & !(TILE - 1); + if e <= s { + continue; + } + if s < cur { + return Err(format!("overlapping mixed ranges at {s:#x} < {cur:#x}")); + } + if s > cur { + segs.push((cur, s - cur, false)); + } + segs.push((s, e - s, true)); + cur = e; + } + if cur < size { + segs.push((cur, size - cur, false)); + } + if !segs.iter().any(|s| s.2) { + return Err("no GPU_UPLOAD range inside the window".into()); + } + Ok(segs) +} + +/// The window could not be made again at its address after it was released: the title's memory +/// there is gone, so the process stops before guest code uses it (as `remake` does). +unsafe fn stop_unbacked(base: usize, size: usize, got: *mut c_void, why: &str) -> ! { + let os_error = windows_sys::Win32::Foundation::GetLastError(); + crate::xlog_error!( + "D3D12.X: coherent window could not be restored at {base:#x} ({size} bytes, got {got:?}, Windows error {os_error}) after {why}; stopping before guest memory is used" + ); + crate::log::flush(); + windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), 0x7C1_0003); + std::process::abort(); +} + +/// `remake` with `XCL_UMA_DRIVER=mixed:...`: the window as one driver heap per segment +/// (`build_segments`), each mapped for the CPU at its place in the window, and one reserved buffer +/// over the window whose tiles map to the segments' heaps. The CUSTOM segments are write-watched +/// (a segment that refuses it fails the remake); the `GPU_UPLOAD` ones are not, and are read +/// through `read_vram_bytes`. On failure the window is the title's memory again, its pages as they +/// were. +unsafe fn remake_mixed(device: &ID3D12Device, base: usize, size: usize, vram_ranges: &[(usize, usize)]) -> Result { + let t0 = std::time::Instant::now(); + let spec = build_segments(size, vram_ranges)?; + let min_seg = spec.iter().map(|s| s.1).min().unwrap_or(64 << 20); + let pages = written_pages(base, size)?; + let kept: usize = pages.iter().map(|p| p.1.len()).sum(); + if VirtualFree(base as *mut c_void, 0, MEM_RELEASE) == 0 { + return Err(format!("VirtualFree of the window at {base:#x} failed")); + } + let restore = |why: String, placed: Vec<(usize, usize, bool, ID3D12Heap, ID3D12Resource)>, placeholders: Vec| -> String { + for (_, _, _, h, b) in placed { + b.Unmap(0, None); + drop((b, h)); + } + for p in placeholders { + if p != 0 { + VirtualFree(p as *mut c_void, 0, MEM_RELEASE); + } + } + let p = VirtualAlloc(base as *const c_void, size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE); + if p as usize != base { + stop_unbacked(base, size, p, &why); + } + for (a, bytes) in &pages { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len()); + } + why + }; + + // every segment's place reserved on its own, so one segment's mapping cannot land in another's + let mut placeholders: Vec = Vec::with_capacity(spec.len()); + for &(off, len, _) in &spec { + let want = base + off; + let p = VirtualAlloc(want as *const c_void, len, MEM_RESERVE, PAGE_NOACCESS); + if p as usize != want { + if !p.is_null() { + VirtualFree(p, 0, MEM_RELEASE); + } + return Err(restore(format!("placeholder reserve at {want:#x} ({} MB) got {p:?}", len >> 20), Vec::new(), placeholders)); + } + placeholders.push(want); + } + + // every free stretch of `min_seg` or more outside the window reserved, but 16 MiB at its start + // for the driver's own small mappings + let groomed = groom_with(base, size, min_seg, (16 << 20).min(min_seg / 4)); + let reservations = groomed.len(); + let readable = |at: usize, len: usize| { + let (mut one, mut n, mut page) = ([std::ptr::null_mut::(); 1], 1usize, 0u32); + GetWriteWatch(0, at as *const c_void, len, one.as_mut_ptr(), &mut n, &mut page) == 0 + }; + let mut placed: Vec<(usize, usize, bool, ID3D12Heap, ID3D12Resource)> = Vec::with_capacity(spec.len()); + let mut fail: Option = None; + for (idx, &(off, len, upload)) in spec.iter().enumerate() { + let want = base + off; + let what = if upload { "GPU_UPLOAD" } else { "CUSTOM" }; + let ph = std::mem::replace(&mut placeholders[idx], 0); + if VirtualFree(ph as *mut c_void, 0, MEM_RELEASE) == 0 { + fail = Some(format!("VirtualFree of the placeholder at {want:#x} failed")); + break; + } + // (no write watch on GPU_UPLOAD: its write-combined pages refuse a watch trap's + // read-only protection, which then retried tens of thousands of times) + match mapped_segment(device, len, upload, !upload) { + Ok((heap, buf, p)) if p == want && (upload || readable(want, len)) => placed.push((off, len, upload, heap, buf)), + Ok((heap, buf, p)) => { + buf.Unmap(0, None); + drop((buf, heap)); + fail = Some(if p == want { + format!("segment {idx} ({} MB {what}): GetWriteWatch cannot read its mapping", len >> 20) + } else { + format!("segment {idx} ({} MB {what}): Map gave {p:#x}, wanted {want:#x}", len >> 20) + }); + break; + } + Err(e) => { + fail = Some(format!("segment {idx} ({} MB {what}): {e}", len >> 20)); + break; + } + } + } + ungroom(groomed); + if let Some(why) = fail { + return Err(restore(why, placed, placeholders)); + } + + // one reserved buffer over the window, its 64 KiB tiles mapped onto the segments' heaps + let reserved = (|| -> Result { + let mut res: Option = None; + device.CreateReservedResource(&buffer_desc(size), D3D12_RESOURCE_STATE_COMMON, None, &mut res).map_err(|e| format!("CreateReservedResource: {e}"))?; + let res = res.ok_or("CreateReservedResource")?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .map_err(|e| format!("CreateCommandQueue: {e}"))?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| format!("CreateFence: {e}"))?; + for (off, len, _, heap, _) in &placed { + let count = (*len / TILE) as u32; + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: (*off / TILE) as u32, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: count, UseBox: false.into(), ..Default::default() }; + let flag = D3D12_TILE_RANGE_FLAG_NONE; + queue.UpdateTileMappings(&res, 1, Some(&coord), Some(®ion), heap, 1, Some(&flag), Some(&0u32), Some(&count), D3D12_TILE_MAPPING_FLAG_NONE); + } + queue.Signal(&fence, 1).map_err(|e| format!("Signal: {e}"))?; + crate::gpu::fence::wait(&fence, 1, device, None, 2000).map_err(|e| format!("tile mapping wait: {e}"))?; + Ok(res) + })(); + let res = match reserved { + Ok(r) => r, + Err(why) => return Err(restore(why, placed, placeholders)), + }; + + for (a, bytes) in &pages { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), *a as *mut u8, bytes.len()); + } + let mut parts = Vec::with_capacity(placed.len()); + let mut heaps = Vec::with_capacity(placed.len()); + let mut watched = Vec::new(); + for (off, len, upload, heap, placed_buf) in placed { + parts.push(format!("{off:#x}+{}MB {}", len >> 20, if upload { "GPU_UPLOAD" } else { "CUSTOM, write-watched" })); + if !upload { + watched.push((base + off, len)); + } + heaps.push((off, len, heap.into_raw() as usize)); + // the segment's CPU mapping lives as long as its buffer: kept for the process + std::mem::forget(placed_buf); + } + crate::xlog_info!( + "D3D12.X: the coherent window at {base:#x} ({} MB) is mixed driver heaps mapped at its address [{}] ({reservations} reservations, {} pages kept, {} KB, {} ms)", + size >> 20, + parts.join(", "), + pages.len(), + kept >> 10, + t0.elapsed().as_millis() + ); + let vram: Vec<(usize, usize)> = spec.iter().filter(|s| s.2).map(|&(off, len, _)| (base + off, base + off + len)).collect(); + init_vram_reader(device, base, size, &res, vram); + let gpu_va = res.GetGPUVirtualAddress(); + Ok(Remade { buf_raw: res.into_raw() as usize, gpu_va, heaps, watched_regions: Some(watched) }) +} + +static VRAM_READER_ACTIVE: AtomicBool = AtomicBool::new(false); +static VRAM_READER: Mutex> = Mutex::new(None); + +/// Reads the `GPU_UPLOAD` segments of a mixed window by a copy on the GPU into a readback buffer. +struct VramReader { + window_base: usize, + window_end: usize, + vram_ranges: Vec<(usize, usize)>, + device: ID3D12Device, + src_buf: ID3D12Resource, + queue: ID3D12CommandQueue, + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + fence_val: u64, + readback: ID3D12Resource, + readback_ptr: *mut u8, + readback_cap: usize, +} + +unsafe impl Send for VramReader {} + +unsafe fn make_readback(device: &ID3D12Device, cap: usize) -> Result<(ID3D12Resource, *mut u8), String> { + let mut rb: Option = None; + let desc = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_NONE, ..buffer_desc(cap) }; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut rb, + ) + .map_err(|e| format!("readback CreateCommittedResource({cap}): {e}"))?; + let rb = rb.ok_or("readback")?; + let mut p: *mut c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(|e| format!("readback Map: {e}"))?; + Ok((rb, p as *mut u8)) +} + +unsafe fn init_vram_reader(device: &ID3D12Device, window_base: usize, window_size: usize, src_buf: &ID3D12Resource, vram_ranges: Vec<(usize, usize)>) { + let made = (|| -> Result { + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COPY, ..Default::default() }) + .map_err(|e| format!("copy queue: {e}"))?; + let alloc: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).map_err(|e| format!("copy allocator: {e}"))?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &alloc, None).map_err(|e| format!("copy list: {e}"))?; + list.Close().map_err(|e| format!("copy list Close: {e}"))?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| format!("copy fence: {e}"))?; + let cap = 32 << 20; + let (readback, readback_ptr) = make_readback(device, cap)?; + Ok(VramReader { + window_base, + window_end: window_base + window_size, + vram_ranges, + device: device.clone(), + src_buf: src_buf.clone(), + queue, + alloc, + list, + fence, + fence_val: 0, + readback, + readback_ptr, + readback_cap: cap, + }) + })(); + match made { + Ok(r) => { + *VRAM_READER.lock().unwrap() = Some(r); + VRAM_READER_ACTIVE.store(true, Ordering::Release); + } + Err(e) => crate::xlog_warn!("D3D12.X: no GPU reader for the mixed window's GPU_UPLOAD segments ({e}): they are read through the BAR"), + } +} + +/// `[at, at + len)` read by a copy on the GPU (`CopyBufferRegion` to a readback buffer) where it +/// overlaps a `GPU_UPLOAD` segment of a mixed window: CPU reads of that video memory through the +/// BAR ran at 12-84 MiB/s. None where it does not. +pub(super) unsafe fn read_vram_bytes(at: usize, len: usize) -> Option> { + if len == 0 || !VRAM_READER_ACTIVE.load(Ordering::Acquire) { + return None; + } + let mut g = VRAM_READER.lock().unwrap(); + let r = g.as_mut()?; + let end = at.checked_add(len)?; + if at < r.window_base || end > r.window_end || !r.vram_ranges.iter().any(|&(s, e)| at < e && end > s) { + return None; + } + if len > r.readback_cap { + let cap = len.next_power_of_two().max(32 << 20); + let (rb, ptr) = make_readback(&r.device, cap).ok()?; + r.readback.Unmap(0, None); + r.readback = rb; + r.readback_ptr = ptr; + r.readback_cap = cap; + } + r.alloc.Reset().ok()?; + r.list.Reset(&r.alloc, None).ok()?; + r.list.CopyBufferRegion(&r.readback, 0, &r.src_buf, (at - r.window_base) as u64, len as u64); + r.list.Close().ok()?; + let cl: ID3D12CommandList = r.list.cast().ok()?; + r.queue.ExecuteCommandLists(&[Some(cl)]); + r.fence_val += 1; + r.queue.Signal(&r.fence, r.fence_val).ok()?; + crate::gpu::fence::wait(&r.fence, r.fence_val, &r.device, None, 5000).ok()?; + let mut out = vec![0u8; len]; + std::ptr::copy_nonoverlapping(r.readback_ptr, out.as_mut_ptr(), len); + Some(out) } #[cfg(test)] mod tests { - use super::decide; + use super::{build_segments, decide, parse_mixed}; + + /// Set in the process of its own a mixed remake test runs in (`ran_alone`). + const ALONE: &str = "XCL_TEST_MIXED_REMAKE"; + + /// The test `name` run again in a process of its own and passed: true in the first process, + /// which has nothing more to do; false in the process of its own, which goes on with the test. + /// A mixed remake reserves every other free stretch of the process so that the driver maps + /// each segment at its place. Beside the other GPU tests (4 test threads, `uma` as the filter) + /// their allocations failed meanwhile, and one of them took a segment's place: its CreateHeap + /// failed (E_OUTOFMEMORY) after a segment was mapped, and the window could not be made again. + fn ran_alone(name: &str) -> bool { + if std::env::var_os(ALONE).is_some() { + return false; + } + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name, "--nocapture", "--test-threads=1"]) + .env(ALONE, "1") + .output() + .unwrap(); + let transcript = format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(output.status.success() && transcript.contains("1 passed"), "{transcript}"); + true + } /// On by default for NVIDIA outside Wine only; the switch overrides either way. #[test] @@ -242,6 +674,82 @@ mod tests { assert!(!decide(Some("0"), || false, || Some(0x10DE))); assert!(decide(Some("custom"), || true, || Some(0x1002))); assert!(decide(Some(" 1 "), || false, || None)); + assert!(decide(Some("mixed:1536:1792"), || true, || Some(0x1002))); + } + + #[test] + fn mixed_ranges_parse_in_order() { + assert_eq!(parse_mixed("mixed:1536:1792"), Some(vec![(1536 << 20, 1792 << 20)])); + assert_eq!(parse_mixed(" mixed:2048:512,512:256 "), Some(vec![(512 << 20, 256 << 20), (2048 << 20, 512 << 20)])); + assert_eq!(parse_mixed("mixed:0:0"), None); + assert_eq!(parse_mixed("mixed:12"), None); + assert_eq!(parse_mixed("custom"), None); + } + + #[test] + fn mixed_segments_cover_the_window() { + let segs = build_segments(4095 << 20, &[(1536 << 20, 1792 << 20)]).unwrap(); + assert_eq!(segs, vec![(0, 1536 << 20, false), (1536 << 20, 1792 << 20, true), (3328 << 20, 767 << 20, false)]); + assert!(build_segments(256 << 20, &[(512 << 20, 64 << 20)]).is_err()); + assert!(build_segments(256 << 20, &[(0, 128 << 20), (64 << 20, 64 << 20)]).is_err()); + } + + /// A mixed window keeps the title's bytes in every segment, and the GPU reads the CPU's later + /// writes to each segment through the one reserved buffer; `read_vram_bytes` reads only the + /// `GPU_UPLOAD` segment. + #[test] + fn mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + // (through the Agility SDK when there is one, as the runtime's device: the inbox D3D12 of + // Windows 11 23H2 has no GPU_UPLOAD heaps) + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + }; + if !unsafe { gpu_upload_heaps(&dev) } { + return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heaps"); + } + if ran_alone("hle::d3d12x::uma_driver::tests::mixed_window_keeps_its_bytes_and_the_gpu_sees_every_segment") { + return; + } + unsafe { + let size = 256 << 20; + let base = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let at = [0x1000, (64 << 20) + 0x1000, (192 << 20) + 0x1000]; + for (i, &o) in at.iter().enumerate() { + std::ptr::write_volatile((base + o) as *mut u32, 0x1111_0000 + i as u32); + } + let remade = match remake_mixed(&dev, base, size, &[(64 << 20, 128 << 20)]) { + Ok(r) => r, + Err(e) if e.contains("CreateHeap") => return crate::gpu::recomp::runner::skip_test("no GPU_UPLOAD heaps"), + Err(e) => panic!("remake_mixed: {e}"), + }; + assert_eq!(remade.heaps.len(), 3); + assert_eq!(remade.watched_regions, Some(vec![(base, 64 << 20), (base + (192 << 20), 64 << 20)])); + for (i, &o) in at.iter().enumerate() { + assert_eq!(std::ptr::read_volatile((base + o) as *const u32), 0x1111_0000 + i as u32); + std::ptr::write_volatile((base + o + 0x1000) as *mut u32, 0xCAFE_0000 + i as u32); + } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (rb, ptr) = make_readback(&dev, 256).unwrap(); + let raw = remade.buf_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + for (i, &o) in at.iter().enumerate() { + list.CopyBufferRegion(&rb, 4 * i as u64, src, (o + 0x1000) as u64, 4); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + assert_eq!(std::slice::from_raw_parts(ptr as *const u32, 3), &[0xCAFE_0000, 0xCAFE_0001, 0xCAFE_0002]); + assert!(read_vram_bytes(base + at[0] + 0x1000, 4).is_none()); + let got = read_vram_bytes(base + at[1] + 0x1000, 4).expect("read of the GPU_UPLOAD segment"); + assert_eq!(u32::from_le_bytes(got.try_into().unwrap()), 0xCAFE_0001); + } } #[test] From e8767e8e5961a6b76147a3ec64dc83a133c3e21e Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:39:19 +0100 Subject: [PATCH 036/175] D3D12.X: XCL_UMA_DRIVER=mixed applies to the first coherent window only Port of upstream b3d63124. With 16 windows the coherent memory can be several windows (upstream: 4095 + 999 MB for a retail title's 4582 MB of GPU heaps). The mixed ranges are offsets in the first one; in a second, smaller window they had no overlap, the remake failed with "no GPU_UPLOAD range inside the window" and the window stayed imported. Further coherent windows are one CUSTOM heap each. Nothing adapted: open_uma passes whether window k is Uma::committed_window. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 2 +- crates/xcl/src/hle/d3d12x/uma_driver.rs | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index eba34d11ce..e9922b3abc 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -419,7 +419,7 @@ unsafe fn open_uma(device: &ID3D12Device, allow_driver_remap: bool) { } if allow_driver_remap && shadow_choice() != Some(true) && super::uma_driver::wanted(device) { let (base, size) = u.window(k); - match super::uma_driver::remake_window(device, base, size) { + match super::uma_driver::remake_window(device, base, size, u.committed_window() == Some(k)) { Ok(remade) => { u.set_driver_window(k); if let Some(segs) = remade.watched_regions { diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs index 662c6378cc..e778e730d3 100644 --- a/crates/xcl/src/hle/d3d12x/uma_driver.rs +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -270,9 +270,10 @@ pub(super) struct Remade { } /// `remake`, or `remake_mixed` with `XCL_UMA_DRIVER=mixed:...` on an adapter with `GPU_UPLOAD` -/// heaps. -pub(super) unsafe fn remake_window(device: &ID3D12Device, base: usize, size: usize) -> Result { - if let Some(ranges) = mixed_ranges() { +/// heaps when `first` (the ranges are those of the first coherent window; a 16-window layout's +/// further ones are one CUSTOM heap each). +pub(super) unsafe fn remake_window(device: &ID3D12Device, base: usize, size: usize, first: bool) -> Result { + if let Some(ranges) = mixed_ranges().filter(|_| first) { if gpu_upload_heaps(device) { return remake_mixed(device, base, size, &ranges); } From 61559df6ffe16b37e1092ea67e8515433f414d6b Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:42:50 +0100 Subject: [PATCH 037/175] D3D12.X: XCL_UMA_DRIVER=mixed makes a refused GPU_UPLOAD segment CUSTOM Port of the rest of upstream 2fc61b64 ("XCL_UMA_DRIVER=mixed falls back without GPU_UPLOAD heaps"); its adapter check, asked before the window is released, went in with the mixed window itself. A GPU_UPLOAD segment refused anyway (out of BAR space, or Map placing it elsewhere) becomes a write-watched CUSTOM segment in place: a mapped segment's pages stay with the driver after its heap is dropped, so the old rollback could not reserve the window again (Windows error 487) and stopped the process. Without a GPU_UPLOAD segment left there is no GPU reader. On an RX 9070 XT (inbox D3D12, no GPU_UPLOAD heaps) the new test, a_refused_gpu_upload_segment_becomes_custom, passes: three CUSTOM segments mapped at their places, the GPU reads the CPU's writes to each through the one reserved buffer. Without the change it fails with "could not be restored ... Windows error 487". Adapted: upstream had its two mixed remake tests take one lock (side by side with 4 test threads one remake's release of its reservations let the other's segment map elsewhere). Here each runs in a process of its own (ran_alone, from the first commit), which also keeps the other GPU tests away from the grooming: with `uma` as the filter and 4 threads, the lock alone was not enough (a CUSTOM segment's CreateHeap failed with E_OUTOFMEMORY after another was mapped, and gpu::recomp's UMA tests failed their own allocations). The test makes its device through the Agility SDK when there is one. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/uma_driver.rs | 88 +++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs index e778e730d3..c20ada969c 100644 --- a/crates/xcl/src/hle/d3d12x/uma_driver.rs +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -296,6 +296,12 @@ unsafe fn gpu_upload_heaps(device: &ID3D12Device) -> bool { && opts.GPUUploadHeapSupported.as_bool() } +#[cfg(test)] +thread_local! { + /// tests: `mapped_segment` refuses `GPU_UPLOAD` heaps on this thread + static REFUSE_GPU_UPLOAD: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + fn heap_props(upload: bool) -> D3D12_HEAP_PROPERTIES { if upload { D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_GPU_UPLOAD, ..Default::default() } @@ -326,6 +332,10 @@ fn buffer_desc(size: usize) -> D3D12_RESOURCE_DESC { /// One segment of a mixed window: a heap of `size` bytes (write-watched when `watch`), a buffer /// over all of it and where the driver mapped it for the CPU. unsafe fn mapped_segment(device: &ID3D12Device, size: usize, upload: bool, watch: bool) -> Result<(ID3D12Heap, ID3D12Resource, usize), String> { + #[cfg(test)] + if upload && REFUSE_GPU_UPLOAD.with(|r| r.get()) { + return Err("CreateHeap: refused by the test".into()); + } let flags = if watch { D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | D3D12_HEAP_FLAG_ALLOW_WRITE_WATCH } else { D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS }; let desc = D3D12_HEAP_DESC { SizeInBytes: size as u64, Properties: heap_props(upload), Alignment: 0x1_0000, Flags: flags }; let mut heap: Option = None; @@ -441,7 +451,6 @@ unsafe fn remake_mixed(device: &ID3D12Device, base: usize, size: usize, vram_ran let mut fail: Option = None; for (idx, &(off, len, upload)) in spec.iter().enumerate() { let want = base + off; - let what = if upload { "GPU_UPLOAD" } else { "CUSTOM" }; let ph = std::mem::replace(&mut placeholders[idx], 0); if VirtualFree(ph as *mut c_void, 0, MEM_RELEASE) == 0 { fail = Some(format!("VirtualFree of the placeholder at {want:#x} failed")); @@ -449,7 +458,25 @@ unsafe fn remake_mixed(device: &ID3D12Device, base: usize, size: usize, vram_ran } // (no write watch on GPU_UPLOAD: its write-combined pages refuse a watch trap's // read-only protection, which then retried tens of thousands of times) - match mapped_segment(device, len, upload, !upload) { + let mut made = mapped_segment(device, len, upload, !upload); + let mut upload = upload; + if upload && !matches!(&made, Ok((_, _, p)) if *p == want) { + // a refused GPU_UPLOAD segment becomes a CUSTOM one: the segments mapped so far cannot + // be given back (their mappings stay with the driver), so the window is kept whole + let why = match &made { + Ok((_, _, p)) => format!("Map gave {p:#x}"), + Err(e) => e.clone(), + }; + if let Ok((heap, buf, _)) = std::mem::replace(&mut made, Err(String::new())) { + buf.Unmap(0, None); + drop((buf, heap)); + } + crate::xlog_warn!("D3D12.X: XCL_UMA_DRIVER=mixed: segment {idx} ({} MB GPU_UPLOAD): {why}; it is a CUSTOM write-watched heap instead", len >> 20); + upload = false; + made = mapped_segment(device, len, false, true); + } + let what = if upload { "GPU_UPLOAD" } else { "CUSTOM" }; + match made { Ok((heap, buf, p)) if p == want && (upload || readable(want, len)) => placed.push((off, len, upload, heap, buf)), Ok((heap, buf, p)) => { buf.Unmap(0, None); @@ -503,6 +530,7 @@ unsafe fn remake_mixed(device: &ID3D12Device, base: usize, size: usize, vram_ran let mut parts = Vec::with_capacity(placed.len()); let mut heaps = Vec::with_capacity(placed.len()); let mut watched = Vec::new(); + let heaps_upload: Vec<(usize, usize)> = placed.iter().filter(|p| p.2).map(|p| (p.0, p.1)).collect(); for (off, len, upload, heap, placed_buf) in placed { parts.push(format!("{off:#x}+{}MB {}", len >> 20, if upload { "GPU_UPLOAD" } else { "CUSTOM, write-watched" })); if !upload { @@ -520,8 +548,10 @@ unsafe fn remake_mixed(device: &ID3D12Device, base: usize, size: usize, vram_ran kept >> 10, t0.elapsed().as_millis() ); - let vram: Vec<(usize, usize)> = spec.iter().filter(|s| s.2).map(|&(off, len, _)| (base + off, base + off + len)).collect(); - init_vram_reader(device, base, size, &res, vram); + let vram: Vec<(usize, usize)> = heaps_upload.iter().map(|&(off, len)| (base + off, base + off + len)).collect(); + if !vram.is_empty() { + init_vram_reader(device, base, size, &res, vram); + } let gpu_va = res.GetGPUVirtualAddress(); Ok(Remade { buf_raw: res.into_raw() as usize, gpu_va, heaps, watched_regions: Some(watched) }) } @@ -753,6 +783,56 @@ mod tests { } } + /// A `GPU_UPLOAD` segment refused after a CUSTOM one was mapped (an adapter without Resizable + /// BAR, or one out of BAR space): the window stays whole, that segment a write-watched CUSTOM + /// heap. (It stopped the process: the mapped segment's pages stay with the driver after its + /// heap is dropped, so the window could not be reserved again.) + #[test] + fn a_refused_gpu_upload_segment_becomes_custom() { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no D3D12 device"); + }; + if ran_alone("hle::d3d12x::uma_driver::tests::a_refused_gpu_upload_segment_becomes_custom") { + return; + } + unsafe { + let size = 256 << 20; + let base = VirtualAlloc(std::ptr::null(), size, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let at = [0x1000, (64 << 20) + 0x1000, (192 << 20) + 0x1000]; + for (i, &o) in at.iter().enumerate() { + std::ptr::write_volatile((base + o) as *mut u32, 0x2222_0000 + i as u32); + } + REFUSE_GPU_UPLOAD.with(|r| r.set(true)); + let remade = remake_mixed(&dev, base, size, &[(64 << 20, 128 << 20)]); + REFUSE_GPU_UPLOAD.with(|r| r.set(false)); + let remade = remade.expect("remake_mixed with the GPU_UPLOAD segment refused"); + assert_eq!(remade.heaps.len(), 3); + assert_eq!(remade.watched_regions, Some(vec![(base, 64 << 20), (base + (64 << 20), 128 << 20), (base + (192 << 20), 64 << 20)])); + for (i, &o) in at.iter().enumerate() { + assert_eq!(std::ptr::read_volatile((base + o) as *const u32), 0x2222_0000 + i as u32); + std::ptr::write_volatile((base + o + 0x1000) as *mut u32, 0xBEEF_0000 + i as u32); + } + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (rb, ptr) = make_readback(&dev, 256).unwrap(); + let raw = remade.buf_raw as *mut c_void; + let src = ID3D12Resource::from_raw_borrowed(&raw).unwrap(); + for (i, &o) in at.iter().enumerate() { + list.CopyBufferRegion(&rb, 4 * i as u64, src, (o + 0x1000) as u64, 4); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 2000).unwrap(); + assert_eq!(std::slice::from_raw_parts(ptr as *const u32, 3), &[0xBEEF_0000, 0xBEEF_0001, 0xBEEF_0002]); + } + } + #[test] fn failed_write_watch_does_not_release_the_original_window() { use super::*; From aaf42bd313e2308a0560e26ebe4eba1fa288cf15 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:45:03 +0100 Subject: [PATCH 038/175] D3D12.X: a console buffer across two segments of a mixed window takes the next fit Port of upstream 39557fa1. place_console_buffer returned through '?' when the block it got lay across two heaps of a mixed window, leaving the block charged to the window. The block is now held while the next fit is tried (up to four) and given back either way (alloc_in_one_heap, with upstream's test). With one heap per window every block has its heap at the first try, as before. Nothing adapted. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 50 +++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e9922b3abc..12b0e090d8 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1662,6 +1662,27 @@ const COHERENT_CUSTOM_WB_MAX: usize = 16 << 20; /// arena pool) const COHERENT_FLOOR: usize = 16 << 20; +/// A block of `size` bytes from `u` that one heap holds (`heap_of(p)`). A block across two +/// segments of a mixed window has none: it is held while the next fit is tried (which then starts +/// past it), and given back either way. +fn alloc_in_one_heap(u: &crate::gpu::uma::Uma, size: usize, heap_of: impl Fn(usize) -> Option) -> Option<(usize, T)> { + let mut held = Vec::new(); + let found = loop { + let Some(p) = u.alloc(size, 0x1_0000).map(|a| a as usize) else { break None }; + if let Some(h) = heap_of(p) { + break Some((p, h)); + } + held.push(p); + if held.len() == 4 { + break None; + } + }; + for p in held { + u.free(p); + } + found +} + /// Whether a readback heap / buffer of `rounded` bytes may take coherent memory. The room /// committed textures leave (`COHERENT_KEPT`) is kept for these: with the textures at that /// limit (Unicorn Overlord's), a second 128 MB of headroom sent every readback buffer to the @@ -1758,16 +1779,15 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return Some(hr); } } - let Some(p) = u.alloc(rounded, 0x1_0000).map(|a| a as usize) else { + let heap_of = |p: usize| u.window_of(p).and_then(|k| uma_heap_for(k, p - u.window(k).0, rounded).map(|h| (k, h))); + let Some((p, (k, (heap, heap_off)))) = alloc_in_one_heap(u, rounded, heap_of) else { if prefer_coherent && u.has_sparse() { return place_console_buffer_sparse(this, &d, bytes, st, readback_on_null_map, riid, ppv); } return None; }; // the heap from OpenExistingHeapFromAddress is cross-adapter: row-major + sanitized flags & state - let k = u.window_of(p)?; let (d, st) = sanitize_coherent_buffer(&d, state, !u.is_driver_window(k)); - let (heap, heap_off) = uma_heap_for(k, p - u.window(k).0, d.Width as usize)?; let hr = dev_create_placed_resource(this, heap, heap_off, &d as *const _ as usize, st as usize, clear, riid, ppv); if hr < 0 || (*ppv).is_null() { u.free(p); @@ -12949,3 +12969,27 @@ mod depth_uav_twin_tests { } } } + +#[cfg(test)] +mod uma_heap_tests { + use super::*; + + /// A console buffer whose first fit crosses two segments of a mixed window goes to the next + /// fit, and the crossing block is given back (it stayed charged to the window). + #[test] + fn a_block_across_two_segments_is_given_back_and_the_next_fit_used() { + let u = crate::gpu::uma::Uma::with_windows(1, 4 << 20).expect("one UMA window"); + let (w0, _) = u.window(0); + let first = u.alloc(960 << 10, 0x1_0000).expect("first block") as usize; + assert_eq!(first, w0); + let used = u.used(); + let boundary = w0 + (1 << 20); + let heap_of = |p: usize| (p + (128 << 10) <= boundary || p >= boundary).then_some(()); + let (p, ()) = alloc_in_one_heap(&u, 128 << 10, heap_of).expect("a block in one segment"); + assert_eq!(p, w0 + (1088 << 10)); + assert_eq!(u.used(), used + (128 << 10)); + assert_eq!(u.alloc(64 << 10, 0x1_0000).map(|a| a as usize), Some(w0 + (960 << 10))); + assert!(alloc_in_one_heap(&u, 64 << 10, |_| None::<()>).is_none()); + assert_eq!(u.used(), used + (192 << 10)); + } +} From feeb016987b6b84754e0432ce3be00804cf23de5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:46:40 +0100 Subject: [PATCH 039/175] D3D12.X: XCL_UMA_UPLOAD_PRIORITY=1 keeps a mixed window's GPU_UPLOAD segment resident Port of upstream da9c69f7. Over its video memory budget, Windows demotes heaps to system memory; upstream (1.9 GB over) saw in a live ETW timeline one demoted heap of 1792 MiB, the size of the coherent window's GPU_UPLOAD segment. The switch gives that heap D3D12_RESIDENCY_PRIORITY_MAXIMUM so other heaps go first. Opt-in, and only for a mixed window's GPU_UPLOAD segments; built, not run here (the inbox D3D12 on this machine makes no GPU_UPLOAD heaps). Nothing adapted. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/uma_driver.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/uma_driver.rs b/crates/xcl/src/hle/d3d12x/uma_driver.rs index c20ada969c..b2343411b4 100644 --- a/crates/xcl/src/hle/d3d12x/uma_driver.rs +++ b/crates/xcl/src/hle/d3d12x/uma_driver.rs @@ -329,6 +329,14 @@ fn buffer_desc(size: usize) -> D3D12_RESOURCE_DESC { } } +/// `XCL_UMA_UPLOAD_PRIORITY=1` (read once): the `GPU_UPLOAD` segments of a mixed window get +/// `D3D12_RESIDENCY_PRIORITY_MAXIMUM`, so Windows demotes other heaps first when the process is +/// over its video memory budget. +fn upload_priority_wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_UMA_UPLOAD_PRIORITY").is_ok_and(|v| v.trim() == "1")) +} + /// One segment of a mixed window: a heap of `size` bytes (write-watched when `watch`), a buffer /// over all of it and where the driver mapped it for the CPU. unsafe fn mapped_segment(device: &ID3D12Device, size: usize, upload: bool, watch: bool) -> Result<(ID3D12Heap, ID3D12Resource, usize), String> { @@ -341,6 +349,18 @@ unsafe fn mapped_segment(device: &ID3D12Device, size: usize, upload: bool, watch let mut heap: Option = None; device.CreateHeap(&desc, &mut heap).map_err(|e| format!("CreateHeap{}: {e}", if watch { " (write-watched)" } else { "" }))?; let heap = heap.ok_or("CreateHeap")?; + if upload && upload_priority_wanted() { + // (a process over its video memory budget has heaps demoted to system memory: not this one, + // which every console program reads its buffers from) + let set = device.cast::().and_then(|d| { + let obj: ID3D12Pageable = heap.cast()?; + d.SetResidencyPriority(1, &Some(obj), &D3D12_RESIDENCY_PRIORITY_MAXIMUM) + }); + match set { + Ok(()) => crate::xlog_info!("D3D12.X: XCL_UMA_UPLOAD_PRIORITY: the {} MB GPU_UPLOAD segment has the highest residency priority", size >> 20), + Err(e) => crate::xlog_warn!("D3D12.X: XCL_UMA_UPLOAD_PRIORITY: SetResidencyPriority: {e}"), + } + } let mut buf: Option = None; device.CreatePlacedResource(&heap, 0, &buffer_desc(size), D3D12_RESOURCE_STATE_COMMON, None, &mut buf).map_err(|e| format!("CreatePlacedResource: {e}"))?; let buf = buf.ok_or("CreatePlacedResource")?; From 91122ee9f2f037d33e2f383dd968fe80cd5cb387 Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:46:00 +0000 Subject: [PATCH 040/175] Recompiler: the DXIL cache key leaves out comments and indentation A cold preparation compiled byte-identical DXIL many times: 43 % of its DXC compiles. Each console record starts with two data words, shown in the HLSL as `// 0000: v_nop ; lit 0x...` / `// 000c: ...` comments; they differ per record (an identifier, not code), so programs with the same code had different HLSL text and the key, the full text, differed. Measured (`xcl shaders shaders.rpf --precompile --limit 1500`, a retail game's pack, fresh cache): main wrote 1,601 DXIL files with 919 distinct contents (CS 538 and VS 144 copies); in every identical group the sources differed only in those comment lines. With this change: 919 files, the same 919 contents byte for byte. The key now hashes the code lines: comments (outside string literals) become a space, lines are trimmed, empty lines dropped; line breaks and spaces inside a line stay. DXC still compiles the full text, so its output is unchanged. Only below 960 KiB of source: from 1 MiB the length, comments included, picks the -O level (compile_with, link_opt_args), so longer sources keep the full-text key (the same key as before). A source with a backslash-newline keeps it too (a `//` comment would go on to the next line). Keys of shorter sources change once: their DXIL is compiled again on the first run. Builds on the idea of #1582 (closed), which stripped comments for the -O choice but kept the full-text key. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/dxc.rs | 163 +++++++++++++++++++++++++++++- crates/xcl/src/gpu/recomp/emit.rs | 2 +- 2 files changed, 159 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index d29d1a50b5..c3790af223 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -937,15 +937,116 @@ pub(super) fn toolchain_identity() -> &'static str { }) } -/// FNV-1a 64 of the inputs that determine the DXIL. +/// Sources shorter than this are keyed without their comments and indentation +/// (`hash_code_lines`). Up to 1 MiB DXC gets no -O switch (`compile_with`, `link_opt_args`), so +/// two such sources with the same code lines get the same DXC arguments and the same DXIL; the +/// margin covers a linked program's declarations (`emit::linked_form`, a few KB) on top of its +/// source. Longer sources are keyed on their full text: their length, comments included, picks +/// the -O level. +const KEY_CODE_LINES_BELOW: usize = 1024 * 1024 - 64 * 1024; + +/// FNV-1a 64 of the inputs that determine the DXIL. DXC still compiles the full `src`; the key +/// leaves out what does not reach the DXIL, so programs that differ only in their +/// `// pc: instruction` comments (data words, other offsets) share one compile. fn cache_key_for_toolchain(src: &str, entry: &str, profile: &str, toolchain: &str) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; - for part in [env!("CARGO_PKG_VERSION"), toolchain, profile, entry, src] { - for b in part.bytes().chain([0u8]) { - h ^= b as u64; - h = h.wrapping_mul(0x100_0000_01b3); + // a backslash-newline splices lines before comments end (a `// …\` comment goes on): + // such a source keeps the full-text key + let code_lines = src.len() < KEY_CODE_LINES_BELOW && !src.contains("\\\n") && !src.contains("\\\r\n"); + let parts: [&str; 4] = [env!("CARGO_PKG_VERSION"), toolchain, profile, entry]; + let full = [src]; + let tag = ["code lines"]; + for part in parts.iter().chain(if code_lines { &tag[..] } else { &full[..] }) { + h = fnv_bytes(h, part.bytes().chain([0u8])); + } + if code_lines { + h = hash_code_lines(h, src); + } + h +} + +fn fnv_bytes(mut h: u64, bytes: impl Iterator) -> u64 { + for b in bytes { + h ^= b as u64; + h = h.wrapping_mul(0x100_0000_01b3); + } + h +} + +/// Hash `src` as DXC's preprocessor sees it, less what cannot change the DXIL: `//` and `/* */` +/// comments (outside string literals) become a space, every line is trimmed, and empty lines are +/// left out. Lines stay separate, so preprocessor directives keep their extent. For a source +/// without backslash-newlines (`cache_key_for_toolchain`). +fn hash_code_lines(mut h: u64, src: &str) -> u64 { + let mut line: Vec = Vec::with_capacity(256); + let (mut in_block, mut in_string) = (false, false); + let mut flush = |h: &mut u64, line: &mut Vec| { + let start = line.iter().position(|b| !b.is_ascii_whitespace()); + if let Some(start) = start { + let end = line.iter().rposition(|b| !b.is_ascii_whitespace()).map_or(start, |e| e + 1); + *h = fnv_bytes(*h, line[start..end].iter().copied().chain([b'\n'])); + } + line.clear(); + }; + let b = src.as_bytes(); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if in_block { + if c == b'*' && b.get(i + 1) == Some(&b'/') { + in_block = false; + line.push(b' '); + i += 2; + continue; + } + // a newline inside a block comment still ends the line + if c == b'\n' { + flush(&mut h, &mut line); + } + i += 1; + continue; + } + if in_string { + line.push(c); + if c == b'\\' { + if let Some(&n) = b.get(i + 1) { + line.push(n); + i += 2; + continue; + } + } else if c == b'"' || c == b'\n' { + in_string = false; + if c == b'\n' { + line.pop(); + flush(&mut h, &mut line); + } + } + i += 1; + continue; } + match c { + b'/' if b.get(i + 1) == Some(&b'/') => { + while i < b.len() && b[i] != b'\n' { + i += 1; + } + line.push(b' '); + continue; + } + b'/' if b.get(i + 1) == Some(&b'*') => { + in_block = true; + i += 2; + continue; + } + b'"' => { + in_string = true; + line.push(c); + } + b'\n' => flush(&mut h, &mut line), + _ => line.push(c), + } + i += 1; } + flush(&mut h, &mut line); h } @@ -1219,6 +1320,9 @@ where F: FnOnce() -> Result, String>, { let key = cache_key(src, entry, profile); + if let Some(d) = std::env::var_os("XCL_DXC_SOURCE_DUMP") { + let _ = std::fs::write(Path::new(&d).join(format!("{key:016x}.{profile}.hlsl")), src); + } let dir = normalized_cache_dir(dir); let file = dir.join(format!("{key:016x}.dxil")); let err_file = dir.join(format!("{key:016x}.err")); @@ -1479,6 +1583,55 @@ mod cache_tests { assert_ne!(a, cache_key_for_toolchain("source", "main", "cs_6_6", "compiler-a/signer-b")); } + #[test] + fn cache_key_leaves_out_comments_and_indentation() { + let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "tc"); + let a = "// generated by XCL\n[numthreads(64, 1, 1)]\nvoid main()\n{\n // 0000: v_nop ; lit 0x1\n uint s0 = io.Load(0u); // the first SGPR\n /* a\n block */ io.Store(0u, s0);\n}\n"; + let b = "// generated by XCL\n[numthreads(64, 1, 1)]\nvoid main()\n{\n // 0000: v_nop ; lit 0x2\n\n uint s0 = io.Load(0u);\n io.Store(0u, s0); \n}"; + assert_eq!(key(a), key(b), "programs that differ only in comments and whitespace around lines share a key"); + // what reaches the DXIL keeps keys apart + assert_ne!(key(a), key(&a.replace("io.Load(0u)", "io.Load(4u)"))); + assert_ne!(key(a), key(&a.replace("uint s0", "uint s0")), "spaces inside a line are kept"); + assert_ne!(key(a), key(&a.replace("[numthreads(64, 1, 1)]\nvoid", "[numthreads(64, 1, 1)] void")), "line breaks are kept"); + assert_ne!(key("#define X 1\nuint y = X;\n"), key("#define X 1 uint y = X;\n")); + assert_ne!(key("[shader(\"compute\")]\n"), key("[shader(\"com//pute\")]\n"), "string literals are code"); + assert_ne!(key(a), cache_key_for_toolchain(a, "main", "cs_6_7", "tc")); + assert_ne!(key(a), cache_key_for_toolchain(a, "other", "cs_6_6", "tc")); + // a backslash-newline continues a comment: such a source keys on its full text + let spliced = "uint a = 1u; // note \\\nuint b = 2u;\n"; + assert_ne!(key(spliced), key("uint a = 1u;\n")); + assert_ne!(key(spliced), key("uint a = 1u; // other \\\nuint b = 2u;\n")); + } + + #[test] + fn cache_key_of_a_long_source_keeps_its_comments() { + // from 1 MiB the length (comments included) picks the -O level (`link_opt_args`) + let code = "uint s0 = io.Load(0u);\n"; + let mut long = String::new(); + while long.len() < KEY_CODE_LINES_BELOW { + long.push_str(code); + } + let commented = format!("// 0000: v_nop\n{long}"); + let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "tc"); + assert_ne!(key(&long), key(&commented)); + assert_eq!(key(&long), key(&long.clone())); + assert!(link_opt_args(KEY_CODE_LINES_BELOW, &[]).is_empty(), "keyed without comments only where DXC gets no -O switch"); + } + + #[test] + fn a_linked_program_stays_within_the_code_line_key_margin() { + // `compile_here` links a compute program: its -O level follows the linked program's + // length, which is the source plus the accessor declarations less the inline accessors + let inline = super::super::emit::mem_accessors(4, None); + let mut src = format!("{inline}[numthreads(64, 1, 1)]\nvoid main()\n{{\n"); + for _ in 0..LINK_MIN_ACCESSES { + src.push_str(" xcl_mStore(0u, xcl_mLoad(0u));\n"); + } + src.push_str("}\n"); + let (program, _) = super::super::emit::linked_form(&src, LINK_MIN_ACCESSES).expect("linked form"); + assert!(program.len() <= src.len() + (1024 * 1024 - KEY_CODE_LINES_BELOW), "{} > {} + margin", program.len(), src.len()); + } + #[test] fn validates_dxil_cache_structure_and_rebuilds_corruption() { let valid = synthetic_dxil(7); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 92d1e732ab..af1b0ee9ea 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -6033,7 +6033,7 @@ fn method_switch(windows: u32, w: &str, ret: &str, name: &str, args: &str, def: /// out-of-UMA pointers can never wrap onto live memory windows. /// `heap`: Some(storage class) – window k is taken from the descriptor heap /// (`Options::heap_windows`) and the same rule is one comparison before the access. -fn mem_accessors(windows: u32, heap: Option<&str>) -> String { +pub(super) fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut s = String::new(); if let Some(coherent) = heap { // one access: window k is descriptor MEM_HEAP_BASE + k; an `xcl_w` outside the windows From 3bb095a07dbd7455277413c36a749fef00d6e245 Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:46:08 +0000 Subject: [PATCH 041/175] D3D12.X: write-watch ranges merge across gaps of up to 4 MiB, not 8 Port of what remains of #2891 by Saksukella (amd-dev commits 0246ae43 and b570a92e) on main: its 4 MiB merge gap. They measured a 1.5 GiB resident write-watch benchmark at 2.28x faster with a 4 MiB gap than with amd-dev's 64 MiB; main had already gone to 8 MiB. Not ported: #2891's opt-in hot/cold 16 MiB chunk tiering and its cold sweep on resubmitted lists. Main has the tiering in another form (XCL_WATCH_HOT, on by default: a look takes the 2 MiB blocks written recently and a thread walks the rest), and #2891 forced the cold sweep only under its own opt-in switch; on main it would bring back the full look (4-7 ms) the walk replaced. With XCL_WATCH_HOT on, a look's calls use hot_gap (64 MiB); this gap shapes the watched ranges whose blocks the walk takes, and every look with XCL_WATCH_HOT=0. Main's comment puts the break-even of one call at 5-9 MiB of gap, so the effect is expected to be small either way: to be measured. Test: watch_ranges_merge_at_the_gap_limit_and_split_past_it (ranges 6 MiB apart are two scans; fails at 8 MiB). Co-authored-by: Saksukella <98151720+Saksukella@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index eb9f190e01..abd67ce736 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -3053,10 +3053,12 @@ unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result Date: Wed, 25 Nov 2026 22:26:07 +0300 Subject: [PATCH 042/175] DXIL: fix heap_structured_buffer, texture_load, and wave_all_equal feature flags Align three `Shader` op builders in `gpu/dxil/ops.rs` with DXC 1.9's validator feature-flag rules: - `heap_structured_buffer`: drop spurious `Feature::RawAndStructuredBuffers` (`ResourceDescriptorHeap` structured buffers require only `ResourceHeapIndexing`, not the static raw/structured binding flag). - `Texture` / `texture_load`: record `pub ncomp: u32` on `Texture` (set in `srv_texture` and `heap_texture`) and gate `Feature::TypedUavLoadAdditionalFormats` on `tex.uav && tex.ncomp > 1` instead of `comp != U32/I32/F32`, fixing both 1-component false positives (`UNormF32`, `SNormF32`, `F16`) and multi-component `F32`/`I32`/`U32` false negatives. - `wave_all_equal`: call `self.wave_int64(v)` matching the other typed wave helpers so `Int64Ops` and `Doubles` are declared immediately on `i64`/`f64` inputs. Part of #1401 Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/ops.rs | 10 ++--- crates/xcl/src/gpu/dxil/ops_tests.rs | 59 ++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/ops.rs b/crates/xcl/src/gpu/dxil/ops.rs index 8c1272bd14..89c9ca0ec0 100644 --- a/crates/xcl/src/gpu/dxil/ops.rs +++ b/crates/xcl/src/gpu/dxil/ops.rs @@ -219,6 +219,7 @@ pub struct Texture { pub kind: TexKind, pub uav: bool, pub comp: CompType, + pub ncomp: u32, } /// A sampler handle. @@ -626,7 +627,7 @@ impl Shader { self.bindings.push(super::shader::Binding { comp_type: comp as u32, ..super::shader::Binding::new(ResClass::Srv, space, lower, kind as u32) }); let h = self.handle_from_binding(ResClass::Srv, lower, lower, space, lower); let handle = self.annotate(h, kind as u32, typed_props(comp, ncomp)); - Texture { handle, kind, uav: false, comp } + Texture { handle, kind, uav: false, comp, ncomp } } /// Declares a cbuffer of `size` bytes at `b, space` (a /// root-constant block is the same: a small cbuffer). @@ -670,7 +671,6 @@ impl Shader { } /// A structured buffer from the heap. pub fn heap_structured_buffer(&mut self, index: Value, uav: bool, stride: u32, nonuniform: bool) -> RawUav { - self.require(Feature::RawAndStructuredBuffers); let h = self.handle_from_heap(index, false, nonuniform); let handle = self.annotate(h, kind::STRUCTURED_BUFFER | if uav { 0x1000 } else { 0 }, stride); RawUav { handle, binding: None } @@ -774,7 +774,7 @@ impl Shader { assert!(!(uav && matches!(kind, TexKind::D2MS | TexKind::D2MSArray)), "RWTexture2DMS needs SM 6.7"); let h = self.handle_from_heap(index, false, nonuniform); let handle = self.annotate(h, kind as u32 | if uav { 0x1000 } else { 0 }, typed_props(comp, ncomp)); - Texture { handle, kind, uav, comp } + Texture { handle, kind, uav, comp, ncomp } } /// A sampler from `SamplerDescriptorHeap[index]`. pub fn heap_sampler(&mut self, index: Value, comparison: bool, nonuniform: bool) -> Sampler { @@ -819,7 +819,7 @@ impl Shader { let mip = mip.unwrap_or_else(|| self.m.undef(i32)); let c = self.padded(coords, 3, i32); let o = if offs.is_empty() { self.padded(&[], 3, i32) } else { self.offsets(tex.kind, offs, 3) }; - if tex.uav && tex.comp != CompType::U32 && tex.comp != CompType::I32 && tex.comp != CompType::F32 { + if tex.uav && tex.ncomp > 1 { self.require(Feature::TypedUavLoadAdditionalFormats); } let mut args = vec![tex.handle, mip]; @@ -1033,7 +1033,7 @@ impl Shader { self.op(114, "waveAllTrue", None, i1, &[cond], FnAttrs::NoUnwind) } pub fn wave_all_equal(&mut self, v: Value) -> Value { - self.require(Feature::WaveOps); + self.wave_int64(v); let t = self.m.type_of(v); let i1 = self.m.i1(); self.op(115, "waveActiveAllEqual", Some(t), i1, &[v], FnAttrs::NoUnwind) diff --git a/crates/xcl/src/gpu/dxil/ops_tests.rs b/crates/xcl/src/gpu/dxil/ops_tests.rs index f38723bf86..be6626c964 100644 --- a/crates/xcl/src/gpu/dxil/ops_tests.rs +++ b/crates/xcl/src/gpu/dxil/ops_tests.rs @@ -1308,3 +1308,62 @@ fn direct_image_atomic_64bit_validates() { assert!(dis32.contains("@dx.op.atomicCompareExchange.i32("), "32-bit cmpswap must emit i32:\n{dis32}"); assert!(!dis32.contains("@dx.op.atomicCompareExchange.i64("), "32-bit cmpswap must not emit i64:\n{dis32}"); } + +fn sfi0(c: &[u8]) -> u64 { + let n = u32::from_le_bytes(c[28..32].try_into().unwrap()) as usize; + for i in 0..n { + let off = u32::from_le_bytes(c[32 + 4 * i..36 + 4 * i].try_into().unwrap()) as usize; + if &c[off..off + 4] == b"SFI0" { return u64::from_le_bytes(c[off + 8..off + 16].try_into().unwrap()); } + } + panic!("no SFI0 part"); +} + +#[test] +fn ops_feature_flags_heap_structured_buffer() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let (x, i0, i1) = (s.thread_id_in_group(0), s.m.i32c(0), s.m.i32c(1)); + let srv = s.heap_structured_buffer(i0, false, 16, false); + let uav = s.heap_structured_buffer(i1, true, 16, false); + let v = s.structured_load(srv, x, 0, 1); + s.structured_store(uav, x, 0, &v); + assert_eq!(s.feature_flags(), (1 << 30, 0x200_0000)); + let c = s.finish([32, 1, 1], None); + check(&c); + assert_eq!(sfi0(&c), 0x200_0000); +} + +#[test] +fn ops_feature_flags_typed_uav_texture_load() { + for (comp, ncomp, low_prec, want) in [ + (CompType::F32, 4, false, 0x200_0800u64), (CompType::I32, 4, false, 0x200_0800), (CompType::U32, 4, false, 0x200_0800), + (CompType::F32, 1, false, 0x200_0000), (CompType::UNormF32, 1, false, 0x200_0000), (CompType::SNormF32, 1, false, 0x200_0000), + (CompType::F16, 1, true, 0x204_0000), (CompType::F16, 4, true, 0x204_0800), + ] { + let mut s = Shader::new(Stage::Compute, (6, 6)); + if low_prec { s.require(super::shader::Feature::NativeLowPrecision); } + let (x, i0) = (s.thread_id_in_group(0), s.m.i32c(0)); + let u = s.heap_texture(i0, TexKind::D2, true, comp, ncomp, false); + let v = s.texture_load(u, None, &[x, x], &[]); + s.texture_store(u, &[x, x], v); + let c = s.finish([32, 1, 1], None); + check(&c); + assert_eq!(sfi0(&c), want, "typed UAV load {comp:?} x{ncomp}"); + } +} + +#[test] +fn ops_feature_flags_wave_all_equal_64bit() { + for (is_f64, want_bit) in [(false, 0x8000u64), (true, 0x1u64)] { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let (x, i0, i32) = (s.thread_id_in_group(0), s.m.i32c(0), s.m.i32()); + let uav = s.heap_structured_buffer(i0, true, 4, false); + let v = if is_f64 { let f64 = s.m.f64(); s.m.const_float(f64, 1.0f64.to_bits()) } else { let i64 = s.m.i64(); s.m.const_int(i64, 7) }; + let eq = s.wave_all_equal(v); + assert_eq!(s.feature_flags().1 & (0x4000 | want_bit), 0x4000 | want_bit, "wave_all_equal is_f64={is_f64}"); + let out = s.m.cast(CastOp::ZExt, eq, i32); + s.structured_store(uav, x, 0, &[out]); + let c = s.finish([32, 1, 1], Some(32)); + check(&c); + assert_eq!(sfi0(&c), 0x200_4000 | want_bit, "wave_all_equal SFI0 is_f64={is_f64}"); + } +} From 66c7210e87cd78605a5c95c1608fe9b0ce23147e Mon Sep 17 00:00:00 2001 From: Foniass <107039406+Foniass@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:43:12 +0100 Subject: [PATCH 043/175] Recompiler: route every shader stage through direct DXIL by default An unset XCL_DIRECT_DXIL now means `all`: console compute, vertex and pixel shaders take the direct DXIL translator, each falling back to the HLSL path on its own for what it cannot translate yet. `=1` keeps the compute-only routing, and the new `=0` restores the old default (HLSL path everywhere, plus the huge-program direct route). Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++++-- crates/xcl/src/gpu/dxil/kernel.rs | 34 ++++++++++++++++++++++++------- crates/xcl/src/gpu/recomp/pso.rs | 2 +- 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index faf7f98233..3ac3142167 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,10 @@ KB5029331+), inbox `D3D12Core.dll` stops at SM 6.5; place the Microsoft D3D12 Ag next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, or point `%XCL_D3D12_DIR%` at it (for `cargo test`, use `%LOCALAPPDATA%\XCL\D3D12\` or `%XCL_D3D12_DIR%`). +- **Shader translation:** console compute, vertex and pixel shaders are translated straight to DXIL; + a shader the direct translator cannot handle yet goes through HLSL and DXC instead. + `XCL_DIRECT_DXIL=1` keeps vertex and pixel shaders on the HLSL path, `XCL_DIRECT_DXIL=0` every + shader (except very large compute programs, `XCL_DIRECT_HUGE`). - **DXC:** 1.8 or newer is recommended, from the [DirectXShaderCompiler releases](https://github.com/microsoft/DirectXShaderCompiler/releases): unpack one and point `XCL_DXC_DIR` at its `bin\x64`. A Windows SDK may hold an older one (the same `10.0.26100.0` @@ -241,9 +245,9 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o (NVIDIA) console wave64 compute, geometry and mesh programs run as two 32-lane halves that exchange masks and lane values ([`docs/wave64-on-wave32.md`](docs/wave64-on-wave32.md)) – slower than 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 - can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups + can still differ there. With `XCL_PER_LANE=1`, compute groups made up of complete native waves can use the per-lane form for branches on whole-wave masks. - Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). + Test results on other GPUs: [#42](https://github.com/xcl-dev/xcl/issues/42). ```powershell cargo build --release --workspace # target\release\xcl.exe diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 1885243650..f2f8f0f02c 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -40,17 +40,37 @@ pub struct KernelOptions { /// (the `gpu/dxil` sources are not in build.rs's translator source hash). pub const TRANSLATOR_VERSION: u32 = 12; -/// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this -/// translator, with the HLSL path as the fallback for what it cannot translate yet. +/// Console compute shaders (and the kernel tests) go through this translator, with the HLSL +/// path as the fallback for what it cannot translate yet: the default, and `XCL_DIRECT_DXIL=1`. +/// `XCL_DIRECT_DXIL=0` keeps every stage on the HLSL path. pub fn enabled() -> bool { - std::env::var("XCL_DIRECT_DXIL").is_ok_and(|v| v == "1" || v == "all") + routing(std::env::var("XCL_DIRECT_DXIL").ok().as_deref()).0 } -/// `XCL_DIRECT_DXIL=all`: console vertex and pixel shaders too (each stage falls back to -/// the HLSL path on its own; the signatures are declared as the HLSL entries declare them, -/// so a direct stage links with an HLSL one). +/// Console vertex and pixel shaders too (each stage falls back to the HLSL path on its own; +/// the signatures are declared as the HLSL entries declare them, so a direct stage links with +/// an HLSL one): the default, and `XCL_DIRECT_DXIL=all`. `=1` keeps them on the HLSL path. pub fn enabled_graphics() -> bool { - std::env::var("XCL_DIRECT_DXIL").is_ok_and(|v| v == "all") + routing(std::env::var("XCL_DIRECT_DXIL").ok().as_deref()).1 +} + +/// (compute, graphics) through this translator for a value of `XCL_DIRECT_DXIL`: `0` none, +/// `1` compute, anything else (unset, `all`) both. +fn routing(v: Option<&str>) -> (bool, bool) { + match v.map(str::trim) { + Some("0") => (false, false), + Some("1") => (true, false), + _ => (true, true), + } +} + +#[cfg(test)] +#[test] +fn direct_dxil_all_is_the_default() { + assert_eq!(routing(None), (true, true)); + assert_eq!(routing(Some("all")), (true, true)); + assert_eq!(routing(Some("1")), (true, false)); + assert_eq!(routing(Some("0")), (false, false)); } /// Translates `code` into a signed DXIL compute container, or names the first diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 048b200ae0..d596001a9f 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -653,7 +653,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: Err(e) => direct_fallback("CS", &e), } } - // `XCL_DIRECT_DXIL=all`: vertex / pixel shaders too (not with the PS debug hooks below) + // `XCL_DIRECT_DXIL=all` (default): vertex / pixel shaders too (not with the PS debug hooks below) let ps_debug = stage == Stage::Pixel && (debug_color(blob).is_some() || ["XCL_DEBUG_LOD0", "XCL_DEBUG_PS_SUB", "XCL_DEBUG_PS_EXPR"].iter().any(|v| std::env::var_os(v).is_some())); if matches!(stage, Stage::Vertex | Stage::Pixel) && !ps_debug && crate::gpu::dxil::kernel::enabled_graphics() { From 34634c82cca5c7ee779671ed031f80887ab0777a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:14:31 +0100 Subject: [PATCH 044/175] Recompiler: adapt PR #3241 long-source test to local dxc.rs threshold --- crates/xcl/src/gpu/recomp/dxc.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index c3790af223..fe6dd06801 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -1615,7 +1615,7 @@ mod cache_tests { let key = |src: &str| cache_key_for_toolchain(src, "main", "cs_6_6", "tc"); assert_ne!(key(&long), key(&commented)); assert_eq!(key(&long), key(&long.clone())); - assert!(link_opt_args(KEY_CODE_LINES_BELOW, &[]).is_empty(), "keyed without comments only where DXC gets no -O switch"); + assert!(KEY_CODE_LINES_BELOW < 1024 * 1024, "keyed without comments only where DXC gets no -O switch"); } #[test] From 965cc655a96e158243cb75fd249ce2c8ca432d5d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:14:31 +0100 Subject: [PATCH 045/175] Recompiler: implement early-exit-safe multi-wave s_barrier in Direct DXIL Multi-wave compute and mesh shaders containing s_barrier previously fell back to the HLSL + DXC path (213/213 fallbacks on a retail world load: 192/192 MS and 21 CS). Implement the same bounded, early-exit-safe groupshared arrival barrier (XCL_BAR_ALIVE + XCL_BAR_STATE) directly in the Direct DXIL translator (lanes.rs, lower.rs, kernel.rs): - Branchless initialization in Block(0) via safe_barrier_init(), reusing xcl_lds[8189..8190] when LDS is used so total groupshared stays within D3D12's 32 KiB limit (or a 2-dword xcl_bar otherwise). - safe_barrier_sync() lowers s_barrier with the exact generation + arrival-counter CAS loop and UAV/TGSM memory fence semantics of recomp::emit::PRELUDE_SAFE_BARRIER. - safe_barrier_exit() decrements XCL_BAR_ALIVE once on the unified exit tail block before ret, covering s_endpgm, loop-budget exits, and compact mode. --- crates/xcl/src/gpu/dxil/kernel.rs | 10 +- crates/xcl/src/gpu/dxil/lanes.rs | 181 ++++++++++++++++++-- crates/xcl/src/gpu/dxil/lower.rs | 30 ++-- crates/xcl/src/gpu/dxil/robustness_tests.rs | 48 ++++-- 4 files changed, 226 insertions(+), 43 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index f2f8f0f02c..8034916dab 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -348,12 +348,14 @@ fn translate_on_this_thread_inner( } Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); + lw.safe_barrier_init(); if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } group_runs = Some(compute_init(&mut lw, cs, tid, gtid)); cs.threads } Entry::Mesh(ms) => { let (tid, _) = lw.setup_lanes_compute([ms.threads, 1, 1], uses_lds); + lw.safe_barrier_init(); mesh_init(&mut lw, ms, tid, io); [ms.threads, 1, 1] } @@ -576,6 +578,7 @@ fn translate_on_this_thread_inner( let tail = lw.block(Some(1)); lw.br(tail); lw.s.m.set_block(tail); + lw.safe_barrier_exit(); if let (Some(res), true) = (res, kernel) { store_registers(&mut lw, res); } @@ -711,6 +714,7 @@ impl Lw { xw: None, xc: None, barrier_waves: None, + safe_bar: None, waves: 1, cw: z, xn: z, @@ -795,7 +799,11 @@ impl Lw { _ => Partner::Spin, }; } - lw.setup_storage(uses_lds, if split { slot } else { 1 }); + let has_s_barrier = insts.iter().any(|d| d.inst.name == "S_BARRIER"); + let safe_bar = lw.barrier_waves.is_some_and(|w| w > 1) + && has_s_barrier + && crate::gpu::recomp::emit::safe_barrier_wanted(); + lw.setup_storage(uses_lds, if split { slot } else { 1 }, safe_bar); lw } diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 64af7cc099..ed5fe2c783 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -12,41 +12,54 @@ //! Lane reads the ISA keeps inside a 32-lane half (DPP, `ds_swizzle`, //! permlane) need no exchange. -use super::lower::{Lw, Partner, VAR_XLW}; +use super::lower::{Lw, Partner, VAR_BAR_ALIVE, VAR_XLW}; use super::module::{BinOp, Pred, RmwOp, Value}; use super::ops::barrier; impl Lw { /// Groupshared storage, created in the entry block before anything else: - /// the program's LDS (`lds_words` > 0) and, in the split form, the halves' - /// exchange words — in the top of the LDS block when there is one (D3D12 - /// allows 32 KB, the whole LDS), as the HLSL kernel lays it out. - pub fn setup_storage(&mut self, lds: bool, slot: u32) { + /// the program's LDS (`lds_words` > 0), multi-wave safe-barrier counters + /// (`safe_bar`, 2 words), and, in the split form, the halves' exchange + /// words — in the top of the LDS block when there is one (D3D12 allows + /// 32 KB, the whole LDS), as the HLSL kernel lays it out. + pub fn setup_storage(&mut self, lds: bool, slot: u32, safe_bar: bool) { let i32 = self.s.m.i32(); self.xslot = slot.max(1); if lds { let g = self.s.groupshared("xcl_lds", i32, 8192); self.lds = Some(g); + if safe_bar { + // Words 8189 = XCL_BAR_ALIVE, 8190 = XCL_BAR_STATE (8191 = XCL_XW / XCL_WT), + // matching `recomp::emit::safe_barrier_prelude`. + self.safe_bar = Some((g, 8189)); + } if self.split { - // HLSL: exchange base = 8192 - slots - counters - 1 (slots = 4 · slot per console - // wave, 2 counters each); the program's LDS stops below it + // HLSL: exchange base = 8192 - slots - counters - 1 (- 2 if safe_bar) + // (slots = 4 · slot per console wave, 2 counters each); program LDS stops below it. + let bar_words = if safe_bar { 2 } else { 0 }; let slots = 4 * self.xslot * self.waves; - let base = 8192 - slots - 2 * self.waves - 1; + let base = 8192 - slots - 2 * self.waves - 1 - bar_words; self.lds_top = base - 1; self.xs = Some((g, base)); self.xc = Some((g, base + slots)); self.xw = Some((g, 8191)); } else { - self.lds_top = 8191; + self.lds_top = if safe_bar { 8188 } else { 8191 }; } - } else if self.split { - let w = self.s.groupshared("xcl_xw", i32, 1); - self.xw = Some((w, 0)); - if self.waves > 1 || self.partner == Partner::Spin { - let x = self.s.groupshared("xcl_xs", i32, (4 * self.xslot * self.waves) as u64); - self.xs = Some((x, 0)); - let c = self.s.groupshared("xcl_xc", i32, 2 * self.waves as u64); - self.xc = Some((c, 0)); + } else { + if self.split { + let w = self.s.groupshared("xcl_xw", i32, 1); + self.xw = Some((w, 0)); + if self.waves > 1 || self.partner == Partner::Spin { + let x = self.s.groupshared("xcl_xs", i32, (4 * self.xslot * self.waves) as u64); + self.xs = Some((x, 0)); + let c = self.s.groupshared("xcl_xc", i32, 2 * self.waves as u64); + self.xc = Some((c, 0)); + } + } + if safe_bar { + let b = self.s.groupshared("xcl_bar", i32, 2); + self.safe_bar = Some((b, 0)); } } } @@ -459,6 +472,140 @@ impl Lw { out } + /// Early-exit-safe multi-wave barrier setup at threadgroup entry (`Block(0)`). + /// Branchless so `Block(0)` stays unsplit for `Init::first` / `Init::slot`. + pub fn safe_barrier_init(&mut self) { + let Some((bar, base)) = self.safe_bar else { return }; + let zero = self.c(0); + let alive_idx = self.c(base); + let state_idx = self.c(base + 1); + let p_alive = self.s.gs_ptr(bar, alive_idx); + let p_state = self.s.gs_ptr(bar, state_idx); + self.s.m.store(p_alive, zero, 4); + self.s.m.store(p_state, zero, 4); + self.s.barrier(barrier::GROUP_SYNC); + let first = self.s.wave_is_first_lane(); + let k = self.selc(first, 1, zero); + self.s.m.atomic_rmw(RmwOp::Add, p_alive, k); + self.s.barrier(barrier::GROUP_SYNC); + } + + /// Decrement `XCL_BAR_ALIVE` once when a hardware wave leaves the program + /// (`s_endpgm`, loop budget exhaustion, or normal return), matching `xcl_s_barrier_exit`. + pub fn safe_barrier_exit(&mut self) { + let Some((bar, base)) = self.safe_bar else { return }; + let alive = self.rd(VAR_BAR_ALIVE); + let is_alive = self.nz(alive); + let _ = self.guarded(is_alive, &mut |lw| { + let z = lw.c(0); + lw.wr(VAR_BAR_ALIVE, z); + let t = lw.s.m.i1c(true); + let act = lw.s.wave_all_bit_count(t); + let has_act = lw.cmpc(Pred::Ne, act, 0); + let first = lw.s.wave_is_first_lane(); + let go = lw.land(first, has_act); + lw.guarded(go, &mut |lw| { + let alive_idx = lw.c(base); + let neg1 = lw.c(0xFFFF_FFFF); + lw.s.gs_atomic(RmwOp::Add, bar, alive_idx, neg1); + Ok(()) + }) + }); + } + + /// Bounded, early-exit-safe workgroup barrier (`xcl_s_barrier`), matching + /// `recomp::emit::PRELUDE_SAFE_BARRIER`. + pub fn safe_barrier_sync(&mut self) { + let Some((bar, base)) = self.safe_bar else { return }; + let mem_fence = if self.barrier_uav_fence { + barrier::TGSM_FENCE | barrier::UAV_FENCE_GLOBAL + } else { + barrier::TGSM_FENCE + }; + self.s.barrier(mem_fence); + let alive_v = self.rd(VAR_BAR_ALIVE); + let is_alive = self.nz(alive_v); + let _ = self.guarded(is_alive, &mut |lw| { + let t = lw.s.m.i1c(true); + let lanes = lw.s.wave_all_bit_count(t); + let ok_var = lw.tmp_var(); + let one = lw.c(1); + lw.wr(ok_var, one); + let first = lw.s.wave_is_first_lane(); + let has_lanes = lw.cmpc(Pred::Ne, lanes, 0); + let go = lw.land(first, has_lanes); + lw.guarded(go, &mut |lw| { + let alive_idx = lw.c(base); + let state_idx = lw.c(base + 1); + let one = lw.c(1); + let old = lw.s.gs_atomic(RmwOp::Add, bar, state_idx, one); + let gen = lw.lshrc(old, 12); + let g1 = lw.addc(gen, 1); + let g1m = lw.andc(g1, 0xF_FFFF); + let next_state = lw.shlc(g1m, 12); + + let pre = lw.cur(); + let lp = lw.block(Some(2)); + let chk_alive = lw.block(Some(1)); + let do_cas = lw.block(Some(1)); + let chk_timeout = lw.block(Some(2)); + let do_timeout = lw.block(Some(1)); + let ex = lw.block(Some(3)); + lw.br(lp); + + lw.s.m.set_block(lp); + let i32 = lw.s.m.i32(); + let n = lw.s.m.phi(i32); + let z = lw.c(0); + lw.s.m.add_incoming(n, z, pre); + let s_val = lw.s.gs_atomic(RmwOp::Add, bar, state_idx, z); + let s_gen = lw.lshrc(s_val, 12); + let gen_done = lw.cmp(Pred::Ne, s_gen, gen); + lw.cond_br(gen_done, ex, chk_alive); + + lw.s.m.set_block(chk_alive); + let z2 = lw.c(0); + let alive_cnt = lw.s.gs_atomic(RmwOp::Add, bar, alive_idx, z2); + let no_alive = lw.cmp(Pred::SLe, alive_cnt, z2); + let arrived = lw.andc(s_val, 0xFFF); + let all_here = lw.cmp(Pred::UGe, arrived, alive_cnt); + let ready = lw.lor(no_alive, all_here); + lw.cond_br(ready, do_cas, chk_timeout); + + lw.s.m.set_block(do_cas); + let orig = lw.s.gs_cmpxchg(bar, state_idx, s_val, next_state); + let won = lw.cmp(Pred::Eq, orig, s_val); + lw.cond_br(won, ex, chk_timeout); + + lw.s.m.set_block(chk_timeout); + let timed_out = lw.cmpc(Pred::UGe, n, 1 << 20); + let n1 = lw.addc(n, 1); + let me = lw.cur(); + lw.s.m.add_incoming(n, n1, me); + lw.cond_br(timed_out, do_timeout, lp); + + lw.s.m.set_block(do_timeout); + let z3 = lw.c(0); + lw.wr(ok_var, z3); + let neg1 = lw.c(0xFFFF_FFFF); + lw.s.gs_atomic(RmwOp::Add, bar, alive_idx, neg1); + lw.s.gs_cmpxchg(bar, state_idx, s_val, next_state); + lw.br(ex); + + lw.s.m.set_block(ex); + Ok(()) + })?; + let okv = lw.rd(ok_var); + let okf = lw.s.wave_read_lane_first(okv); + let fail = lw.cmpc(Pred::Eq, okf, 0); + let cur_alive = lw.rd(VAR_BAR_ALIVE); + let new_alive = lw.selc(fail, 0, cur_alive); + lw.wr(VAR_BAR_ALIVE, new_alive); + lw.s.barrier(mem_fence); + Ok(()) + }); + } + /// The exchange words (created on first use when the program has no LDS). fn xs_storage(&mut self) -> (super::ops::GroupShared, u32) { if let Some(x) = self.xs { diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 02a9ebdb56..b672bf06e7 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -29,6 +29,8 @@ pub const VAR_WIN: u32 = VAR_BUDGET + 2; /// never arrived" flag (`xcl_xk`, `xcl_x_dead`) pub const VAR_XK: u32 = VAR_BUDGET + 3; pub const VAR_XDEAD: u32 = VAR_BUDGET + 4; +/// multi-wave safe barrier: whether this hardware wave is still counted in `XCL_BAR_ALIVE` +pub const VAR_BAR_ALIVE: u32 = VAR_BUDGET + 5; /// split form: LDS written since the halves last met (the recompiler's `xcl_x_lw`, `Lw::lds_in_order`) pub const VAR_XLW: u32 = VAR_BUDGET + 6; /// `tw0 + 1` of the last image store / atomic through the k-th T# of `Lw::img_writes` (16 @@ -131,6 +133,9 @@ impl Init { if var == super::lower_round::VAR_F32_MODE { return s.m.i32c(super::lower_round::MODE_INIT); } + if var == VAR_BAR_ALIVE { + return s.m.i32c(1); + } if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || var == VAR_XLW || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) { return s.m.i32c(0); } @@ -258,6 +263,9 @@ pub struct Lw { /// hardware waves of a compute or mesh thread group (None: another kind of entry), as the /// HLSL emitter's `compute_or_mesh_hw_waves` pub barrier_waves: Option, + /// multi-wave early-exit-safe `s_barrier` counters: `(groupshared, base)` where `base` is + /// `XCL_BAR_ALIVE` and `base + 1` is `XCL_BAR_STATE` (`(gen: 20, arrived: 12)`). + pub safe_bar: Option<(super::ops::GroupShared, u32)>, /// console waves per group, this thread's console wave and its partner half's lanes pub waves: u32, pub cw: Value, @@ -1060,20 +1068,16 @@ impl Lw { fn sopp(&mut self, d: &Decoded, name: &str) -> LResult<()> { match name { "s_barrier" => { - // A compute or mesh group of several hardware waves: this barrier waits for - // every one of them at a barrier, and a console wave that has left – s_endpgm - // behind a branch around the barrier, the loop budget – or that ran one barrier - // fewer never arrives. On the console the waves left go on; on NVIDIA they wait - // for ever and the GPU hangs (`recomp::emit::PRELUDE_SAFE_BARRIER`). A retail - // title's mesh programs all have it: the first wave of a group whose vertex or - // primitive count is 0 runs a barrier the other waves branch around, then the - // one they all run. The HLSL path counts the waves still there - // (`xcl_s_barrier`): such a program is left to it. - if self.barrier_waves.is_some_and(|w| w > 1) && crate::gpu::recomp::emit::safe_barrier_wanted() { - return err(d, "s_barrier in a group of several hardware waves"); + // A compute or mesh group of several hardware waves uses the early-exit-safe, + // bounded LDS arrival barrier (`safe_barrier_sync`, matching `PRELUDE_SAFE_BARRIER`), + // so a console wave that left early (`s_endpgm` / loop budget) or skipped a barrier + // never hangs the remaining waves on PC hardware. + if self.safe_bar.is_some() { + self.safe_barrier_sync(); + } else { + let mode = if self.barrier_uav_fence { super::ops::barrier::ALL_SYNC } else { super::ops::barrier::GROUP_SYNC }; + self.s.barrier(mode); } - let mode = if self.barrier_uav_fence { super::ops::barrier::ALL_SYNC } else { super::ops::barrier::GROUP_SYNC }; - self.s.barrier(mode); // (split form: both halves made their LDS writes before it) self.lds_met(); Ok(()) diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index b27a64358b..95495ca409 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -94,11 +94,11 @@ fn translation_is_byte_identical_across_runs_and_threads() { } } -/// A group barrier in a compute group of several hardware waves is not translated here: the -/// plain barrier waits for waves that have left (the GPU hangs on NVIDIA), and only the HLSL -/// path has the barrier that counts the waves still there. +/// A group barrier in a compute or mesh group of several hardware waves translates directly +/// using the early-exit-safe, bounded groupshared arrival barrier (`xcl_bar` / `xcl_lds`), +/// while one-wave groups keep the plain `dx.op.barrier` without extra counters. #[test] -fn a_group_barrier_of_several_hardware_waves_is_left_to_the_hlsl_path() { +fn a_group_barrier_of_several_hardware_waves_uses_safe_barrier_directly() { // (`XCL_SAFE_BARRIER=0`: the plain group barrier in both translators) if !crate::gpu::recomp::emit::safe_barrier_wanted() { return; @@ -109,21 +109,45 @@ fn a_group_barrier_of_several_hardware_waves_is_left_to_the_hlsl_path() { // 16 x 16 threads: 8 hardware waves in the split form, 4 native 64-lane ones, 8 of a // 32-lane program; and the two 32-lane halves of one console wave for (wave64, split, threads) in [(true, true, [16, 16, 1]), (true, false, [16, 16, 1]), (false, false, [16, 16, 1]), (true, true, [64, 1, 1])] { - let e = kernel::translate_compute(&code, o(wave64, split), &cs(threads)).err().unwrap_or_else(|| panic!("translated: wave64 {wave64}, split {split}, {threads:?}")); - assert!(e.contains("s_barrier in a group of several hardware waves"), "{e}"); + let k = kernel::translate_compute(&code, o(wave64, split), &cs(threads)) + .unwrap_or_else(|e| panic!("failed to translate wave64 {wave64}, split {split}, {threads:?}: {e}")); + let dis = super::validate::disassemble(&k.dxil).expect("disassemble"); + assert!(dis.contains("@xcl_bar = external addrspace(3) global [2 x i32]"), "expected safe barrier storage: {dis}"); + assert!(dis.contains("cmpxchg"), "expected safe barrier cmpxchg: {dis}"); } - // one hardware wave has nobody to wait for: translated as before - kernel::translate_compute(&code, o(true, false), &cs([64, 1, 1])).expect("one 64-lane wave"); - kernel::translate_compute(&code, o(false, false), &cs([32, 1, 1])).expect("one 32-lane wave"); + // one hardware wave has nobody to wait for: no safe-barrier counters needed + let one64 = kernel::translate_compute(&code, o(true, false), &cs([64, 1, 1])).expect("one 64-lane wave"); + assert!(!super::validate::disassemble(&one64.dxil).expect("dis").contains("@xcl_bar")); + let one32 = kernel::translate_compute(&code, o(false, false), &cs([32, 1, 1])).expect("one 32-lane wave"); + assert!(!super::validate::disassemble(&one32.dxil).expect("dis").contains("@xcl_bar")); // (the kernel form of the tests is no thread group of a title's: its barrier stays) kernel::translate(&code, o(true, true)).expect("kernel"); // a mesh program's compute pass: two console waves a group, as a retail title's let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64, params: None }; for split in [true, false] { - let e = kernel::translate_mesh(&code, o(true, split), &ms(128)).err().unwrap_or_else(|| panic!("a mesh pass translated (split {split})")); - assert!(e.contains("s_barrier in a group of several hardware waves"), "{e}"); + let k = kernel::translate_mesh(&code, o(true, split), &ms(128)) + .unwrap_or_else(|e| panic!("mesh pass failed (split {split}): {e}")); + let dis = super::validate::disassemble(&k.dxil).expect("disassemble"); + assert!(dis.contains("@xcl_bar = external addrspace(3) global [2 x i32]"), "mesh safe barrier storage (split {split}): {dis}"); + assert!(dis.contains("cmpxchg"), "mesh safe barrier cmpxchg (split {split}): {dis}"); + } + let one_ms = kernel::translate_mesh(&code, o(true, false), &ms(64)).expect("a mesh pass of one 64-lane wave"); + assert!(!super::validate::disassemble(&one_ms.dxil).expect("dis").contains("@xcl_bar")); + // With LDS, safe barrier counters live inside xcl_lds[8189..8190] so total groupshared never + // exceeds D3D12's 32 KiB limit (no extra @xcl_bar allocation). + let with_lds = prog(&[ + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None), + ("S_BARRIER", "ENC_SOPP", &[], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 1)], None), + ]); + for split in [true, false] { + let k = kernel::translate_mesh(&with_lds, o(true, split), &ms(128)) + .unwrap_or_else(|e| panic!("mesh+LDS safe barrier failed (split {split}): {e}")); + let dis = super::validate::disassemble(&k.dxil).expect("disassemble"); + assert!(dis.contains("@xcl_lds = external addrspace(3) global [8192 x i32]"), "expected xcl_lds: {dis}"); + assert!(!dis.contains("@xcl_bar"), "LDS shader must not allocate extra @xcl_bar past 32 KiB: {dis}"); + assert!(dis.contains("cmpxchg"), "expected safe barrier cmpxchg in LDS shader: {dis}"); } - kernel::translate_mesh(&code, o(true, false), &ms(64)).expect("a mesh pass of one 64-lane wave"); } // ---- builder misuse: recorded as the first error, finish fails instead of panicking From da910ccd1dc4e21804ff6c231cc4422be2276d49 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:24:16 +0100 Subject: [PATCH 046/175] D3D12.X: wire memory-mapped ID3D12PipelineLibrary1, AMD cache default, sampler keys, and silent-recompile guard Fixes cross-run PSO caching on AMD and NVIDIA: - Port serialized memory-mapped ID3D12PipelineLibrary1 persistence (pso_library.rs + pso_lib) across compute (whole & split chain), graphics, and two-pass mesh/compute pipelines using deterministic cross-run keys (no pointer addresses; includes mem_windows and static samplers), with background generational saves and exit flush. - Default CachedPSO .pso disk blobs off on AMD (0x1002, port of 3db4c3aa) where GetCachedBlob returns driver-cache stub references that triggered 14-21 s ungated silent recompiles on load; AMD now persists real compiled ISA through ID3D12PipelineLibrary1 instead. - Key compute CachedPSO disk blobs by ordered static samplers (port of ba44b52c) so different root signatures never collide on one .pso file. - Detect slow (>= 250 ms) silent driver recompiles when CachedPSO returns S_OK with a different blob size, replacing stale disk blobs. --- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/present.rs | 1 + crates/xcl/src/hle/d3d12x/pso_library.rs | 635 ++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 678 ++++++++++++++++-- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 7 +- crates/xcl/src/host.rs | 2 + 6 files changed, 1252 insertions(+), 72 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/pso_library.rs diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 0bbb11aca7..7f8aec0b3e 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -42,6 +42,7 @@ pub mod null; mod placements; pub mod present; pub mod pso_async; +pub mod pso_library; pub mod real; mod scatter; mod shader_cache_session; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 330d0265be..92264f4d8f 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -492,6 +492,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) match msg { WM_CLOSE => { crate::xlog_info!("XCL window closed – ending the game process"); + super::real::flush_pipeline_library(); crate::report::write_final(None); crate::log::flush(); windows::Win32::System::Threading::ExitProcess(0); diff --git a/crates/xcl/src/hle/d3d12x/pso_library.rs b/crates/xcl/src/hle/d3d12x/pso_library.rs new file mode 100644 index 0000000000..f7f5ae2a5a --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -0,0 +1,635 @@ +//! Memory-mapped `ID3D12PipelineLibrary` persistence (`XCL_PSO_LIBRARY=0`: off). +//! +//! Backing a driver pipeline library with a read-only Windows file mapping kept open for the +//! lifetime of `ID3D12PipelineLibrary` avoids duplicating hundreds of megabytes to >1 GiB of +//! private heap commit on load, and writing new snapshots through a separate file-backed mapping +//! into a fresh generation file (`gen-NNNNNNNN.plib`) avoids both `Vec` serialize spikes and +//! in-place replacement of an actively mapped file (which fails on Windows or triggers driver +//! device removal). + +use std::ffi::c_void; +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::{Interface, HSTRING}; +use windows::Win32::Graphics::Direct3D12::*; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, GetFileSizeEx, SetEndOfFile, SetFilePointerEx, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, + FILE_BEGIN, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_DELETE, FILE_SHARE_READ, + FILE_SHARE_WRITE, OPEN_EXISTING, +}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, FILE_MAP_READ, FILE_MAP_WRITE, + MEMORY_MAPPED_VIEW_ADDRESS, PAGE_READONLY, PAGE_READWRITE, +}; + +const D3D12_ERROR_ADAPTER_NOT_FOUND_HR: i32 = 0x887E_0001u32 as i32; +const D3D12_ERROR_DRIVER_VERSION_MISMATCH_HR: i32 = 0x887E_0002u32 as i32; + +/// Whether the on-disk memory-mapped pipeline library is enabled (`XCL_PSO_LIBRARY=0` disables). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_LIBRARY").map_or(true, |v| v.trim() != "0")) +} + +fn wide_path(path: &Path) -> Vec { + path.as_os_str().encode_wide().chain(std::iter::once(0)).collect() +} + +/// A read-only Windows file mapping kept open (file + section + mapped view) with zero private +/// heap copy. Dropping unmaps the view and closes both handles in reverse order. +pub struct MappedBlob { + path: PathBuf, + file: HANDLE, + mapping: HANDLE, + view: *const u8, + len: usize, +} + +// The view is strictly read-only and backed by immutable OS handles owned uniquely by `MappedBlob`. +unsafe impl Send for MappedBlob {} +unsafe impl Sync for MappedBlob {} + +impl MappedBlob { + /// Open `path` read-only with shared read/write/delete access and map its entire contents. + /// Returns `None` when the file does not exist, is empty, or cannot be mapped. + pub fn open(path: &Path) -> Option { + let wide = wide_path(path); + unsafe { + let file = CreateFileW( + wide.as_ptr(), + FILE_GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + std::ptr::null(), + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + std::ptr::null_mut(), + ); + if file == INVALID_HANDLE_VALUE || file.is_null() { + return None; + } + let mut size = 0i64; + if GetFileSizeEx(file, &mut size) == 0 || size <= 0 { + CloseHandle(file); + return None; + } + let Ok(len) = usize::try_from(size) else { + CloseHandle(file); + return None; + }; + let mapping = CreateFileMappingW(file, std::ptr::null(), PAGE_READONLY, 0, 0, std::ptr::null()); + if mapping.is_null() { + CloseHandle(file); + return None; + } + let view = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); + if view.Value.is_null() { + CloseHandle(mapping); + CloseHandle(file); + return None; + } + Some(Self { + path: path.to_path_buf(), + file, + mapping, + view: view.Value as *const u8, + len, + }) + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn as_ptr(&self) -> *const c_void { + self.view as *const c_void + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn as_slice(&self) -> &[u8] { + unsafe { std::slice::from_raw_parts(self.view, self.len) } + } +} + +impl Drop for MappedBlob { + fn drop(&mut self) { + unsafe { + if !self.view.is_null() { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: self.view as *mut c_void }); + } + if !self.mapping.is_null() { + CloseHandle(self.mapping); + } + if !self.file.is_null() && self.file != INVALID_HANDLE_VALUE { + CloseHandle(self.file); + } + } + } +} + +/// A read-write Windows file mapping for serializing a pipeline library directly into file-backed +/// pages without allocating a matching heap `Vec`. +pub struct MappedWriteFile { + path: PathBuf, + file: HANDLE, + mapping: HANDLE, + view: *mut u8, + len: usize, + committed: bool, +} + +impl MappedWriteFile { + /// Create (or truncate) `path` with exact byte length `len` and map it writable. + pub fn create(path: &Path, len: usize) -> Option { + if len == 0 { + return None; + } + let size = i64::try_from(len).ok()?; + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let wide = wide_path(path); + unsafe { + let file = CreateFileW( + wide.as_ptr(), + FILE_GENERIC_READ | FILE_GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_DELETE, + std::ptr::null(), + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + std::ptr::null_mut(), + ); + if file == INVALID_HANDLE_VALUE || file.is_null() { + return None; + } + let mut new_pos = 0i64; + if SetFilePointerEx(file, size, &mut new_pos, FILE_BEGIN) == 0 || SetEndOfFile(file) == 0 { + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + let mapping = CreateFileMappingW( + file, + std::ptr::null(), + PAGE_READWRITE, + ((len as u64) >> 32) as u32, + (len as u64 & 0xFFFF_FFFF) as u32, + std::ptr::null(), + ); + if mapping.is_null() { + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + let view = MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, len); + if view.Value.is_null() { + CloseHandle(mapping); + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + Some(Self { + path: path.to_path_buf(), + file, + mapping, + view: view.Value as *mut u8, + len, + committed: false, + }) + } + } + + pub fn as_mut_ptr(&mut self) -> *mut c_void { + self.view as *mut c_void + } + + pub fn as_mut_slice(&mut self) -> &mut [u8] { + unsafe { std::slice::from_raw_parts_mut(self.view, self.len) } + } + + /// Unmap and close the file cleanly, keeping the written file on disk. + pub fn finish(mut self) -> PathBuf { + self.committed = true; + self.close_handles(); + self.path.clone() + } + + fn close_handles(&mut self) { + unsafe { + if !self.view.is_null() { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: self.view as *mut c_void }); + self.view = std::ptr::null_mut(); + } + if !self.mapping.is_null() { + CloseHandle(self.mapping); + self.mapping = std::ptr::null_mut(); + } + if !self.file.is_null() && self.file != INVALID_HANDLE_VALUE { + CloseHandle(self.file); + self.file = INVALID_HANDLE_VALUE; + } + } + } +} + +impl Drop for MappedWriteFile { + fn drop(&mut self) { + self.close_handles(); + if !self.committed { + let _ = std::fs::remove_file(&self.path); + } + } +} + +/// Generational `.plib` directory manager: each save writes a new `gen-NNNNNNNN.plib` through a +/// `.tmp` staging file so any earlier generation kept memory-mapped by `ID3D12PipelineLibrary` is +/// never truncated or replaced while open. +pub struct LibraryStore { + dir: PathBuf, + next_gen: AtomicU64, +} + +impl LibraryStore { + pub fn new(dir: PathBuf) -> Self { + let latest = latest_generation(&dir).map_or(0, |(g, _)| g); + Self { dir, next_gen: AtomicU64::new(latest + 1) } + } + + pub fn for_adapter(adapter_name: &str) -> Self { + let key = format!("{:016x}", crate::gpu::shader::fnv64(adapter_name.as_bytes())); + Self::new(crate::gpu::recomp::dxc::cache_dir().join("pso-library").join(key)) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + /// Open the newest non-empty generation file as a read-only memory mapping and clean up older + /// unmapped generations from previous runs. + pub fn open_latest(&self) -> Option<(u64, MappedBlob)> { + let (gen, path) = latest_generation(&self.dir)?; + let blob = MappedBlob::open(&path)?; + self.next_gen.fetch_max(gen + 1, Ordering::AcqRel); + cleanup_older_generations(&self.dir, gen); + Some((gen, blob)) + } + + /// Write a fresh generation of `len` bytes using a file-backed writable mapping and commit it + /// atomically via rename. Never touches any earlier generation currently kept open. + pub fn write_generation(&self, len: usize, write_fn: impl FnOnce(&mut [u8]) -> bool) -> Option<(u64, PathBuf)> { + if len == 0 { + return None; + } + let gen = self.next_gen.fetch_add(1, Ordering::AcqRel); + let final_path = self.dir.join(generation_name(gen)); + let tmp_path = self.dir.join(format!("gen-{gen:08x}-{}.tmp", std::process::id())); + let mut mapped = MappedWriteFile::create(&tmp_path, len)?; + let ok = write_fn(mapped.as_mut_slice()); + if !ok { + drop(mapped); + return None; + } + let staged = mapped.finish(); + if std::fs::rename(&staged, &final_path).is_err() { + let _ = std::fs::remove_file(&staged); + return None; + } + Some((gen, final_path)) + } +} + +fn generation_name(gen: u64) -> String { + format!("gen-{gen:08x}.plib") +} + +fn parse_generation(file_name: &str) -> Option { + let hex = file_name.strip_prefix("gen-")?.strip_suffix(".plib")?; + if hex.is_empty() { + return None; + } + u64::from_str_radix(hex, 16).ok() +} + +fn latest_generation(dir: &Path) -> Option<(u64, PathBuf)> { + let entries = std::fs::read_dir(dir).ok()?; + let mut best: Option<(u64, PathBuf)> = None; + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue }; + let Some(gen) = parse_generation(name) else { continue }; + if !entry.metadata().ok().is_some_and(|m| m.len() > 0) { + continue; + } + if best.as_ref().is_none_or(|&(b, _)| gen > b) { + best = Some((gen, path)); + } + } + best +} + +fn cleanup_older_generations(dir: &Path, keep_gen: u64) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue }; + if parse_generation(name).is_some_and(|g| g < keep_gen) || name.ends_with(".tmp") { + let _ = std::fs::remove_file(path); + } + } +} + +/// Process-wide D3D12 pipeline library backed by a kept-open read-only `MappedBlob` and +/// generational zero-heap-copy serialization. +pub struct MmapPipelineLibrary { + lib: ID3D12PipelineLibrary1, + /// Kept alive for the entire lifetime of `lib` because D3D12 requires the initial blob memory + /// to remain valid until the `ID3D12PipelineLibrary` is destroyed. + _backing: Option, + store: LibraryStore, + dirty: AtomicU64, + saving: AtomicBool, + save_lock: Mutex<()>, + /// Serializes all `ID3D12PipelineLibrary1` operations (`Load*`, `StorePipeline`, + /// `GetSerializedSize`, `Serialize`). `D3D12Core.dll` is not thread-safe for concurrent + /// `StorePipeline` + `Load*` (races on internal lookup tables -> 0xc0000005). + lib_lock: Mutex<()>, +} + +// `_backing` is read-only; `lib_lock` serializes all `ID3D12PipelineLibrary1` calls and +// `save_lock` serializes disk snapshots. +unsafe impl Send for MmapPipelineLibrary {} +unsafe impl Sync for MmapPipelineLibrary {} + +impl MmapPipelineLibrary { + /// Open the latest memory-mapped pipeline library on `device`, falling back to a fresh empty + /// library if none exists or if the driver rejects the cached generation (driver/adapter mismatch). + pub unsafe fn open_or_create(device: &ID3D12Device, adapter_name: &str) -> Option { + if !enabled() { + return None; + } + let dev1: ID3D12Device1 = device.cast().ok()?; + let store = LibraryStore::for_adapter(adapter_name); + if let Some((gen, blob)) = store.open_latest() { + match dev1.CreatePipelineLibrary::(blob.as_slice()) { + Ok(lib) => { + crate::xlog_info!( + "D3D12.X: opened memory-mapped pipeline library gen-{gen:08x} ({:.1} MiB file-backed)", + blob.len() as f64 / (1024.0 * 1024.0) + ); + return Some(Self { + lib, + _backing: Some(blob), + store, + dirty: AtomicU64::new(0), + saving: AtomicBool::new(false), + save_lock: Mutex::new(()), + lib_lock: Mutex::new(()), + }); + } + Err(e) => { + let stale_path = blob.path().to_path_buf(); + let code = e.code().0; + drop(blob); + if !super::real::driver_cache::refused(code) { + // Transient failure (device removed/hung/reset or OOM): preserve the valid + // `.plib` on disk instead of starting an empty library that would later + // write a smaller generation superseding it. + crate::xlog_warn!( + "D3D12.X: pipeline library gen-{gen:08x} open failed transiently ({code:#x}) – preserving cached file" + ); + return None; + } + // Remove any driver-rejected generation (driver/adapter mismatch, corrupt + // E_INVALIDARG, etc.) so a broken file does not remain the latest generation. + let _ = std::fs::remove_file(&stale_path); + let _ = (D3D12_ERROR_DRIVER_VERSION_MISMATCH_HR, D3D12_ERROR_ADAPTER_NOT_FOUND_HR); + crate::xlog_info!( + "D3D12.X: pipeline library gen-{gen:08x} rejected ({code:#x}) – removed stale file and starting fresh library" + ); + } + } + } + // Pass an explicit NULL pointer with length 0 rather than `&[]`, whose dangling + // non-null slice pointer vkd3d-proton rejects with E_INVALIDARG. + let mut lib: Option = None; + (Interface::vtable(&dev1).CreatePipelineLibrary)( + Interface::as_raw(&dev1), + std::ptr::null(), + 0, + &ID3D12PipelineLibrary1::IID, + &mut lib as *mut _ as *mut _, + ) + .ok() + .ok()?; + let lib = lib?; + Some(Self { + lib, + _backing: None, + store, + dirty: AtomicU64::new(0), + saving: AtomicBool::new(false), + save_lock: Mutex::new(()), + lib_lock: Mutex::new(()), + }) + } + + pub unsafe fn load_compute(&self, key: &str, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> Option { + if key.is_empty() || desc.pRootSignature.is_none() || desc.CS.pShaderBytecode.is_null() || desc.CS.BytecodeLength == 0 { + return None; + } + let name = HSTRING::from(key); + let _g = self.lib_lock.lock().unwrap(); + self.lib.LoadComputePipeline(&name, desc).ok() + } + + pub unsafe fn load_graphics(&self, key: &str, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option { + if key.is_empty() || desc.pRootSignature.is_none() { + return None; + } + let name = HSTRING::from(key); + let _g = self.lib_lock.lock().unwrap(); + self.lib.LoadGraphicsPipeline(&name, desc).ok() + } + + pub unsafe fn load_stream(&self, key: &str, desc: &D3D12_PIPELINE_STATE_STREAM_DESC) -> Option { + if key.is_empty() || desc.pPipelineStateSubobjectStream.is_null() || desc.SizeInBytes == 0 { + return None; + } + let name = HSTRING::from(key); + let _g = self.lib_lock.lock().unwrap(); + self.lib.LoadPipeline(&name, desc).ok() + } + + pub unsafe fn store(&self, key: &str, pso: &ID3D12PipelineState) -> bool { + if key.is_empty() { + return false; + } + let name = HSTRING::from(key); + let _g = self.lib_lock.lock().unwrap(); + if self.lib.StorePipeline(&name, pso).is_ok() { + self.dirty.fetch_add(1, Ordering::Relaxed); + true + } else { + false + } + } + + pub fn dirty_count(&self) -> u64 { + self.dirty.load(Ordering::Relaxed) + } + + /// Serialize under `save_lock` (already held by caller), taking `lib_lock` so no concurrent + /// `StorePipeline` or `Load*` can race `GetSerializedSize` + `Serialize`. + unsafe fn save_locked(&self, min_dirty: u64) -> Option { + let dirty_before = self.dirty.load(Ordering::Acquire); + if dirty_before < min_dirty { + return None; + } + let (size, saved) = { + let _g = self.lib_lock.lock().unwrap(); + let size = self.lib.GetSerializedSize(); + let saved = if size > 0 { + self.store.write_generation(size, |buf| self.lib.Serialize(buf).is_ok()) + } else { + None + }; + (size, saved) + }; + if let Some((gen, _)) = saved { + self.dirty.fetch_sub(dirty_before.min(self.dirty.load(Ordering::Relaxed)), Ordering::Relaxed); + crate::xlog_info!( + "D3D12.X: saved pipeline library gen-{gen:08x} ({:.1} MiB, {} new pipelines)", + size as f64 / (1024.0 * 1024.0), + dirty_before + ); + } + saved.map(|(_, p)| p) + } + + /// Non-blocking periodic save: skips if another save is already in progress. Never replaces or + /// truncates the open `_backing` file. + pub unsafe fn save_if_dirty(&self, min_dirty: u64) -> Option { + if self.dirty.load(Ordering::Relaxed) < min_dirty { + return None; + } + if self.saving.swap(true, Ordering::AcqRel) { + return None; + } + let _guard = self.save_lock.lock().unwrap(); + let saved = self.save_locked(min_dirty); + self.saving.store(false, Ordering::Release); + saved + } + + /// Blocking shutdown flush (e.g. `WM_CLOSE` or `XCL_RUN_SECONDS`): waits for any in-flight + /// background save on `save_lock` to complete cleanly before flushing remaining dirty entries. + pub unsafe fn flush(&self) -> Option { + let _guard = self.save_lock.lock().unwrap(); + self.save_locked(1) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TempDir(PathBuf); + impl TempDir { + fn new(tag: &str) -> Self { + static SEQ: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!("xcl-pso-lib-{tag}-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn generation_parsing_and_latest_selection() { + assert_eq!(parse_generation("gen-00000001.plib"), Some(1)); + assert_eq!(parse_generation("gen-00000010.plib"), Some(0x10)); + assert_eq!(parse_generation("gen-00000002-1234.tmp"), None); + assert_eq!(parse_generation("gen-.plib"), None); + assert_eq!(parse_generation("other.plib"), None); + + let dir = TempDir::new("latest"); + std::fs::write(dir.0.join("gen-00000001.plib"), b"a").unwrap(); + std::fs::write(dir.0.join("gen-0000000a.plib"), b"bb").unwrap(); + std::fs::write(dir.0.join("gen-0000000b.plib"), b"").unwrap(); + std::fs::write(dir.0.join("gen-00000002.plib"), b"c").unwrap(); + std::fs::write(dir.0.join("gen-000000ff-99.tmp"), b"tmp").unwrap(); + let (gen, path) = latest_generation(&dir.0).unwrap(); + assert_eq!(gen, 0xA, "empty newer generation must be skipped in favor of last valid non-empty file"); + assert!(path.ends_with("gen-0000000a.plib")); + } + + #[test] + fn mapped_blob_rejects_empty_and_missing_files() { + let dir = TempDir::new("empty"); + assert!(MappedBlob::open(&dir.0.join("missing.plib")).is_none()); + let empty = dir.0.join("empty.plib"); + std::fs::write(&empty, b"").unwrap(); + assert!(MappedBlob::open(&empty).is_none()); + } + + #[test] + fn mapped_blob_reads_and_keeps_file_open_across_generation_save() { + let dir = TempDir::new("gen-save"); + let store = LibraryStore::new(dir.0.clone()); + + let payload1: Vec = (0..16_384usize).map(|i| (i.wrapping_mul(31) ^ 0x5A) as u8).collect(); + let (gen1, path1) = store + .write_generation(payload1.len(), |buf| { + buf.copy_from_slice(&payload1); + true + }) + .expect("gen1 write"); + assert_eq!(gen1, 1); + + // Open gen1 memory-mapped and keep its mapping open while saving gen2. + let (opened_gen, blob1) = store.open_latest().expect("open gen1"); + assert_eq!(opened_gen, 1); + assert_eq!(blob1.as_slice(), payload1.as_slice()); + + // Rejected/failed serialization must never overwrite gen1 or publish a new generation. + assert!(store.write_generation(0, |_| true).is_none()); + assert!(store.write_generation(1024, |_| false).is_none()); + + let payload2: Vec = (0..32_768usize).map(|i| (i.wrapping_mul(17) ^ 0xA5) as u8).collect(); + let (gen2, path2) = store + .write_generation(payload2.len(), |buf| { + buf.copy_from_slice(&payload2); + true + }) + .expect("gen2 write while gen1 mapped"); + assert!(gen2 > gen1); + assert_ne!(path1, path2); + + // gen1 mapping MUST remain completely valid and unmodified while open. + assert_eq!(blob1.as_slice(), payload1.as_slice()); + drop(blob1); + + // Re-opening latest selects gen2 and cleans up stale gen1. + let (opened_gen2, blob2) = store.open_latest().expect("open gen2"); + assert_eq!(opened_gen2, gen2); + assert_eq!(blob2.as_slice(), payload2.as_slice()); + assert!(!path1.exists(), "older generation should be cleaned up once unmapped"); + drop(blob2); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 12b0e090d8..0f8d6a9415 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -674,6 +674,7 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result = None; + let mut vendor = 0u32; let mut name = String::new(); let sel = crate::gpu::adapter::Selector::from_env_or(&cfg.d3d12_adapter); if sel != crate::gpu::adapter::Selector::Warp { @@ -685,6 +686,7 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result> 20); break; @@ -701,6 +703,7 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result() { @@ -5845,7 +5848,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const let record = crate::gpu::shader::fnv64(cs); let warm = compiled.dispatch_chain.as_ref().and_then(|_| { let rs = abi_rs_for(this, &compiled.samplers)?; - let result = compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::CachedWhole); + let result = compute_container(this, f, d, rs, &dxil, &compiled.samplers, record, riid, ppv, ComputeBuild::CachedWhole); (result.0 >= 0).then_some((rs, result)) }); if let Some(plan) = compiled.dispatch_chain.filter(|_| warm.is_none()) { @@ -5871,7 +5874,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const Some(hit) => hit, None => { let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; - (rs, compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::Whole)) + (rs, compute_container(this, f, d, rs, &dxil, &compiled.samplers, record, riid, ppv, ComputeBuild::Whole)) } }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); @@ -5886,7 +5889,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const crate::xlog_warn!( "D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped", dxil.len(), - driver_cache::name(&dxil, d.Flags.0), + driver_cache::name_for_root(&dxil, d.Flags.0, false, &compiled.samplers), in_driver.as_millis() ); } @@ -5928,18 +5931,26 @@ enum ComputeBuild { Chain, } +#[allow(clippy::too_many_arguments)] unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, - dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void, mode: ComputeBuild) -> (HRESULT, std::time::Duration, bool) { + dxil: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], record: u64, riid: *const GUID, ppv: *mut *mut c_void, mode: ComputeBuild) -> (HRESULT, std::time::Duration, bool) { let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.CS = bytecode(dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + // Try the memory-mapped ID3D12PipelineLibrary1 first (persists real compiled ISA across runs + // on both AMD and NVIDIA without GetCachedBlob stub pitfalls). + let windows = crate::gpu::recomp::pso::mem_windows(); + let lib_key = pso_lib::compute_key(dxil, samplers, copy.Flags.0, windows, mode == ComputeBuild::Chain); + if pso_lib::try_load_compute(this, &lib_key, ©, riid, ppv) { + return (S_OK, std::time::Duration::ZERO, true); + } // A program built again gets the driver's own result of its first build: a retail title // made 14 big compute pipelines twice while loading, 13 - 30 s each the second time. let key = compute_blob_key(dxil, rs as usize, copy.Flags.0); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path_for(dxil, copy.Flags.0, mode == ComputeBuild::Chain); + let disk = driver_cache::path_for_root(dxil, copy.Flags.0, mode == ComputeBuild::Chain, samplers); let from_disk = cached.is_none(); if from_disk { cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); @@ -5977,7 +5988,22 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL hr = retried; in_driver += took; } - let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; + let mut reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; + // Detect drivers that silently ignore a stale CachedPSO blob, compile from DXIL, and return S_OK. + if reused && in_driver >= std::time::Duration::from_millis(250) { + if let (Some(supplied), Some(actual)) = (cached.as_deref(), read_pso_cached_blob(*ppv)) { + if actual.len() != supplied.len() { + reused = false; + forget_compute_blob(key); + if from_disk { + driver_cache::note(false, disk.as_deref()); + } + } + } + } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + pso_lib::store_pipeline(this, &lib_key, *ppv); + } if hr >= 0 && !reused { let (memory, to_disk) = compute_blob_kept(dxil.len(), in_driver, driver_cache::compute_keep_threshold()); if let (Some(p), Some(b)) = (disk.as_deref(), keep_compute_blob(key, *ppv, memory, to_disk && disk.is_some())) { @@ -6004,7 +6030,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL /// `XCL_PSO_DISK_CACHE=0`: off. pub(crate) mod driver_cache { use std::path::{Path, PathBuf}; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; /// builds shorter than this are not worth a file const KEEP: std::time::Duration = std::time::Duration::from_millis(250); @@ -6015,7 +6041,31 @@ pub(crate) mod driver_cache { static HITS: AtomicU64 = AtomicU64::new(0); static STALE: AtomicU64 = AtomicU64::new(0); static STORED: AtomicU64 = AtomicU64::new(0); - static KEEP_FIXTURES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + static KEEP_FIXTURES: AtomicBool = AtomicBool::new(false); + static REFERENCE_BLOBS: AtomicBool = AtomicBool::new(false); + + /// AMD's cached-PSO blobs name entries in the driver's own cache instead of containing + /// self-sufficient code. Default them off on AMD (where `ID3D12PipelineLibrary1` persists real + /// compiled ISA across runs) unless `XCL_PSO_DISK_CACHE=1` forces them on. + pub fn note_vendor(vendor: u32) { + let references = reference_blob_vendor(vendor); + let was = REFERENCE_BLOBS.fetch_or(references, Ordering::Relaxed); + if references && !was && !enabled() { + crate::xlog_info!("D3D12.X: driver-blob disk cache off on AMD (using pipeline library; XCL_PSO_DISK_CACHE=1: force on)"); + } + } + + fn reference_blob_vendor(vendor: u32) -> bool { + vendor == 0x1002 + } + + /// True when `hr` indicates the driver rejected a persisted cache/library blob as incompatible + /// or corrupt (safe to discard), rather than a transient error such as OOM or device removal. + pub(crate) fn refused(hr: i32) -> bool { + const D3D12_ERROR_ADAPTER_NOT_FOUND: i32 = 0x887E_0001u32 as i32; + const D3D12_ERROR_DRIVER_VERSION_MISMATCH: i32 = 0x887E_0002u32 as i32; + matches!(hr, crate::util::E_INVALIDARG | D3D12_ERROR_ADAPTER_NOT_FOUND | D3D12_ERROR_DRIVER_VERSION_MISMATCH) + } pub(super) fn keep_fixtures() -> bool { KEEP_FIXTURES.load(Ordering::Relaxed) @@ -6029,6 +6079,18 @@ pub(crate) mod driver_cache { (HITS.load(Ordering::Relaxed), STALE.load(Ordering::Relaxed), STORED.load(Ordering::Relaxed)) } + fn samplers_hash(samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> u64 { + let mut bytes = Vec::with_capacity(8 + samplers.len() * 17); + bytes.extend_from_slice(&(samplers.len() as u64).to_le_bytes()); + for (words, cmp) in samplers { + for &w in words { + bytes.extend_from_slice(&w.to_le_bytes()); + } + bytes.push(*cmp as u8); + } + crate::gpu::shader::fnv64(&bytes) + } + /// The file of the pipeline made from `dxil` with `flags`. pub fn name(dxil: &[u8], flags: i32) -> String { name_for(dxil, flags, false) @@ -6037,8 +6099,18 @@ pub(crate) mod driver_cache { /// Like [`name`], using `.chain.pso` for pipelines built with the dispatch chain's root /// signature (`dispatch_chain`). pub fn name_for(dxil: &[u8], flags: i32, chained: bool) -> String { + name_for_root(dxil, flags, chained, &[]) + } + + /// Like [`name_for`], keying ordered static samplers into the filename when non-empty while + /// preserving legacy filenames for empty-sampler roots (PR #1420 / ba44b52c). + pub fn name_for_root(dxil: &[u8], flags: i32, chained: bool, samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> String { let ext = if chained { "chain.pso" } else { "pso" }; - format!("{:016x}-{:x}-{:x}.{ext}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags) + if samplers.is_empty() { + format!("{:016x}-{:x}-{:x}.{ext}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags) + } else { + format!("{:016x}-{:x}-{:x}-s{:016x}.{ext}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags, samplers_hash(samplers)) + } } /// The file of a translated graphics pipeline keyed by its full state + shader digest. @@ -6046,9 +6118,21 @@ pub(crate) mod driver_cache { format!("gfx-{hash:016x}-{bytes:x}.pso") } + fn env_setting() -> Option { + static ON: std::sync::OnceLock> = std::sync::OnceLock::new(); + *ON.get_or_init(|| configured(std::env::var("XCL_PSO_DISK_CACHE").ok().as_deref())) + } + + fn configured(value: Option<&str>) -> Option { + value.map(|v| v.trim() != "0") + } + + fn enabled_with(setting: Option, reference_blobs: bool) -> bool { + setting.unwrap_or(!reference_blobs) + } + pub fn enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")) + enabled_with(env_setting(), REFERENCE_BLOBS.load(Ordering::Relaxed)) } pub fn path(dxil: &[u8], flags: i32) -> Option { @@ -6056,7 +6140,11 @@ pub(crate) mod driver_cache { } pub fn path_for(dxil: &[u8], flags: i32, chained: bool) -> Option { - enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for(dxil, flags, chained))) + path_for_root(dxil, flags, chained, &[]) + } + + pub fn path_for_root(dxil: &[u8], flags: i32, chained: bool, samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> Option { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for_root(dxil, flags, chained, samplers))) } pub fn graphics_path(hash: u64, bytes: usize) -> Option { @@ -6196,10 +6284,29 @@ pub(crate) mod driver_cache { // (the length is in the name: two programs of one hash and different lengths differ) assert!(name(&[0u8; 0x1234], 2).ends_with("-1234-2.pso")); assert_eq!(name_for(b"abc", 0, false), name(b"abc", 0)); + assert_eq!(name_for_root(b"abc", 0, false, &[]), name(b"abc", 0)); + let s1 = [([1u32, 2, 3, 4], false)]; + let s2 = [([1u32, 2, 3, 5], false)]; + assert_ne!(name_for_root(b"abc", 0, false, &s1), name(b"abc", 0)); + assert_ne!(name_for_root(b"abc", 0, false, &s1), name_for_root(b"abc", 0, false, &s2)); assert_ne!(name_for(b"abc", 0, true), name_for(b"abc", 0, false)); assert!(name_for(&[0u8; 0x1234], 2, true).ends_with("-1234-2.chain.pso")); } + #[test] + fn disk_blobs_default_off_only_for_amd_and_can_be_overridden() { + assert!(reference_blob_vendor(0x1002)); + assert!(!reference_blob_vendor(0x10de)); // NVIDIA + assert!(!reference_blob_vendor(0x8086)); // Intel + assert!(!reference_blob_vendor(0x1414)); // WARP + + assert!(!enabled_with(None, true)); + assert!(enabled_with(None, false)); + assert!(enabled_with(configured(Some("1")), true)); + assert!(!enabled_with(configured(Some(" 0 ")), false)); + assert_eq!(configured(None), None); + } + /// A graphics pipeline's file follows its description's key, the adapter and driver and /// the window count, and the same inputs name the same file in every run (a fixed hash, /// none seeded per process). @@ -7095,12 +7202,31 @@ unsafe fn graphics_pso_through_cache( |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((record, has_cached)), f), create, ); + let mut build = build; if build.cache_eligible { if let (Some(b), Some(p)) = (blob_of(), disk) { driver_cache::keep_at(p, &b, build.in_driver, keep_min); } - } else if build.reused && from_disk { - driver_cache::note(true, None); + } else if build.reused { + // Detect drivers that silently ignore a stale CachedPSO blob, compile from DXIL, and return S_OK. + if build.in_driver >= std::time::Duration::from_millis(250) { + if let (Some(supplied), Some(actual)) = (cached.as_deref(), blob_of()) { + if actual.len() != supplied.len() { + build.reused = false; + if let Some(blob) = &cached { forget_graphics_blob(gkey, blob); } + if from_disk { + driver_cache::note(false, disk); + } + if let Some(p) = disk { + driver_cache::keep_at(p, &actual, build.in_driver, keep_min); + } + return build; + } + } + } + if from_disk { + driver_cache::note(true, None); + } } build } @@ -7180,6 +7306,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } pc_topology_type(&mut copy); let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); + let debug_override = debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) || debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash); if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); } @@ -7188,24 +7315,34 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); - // (no file without the adapter's identity: it could be another adapter's) - let driver = driver_identity(this); - let disk = driver.and_then(|id| driver_cache::graphics_path(driver_cache::graphics_file_hash(gkey, id, crate::gpu::recomp::pso::mem_windows()), bytes)); - // (for the driver compile log of this pipeline only) - GRAPHICS_STAGES.with(|s| s.set(Some((vs_took, ps_took)))); - // (a preparation worker keeps every blob: the title builds these pipelines at once from them) - let keep_min = if PREPARING.load(Ordering::Relaxed) { std::time::Duration::ZERO } else { driver_cache::keep_threshold() }; - let build = graphics_pso_through_cache( - gkey, - disk.as_deref(), - keep_min, - &mut copy, - rect_gs.is_some(), - ps_hash, - |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), - || keep_graphics_blob(gkey, *ppv, bytes), - ); - GRAPHICS_STAGES.with(|s| s.set(None)); + let windows = crate::gpu::recomp::pso::mem_windows(); + let lib_key = (!debug_override).then(|| pso_lib::graphics_key(gkey, windows)); + let mut from_lib = false; + let build = if let Some(key) = lib_key.as_deref().filter(|key| pso_lib::try_load_graphics(this, key, ©, riid, ppv)) { + let _ = key; + from_lib = true; + GraphicsPsoBuild { hr: S_OK, in_driver: std::time::Duration::ZERO, reused: true, cache_eligible: false } + } else { + // (no file without the adapter's identity: it could be another adapter's) + let driver = driver_identity(this); + let disk = driver.and_then(|id| driver_cache::graphics_path(driver_cache::graphics_file_hash(gkey, id, windows), bytes)); + // (for the driver compile log of this pipeline only) + GRAPHICS_STAGES.with(|s| s.set(Some((vs_took, ps_took)))); + // (a preparation worker keeps every blob: the title builds these pipelines at once from them) + let keep_min = if PREPARING.load(Ordering::Relaxed) { std::time::Duration::ZERO } else { driver_cache::keep_threshold() }; + let b = graphics_pso_through_cache( + gkey, + disk.as_deref(), + keep_min, + &mut copy, + rect_gs.is_some(), + ps_hash, + |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), + || keep_graphics_blob(gkey, *ppv, bytes), + ); + GRAPHICS_STAGES.with(|s| s.set(None)); + b + }; let hr = build.hr; if hr < 0 { note_translation_error(format!( @@ -7218,6 +7355,17 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const )); return None; } + if !from_lib && !ppv.is_null() && !(*ppv).is_null() { + if let Some(key) = lib_key { + let final_key = if rect_gs.is_some() && copy.GS.pShaderBytecode.is_null() { + let dropped_gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), None, &samplers); + pso_lib::graphics_key(dropped_gkey, windows) + } else { + key + }; + pso_lib::store_pipeline(this, &final_key, *ppv); + } + } let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); @@ -8220,7 +8368,31 @@ unsafe fn build_two_pass_pso( let from_disk = mem.is_none(); let cached = mem.or_else(|| disk.and_then(driver_cache::load).map(std::sync::Arc::new)); if let Some(blob) = cached { - if let Ok((hr, pso, _)) = attempt(Some(&blob)) { + if let Ok((hr, pso, took)) = attempt(Some(&blob)) { + // Detect drivers that silently ignore CachedPSO, compile from DXIL, and return S_OK. + if took >= std::time::Duration::from_millis(250) { + if let Some(actual) = read_pso_cached_blob(pso.as_raw()) { + if actual.len() != blob.len() { + if let Some((map, total)) = COMPUTE_BLOBS.lock().unwrap().as_mut() { + if map.get(&cache.key).is_some_and(|b| std::sync::Arc::ptr_eq(b, &blob)) { + *total -= map.remove(&cache.key).unwrap().len(); + } + } + if from_disk || disk.is_some_and(|p| p.is_file()) { + driver_cache::note(false, disk); + } + let preparing = PREPARING.load(Ordering::Relaxed); + let min = if preparing { std::time::Duration::ZERO } else { driver_cache::keep_threshold() }; + if let Some(path) = disk.filter(|_| took >= min) { + driver_cache::keep_at(path, &actual, took, min); + } + if !preparing && (bytes >= COMPUTE_BLOB_MIN_DXIL || took >= min) { + store_compute_blob(cache.key, std::sync::Arc::new(actual)); + } + return Ok((hr, pso, false)); + } + } + } if from_disk { driver_cache::note(true, None); store_compute_blob(cache.key, blob); @@ -8330,10 +8502,24 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let driver = driver_identity(this); let persist = driver.is_some() && driver_cache::enabled(); let windows = crate::gpu::recomp::pso::mem_windows(); - let cs = TwoPassBlob::new(two_pass_cs_key(&tp.cs, &tp.samplers, driver.unwrap_or(0), windows), tp.cs.len(), rs, false, persist); + let cs_hash = two_pass_cs_key(&tp.cs, &tp.samplers, driver.unwrap_or(0), windows); + let cs = TwoPassBlob::new(cs_hash, tp.cs.len(), rs, false, persist); let mesh = two_pass_stream_key(&stream.0, ps_samplers, driver.unwrap_or(0), windows) .map(|(h, n)| TwoPassBlob::new(h, n, mesh_rs, true, persist)); + // Try loading both halves from the memory-mapped pipeline library before acquiring any cold + // compile slot so warm runs bypass `huge_compile_turn` and commit waits completely. + let mesh_lib_key = mesh.as_ref().map(|m| pso_lib::two_pass_mesh_key(m.key.0, stream.shader_bytes())); + let cs_lib_key = pso_lib::two_pass_cs_key_str(cs_hash, tp.cs.len()); + let mut mesh_from_lib = None; + if let Some(key) = mesh_lib_key.as_deref() { + let mut raw_mesh = std::ptr::null_mut(); + if pso_lib::try_load_stream(this, key, &stream.0, riid, &mut raw_mesh) && !raw_mesh.is_null() { + mesh_from_lib = Some(ID3D12PipelineState::from_raw(raw_mesh)); + } + } + let cs_from_lib = pso_lib::try_load_compute_raw(this, &cs_lib_key, rs, &tp.cs).map(|raw| ID3D12PipelineState::from_raw(raw)); + // Take at most one cold turn for the pair, also when a cached attempt needs a retry. let bytes = stream.shader_bytes() + tp.cs.len(); let mut cold_slot = None; @@ -8345,47 +8531,64 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); - let mesh_result = build_two_pass_pso("passthrough mesh graphics pass", stream.shader_bytes(), mesh.as_ref(), &mut take_cold_slot, |blob, out| { - let mut cached_stream; - let stream = if let Some(blob) = blob { - cached_stream = StreamOut(stream.0.clone(), stream.1); - cached_stream.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &D3D12_CACHED_PIPELINE_STATE { - pCachedBlob: blob.as_ptr().cast(), CachedBlobSizeInBytes: blob.len(), - }); - &cached_stream - } else { - stream - }; - let desc = [stream.0.len(), stream.0.as_ptr() as usize]; - finish_pso(this, fs, desc.as_ptr().cast(), riid, out) - }); - let (hr, mesh_pso, mesh_reused) = match mesh_result { - Ok(result) => result, - Err(hr) => { - note_translation_error(format!("the driver rejected the mesh pipeline from the console {kind} ({hr:#x})")); - return E_INVALIDARG; + let (hr, mesh_pso, mesh_reused) = if let Some(pso) = mesh_from_lib { + (S_OK, pso, true) + } else { + let mesh_result = build_two_pass_pso("passthrough mesh graphics pass", stream.shader_bytes(), mesh.as_ref(), &mut take_cold_slot, |blob, out| { + let mut cached_stream; + let stream = if let Some(blob) = blob { + cached_stream = StreamOut(stream.0.clone(), stream.1); + cached_stream.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: blob.as_ptr().cast(), CachedBlobSizeInBytes: blob.len(), + }); + &cached_stream + } else { + stream + }; + let desc = [stream.0.len(), stream.0.as_ptr() as usize]; + finish_pso(this, fs, desc.as_ptr().cast(), riid, out) + }); + match mesh_result { + Ok((hr, pso, reused)) => { + if let Some(key) = mesh_lib_key.as_deref() { + pso_lib::store_pipeline(this, key, pso.as_raw()); + } + (hr, pso, reused) + } + Err(hr) => { + note_translation_error(format!("the driver rejected the mesh pipeline from the console {kind} ({hr:#x})")); + return E_INVALIDARG; + } } }; - let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); - let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); - desc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); - desc.CS = bytecode(&tp.cs); - let iid = pc_iid(Kind::PipelineState); - let compute_result = build_two_pass_pso("NGG compute pass", tp.cs.len(), Some(&cs), &mut take_cold_slot, |blob, out| { - desc.CachedPSO = blob.map_or_else(Default::default, |b| D3D12_CACHED_PIPELINE_STATE { - pCachedBlob: b.as_ptr().cast(), CachedBlobSizeInBytes: b.len(), + let (_, compute, cs_reused) = if let Some(pso) = cs_from_lib { + (S_OK, pso, true) + } else { + let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + desc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + desc.CS = bytecode(&tp.cs); + let iid = pc_iid(Kind::PipelineState); + let compute_result = build_two_pass_pso("NGG compute pass", tp.cs.len(), Some(&cs), &mut take_cold_slot, |blob, out| { + desc.CachedPSO = blob.map_or_else(Default::default, |b| D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: b.as_ptr().cast(), CachedBlobSizeInBytes: b.len(), + }); + driver_pso(fc, this, (&desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC).cast(), &iid, out) }); - driver_pso(fc, this, (&desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC).cast(), &iid, out) - }); - drop(cold_slot); - let (_, compute, cs_reused) = match compute_result { - Ok(result) => result, - Err(hr) => { - note_translation_error(format!("the driver rejected the NGG compute pass of the console {kind} ({hr:#x})")); - return E_INVALIDARG; + match compute_result { + Ok((hr, pso, reused)) => { + pso_lib::store_pipeline(this, &cs_lib_key, pso.as_raw()); + (hr, pso, reused) + } + Err(hr) => { + drop(cold_slot); + note_translation_error(format!("the driver rejected the NGG compute pass of the console {kind} ({hr:#x})")); + return E_INVALIDARG; + } } }; + drop(cold_slot); *ppv = mesh_pso.into_raw(); note_pso_rs(*ppv, mesh_rs); @@ -12993,3 +13196,340 @@ mod uma_heap_tests { assert_eq!(u.used(), used + (192 << 10)); } } + +/// Flush any newly compiled pipelines in the memory-mapped `ID3D12PipelineLibrary1` to a fresh +/// generation file before process exit (`WM_CLOSE`, `XCL_RUN_SECONDS`, or normal title return). +pub(crate) fn flush_pipeline_library() { + pso_lib::flush_now(); +} + +/// Runtime wiring for `pso_library::MmapPipelineLibrary`: deterministic cross-run pipeline keys, +/// kept-open per-device library lookup, load/store helpers, and debounced background generational +/// persistence (zero heap copy, never replaces an actively mapped `.plib`). +mod pso_lib { + use super::*; + use crate::hle::d3d12x::pso_library::MmapPipelineLibrary; + use std::sync::Arc; + use std::time::{Duration, Instant}; + + /// Minimum newly stored pipelines before triggering a periodic background generation save. + const SAVE_BATCH_THRESHOLD: u64 = 32; + /// Minimum spacing between periodic background saves while pipelines are streaming in. + const SAVE_MIN_INTERVAL: Duration = Duration::from_secs(15); + /// Idle delay after the last stored pipeline before flushing any remaining tail (`>= 1` dirty). + const SAVE_IDLE_FLUSH: Duration = Duration::from_secs(5); + + struct LibState { + device: usize, + lib: Option>, + stored_keys: HashSet, + hits: u64, + stores: u64, + } + + static LIB_STATE: Mutex> = Mutex::new(None); + static LAST_STORE_MS: AtomicU64 = AtomicU64::new(0); + static LAST_SAVE_MS: AtomicU64 = AtomicU64::new(0); + static SAVER_STARTED: std::sync::Once = std::sync::Once::new(); + static EPOCH: OnceLock = OnceLock::new(); + + fn now_ms() -> u64 { + EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 + } + + /// Pure save-scheduling decision (unit-testable on CPU): + /// - Save immediately when `dirty >= SAVE_BATCH_THRESHOLD` and at least `SAVE_MIN_INTERVAL` + /// elapsed since the last save. + /// - Or save any tail (`dirty > 0`) once no new pipeline has been stored for `SAVE_IDLE_FLUSH`. + pub(super) fn should_background_save(dirty: u64, now_ms: u64, last_store_ms: u64, last_save_ms: u64) -> bool { + if dirty == 0 { + return false; + } + let since_save = now_ms.saturating_sub(last_save_ms); + let since_store = now_ms.saturating_sub(last_store_ms); + (dirty >= SAVE_BATCH_THRESHOLD && since_save >= SAVE_MIN_INTERVAL.as_millis() as u64) + || (last_store_ms > 0 && since_store >= SAVE_IDLE_FLUSH.as_millis() as u64 && since_save >= SAVE_IDLE_FLUSH.as_millis() as u64) + } + + fn ensure_saver_thread() { + SAVER_STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-plib-save".into()).spawn(|| loop { + std::thread::sleep(Duration::from_secs(2)); + let lib = LIB_STATE.lock().unwrap().as_ref().and_then(|s| s.lib.clone()); + let Some(lib) = lib else { continue }; + let now = now_ms(); + let dirty = lib.dirty_count(); + if should_background_save(dirty, now, LAST_STORE_MS.load(Ordering::Acquire), LAST_SAVE_MS.load(Ordering::Acquire)) { + if unsafe { lib.save_if_dirty(1) }.is_some() { + LAST_SAVE_MS.store(now_ms(), Ordering::Release); + } + } + }); + }); + } + + unsafe fn library_for(device: *mut c_void) -> Option> { + if cfg!(test) || PREPARING.load(Ordering::Relaxed) || device.is_null() || !super::super::pso_library::enabled() { + return None; + } + let dev_key = device as usize; + { + let g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_ref().filter(|s| s.device == dev_key) { + return s.lib.clone(); + } + } + let adapter = { + let s = ADAPTER.lock().unwrap().clone(); + if s.is_empty() { "default".to_string() } else { s } + }; + let opened = ID3D12Device::from_raw_borrowed(&device) + .and_then(|dev| MmapPipelineLibrary::open_or_create(dev, &adapter)) + .map(Arc::new); + let mut g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_ref().filter(|s| s.device == dev_key) { + return s.lib.clone(); + } + let ret = opened.clone(); + *g = Some(LibState { + device: dev_key, + lib: opened, + stored_keys: HashSet::new(), + hits: 0, + stores: 0, + }); + if ret.is_some() { + ensure_saver_thread(); + } + ret + } + + pub(super) fn flush_now() { + let lib = LIB_STATE.lock().unwrap().as_ref().and_then(|s| s.lib.clone()); + if let Some(lib) = lib { + if unsafe { lib.flush() }.is_some() { + LAST_SAVE_MS.store(now_ms(), Ordering::Release); + } + } + } + + fn fnv_feed(h: &mut u64, bytes: &[u8]) { + for &b in bytes { + *h ^= b as u64; + *h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + } + + fn samplers_digest(samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &(samplers.len() as u64).to_le_bytes()); + for (w, cmp) in samplers { + for &x in w { + fnv_feed(&mut h, &x.to_le_bytes()); + } + fnv_feed(&mut h, &[*cmp as u8]); + } + h + } + + /// Deterministic cross-run key for a translated compute pipeline (whole or dispatch-chain piece). + pub(super) fn compute_key(dxil: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], flags: i32, windows: u32, chained: bool) -> String { + let tag = if chained { "cc" } else { "c" }; + format!( + "{tag}-{:016x}-{:x}-{:016x}-{:x}-{:x}", + crate::gpu::shader::fnv64(dxil), + dxil.len(), + samplers_digest(samplers), + flags as u32, + windows + ) + } + + /// Deterministic cross-run key for a translated graphics pipeline (reusing `graphics_blob_key`). + pub(super) fn graphics_key(gkey: (u64, usize), windows: u32) -> String { + format!("g-{:016x}-{:x}-{:x}", gkey.0, gkey.1, windows) + } + + /// Deterministic cross-run keys for two-pass mesh & NGG compute pipelines. + pub(super) fn two_pass_mesh_key(hash: u64, shader_bytes: usize) -> String { + format!("tm-{hash:016x}-{shader_bytes:x}") + } + + pub(super) fn two_pass_cs_key_str(hash: u64, cs_bytes: usize) -> String { + format!("tc-{hash:016x}-{cs_bytes:x}") + } + + unsafe fn adopt_loaded_pso(device: *mut c_void, pso: ID3D12PipelineState, riid: *const GUID, ppv: *mut *mut c_void) -> bool { + if ppv.is_null() { + return false; + } + let raw = pso.into_raw(); + let target_iid = if riid.is_null() { pc_iid(Kind::PipelineState) } else { *riid }; + let wanted_iid = pc_iid(Kind::PipelineState); + let same_iid = (target_iid.data1, target_iid.data2, target_iid.data3, target_iid.data4) + == (wanted_iid.data1, wanted_iid.data2, wanted_iid.data3, wanted_iid.data4); + let final_ptr = if same_iid { + raw + } else { + let vt = *(raw as *const *const usize); + let qi: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt); + let mut out = std::ptr::null_mut(); + let hr = qi(raw, &target_iid, &mut out); + drop(ID3D12PipelineState::from_raw(raw)); + if hr < 0 || out.is_null() { + return false; + } + out + }; + adopt(final_ptr, Kind::PipelineState); + let _ = device; + *ppv = final_ptr; + true + } + + fn note_hit(kind: &str) { + let mut g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + s.hits += 1; + let n = s.hits; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} pipelines loaded from memory-mapped pipeline library (latest: {kind})"); + } + } + } + + pub(super) unsafe fn try_load_compute( + device: *mut c_void, + key: &str, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + if desc.pRootSignature.is_none() || desc.CS.pShaderBytecode.is_null() || desc.CS.BytecodeLength == 0 || ppv.is_null() { + return false; + } + let Some(lib) = library_for(device) else { return false }; + let Some(pso) = lib.load_compute(key, desc) else { return false }; + if adopt_loaded_pso(device, pso, riid, ppv) { + note_hit("compute"); + true + } else { + false + } + } + + pub(super) unsafe fn try_load_compute_raw( + device: *mut c_void, + key: &str, + rs: *mut c_void, + cs: &[u8], + ) -> Option<*mut c_void> { + if rs.is_null() || cs.is_empty() { + return None; + } + let lib = library_for(device)?; + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + desc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + desc.CS = bytecode(cs); + let pso = lib.load_compute(key, &desc)?; + note_hit("two-pass compute"); + Some(pso.into_raw()) + } + + pub(super) unsafe fn try_load_graphics( + device: *mut c_void, + key: &str, + desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + if desc.pRootSignature.is_none() || desc.VS.pShaderBytecode.is_null() || desc.VS.BytecodeLength == 0 || ppv.is_null() { + return false; + } + let Some(lib) = library_for(device) else { return false }; + let Some(pso) = lib.load_graphics(key, desc) else { return false }; + if adopt_loaded_pso(device, pso, riid, ppv) { + note_hit("graphics"); + true + } else { + false + } + } + + pub(super) unsafe fn try_load_stream( + device: *mut c_void, + key: &str, + stream_bytes: &[u8], + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + if stream_bytes.is_empty() || ppv.is_null() { + return false; + } + let Some(lib) = library_for(device) else { return false }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: stream_bytes.len(), + pPipelineStateSubobjectStream: stream_bytes.as_ptr() as *mut c_void, + }; + let Some(pso) = lib.load_stream(key, &desc) else { return false }; + if adopt_loaded_pso(device, pso, riid, ppv) { + note_hit("two-pass mesh"); + true + } else { + false + } + } + + pub(super) unsafe fn store_pipeline(device: *mut c_void, key: &str, pso: *mut c_void) { + if pso.is_null() { + return; + } + let Some(lib) = library_for(device) else { return }; + { + let mut g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if !s.stored_keys.insert(key.to_string()) { + return; + } + } + } + if let Some(borrowed) = ID3D12PipelineState::from_raw_borrowed(&pso) { + if lib.store(key, borrowed) { + LAST_STORE_MS.store(now_ms(), Ordering::Release); + let mut g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + s.stores += 1; + let n = s.stores; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} pipelines stored in memory-mapped pipeline library"); + } + } + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn background_save_triggers_on_batch_or_idle_tail() { + assert!(!should_background_save(0, 100_000, 1_000, 0)); + assert!(!should_background_save(5, 10_000, 9_000, 0)); + assert!(should_background_save(32, 20_000, 19_500, 0)); + assert!(!should_background_save(32, 20_000, 19_500, 10_000)); + assert!(should_background_save(1, 20_000, 14_000, 10_000)); + } + + #[test] + fn compute_and_graphics_library_keys_are_deterministic_and_distinct() { + let s1 = [([1u32, 2, 3, 4], false)]; + let s2 = [([1u32, 2, 3, 5], false)]; + assert_eq!(compute_key(b"dxil", &s1, 0, 16, false), compute_key(b"dxil", &s1, 0, 16, false)); + assert_ne!(compute_key(b"dxil", &s1, 0, 16, false), compute_key(b"dxil", &s2, 0, 16, false)); + assert_ne!(compute_key(b"dxil", &s1, 0, 16, false), compute_key(b"dxil", &s1, 0, 1, false)); + assert_ne!(compute_key(b"dxil", &s1, 0, 16, false), compute_key(b"dxil", &s1, 0, 16, true)); + assert_ne!(graphics_key((0x1234, 512), 16), graphics_key((0x1234, 512), 1)); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 4f8f069e5f..06cdbfc774 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -39,6 +39,7 @@ struct PipelineBuilder { device: ID3D12Device, create: PsoFn, signature: ID3D12RootSignature, + samplers: Vec, flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, @@ -49,14 +50,14 @@ impl PipelineBuilder { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); let (hr, in_driver, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), - dxil, self.record, iid, &mut raw, ComputeBuild::Chain); + dxil, &self.samplers, self.record, iid, &mut raw, ComputeBuild::Chain); // (as `translated_compute_pso_once` logs a huge whole program the driver refuses) if hr < 0 && dxil.len() >= huge_pso_bytes() { crate::xlog_warn!( "D3D12.X: the driver refused a dispatch chain's compute PSO of record {:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver", self.record, dxil.len(), - driver_cache::name(dxil, self.flags.0), + driver_cache::name_for_root(dxil, self.flags.0, true, &self.samplers), in_driver.as_millis() ); } @@ -119,7 +120,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; let rs = signature.as_raw() as usize; let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, - flags: desc.Flags, node: desc.NodeMask, record }); + samplers: samplers.to_vec(), flags: desc.Flags, node: desc.NodeMask, record }); let jobs = (0..plan.pieces.len()).map(|i| { let plan = plan.clone(); let builder = builder.clone(); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 8e328c157d..28ebab8076 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -256,6 +256,7 @@ pub fn host_main(boot_path: &Path) -> i32 { std::thread::sleep(std::time::Duration::from_secs(secs)); let (shown, presented) = crate::hle::d3d12x::present::counters(); crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)"); + crate::hle::d3d12x::real::flush_pipeline_library(); crate::report::write_final(None); crate::log::flush(); crate::hle::d3d12x::real::end_title(0); @@ -274,6 +275,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::report::write_final(None); let code = crate::loader::run_main(&main); crate::xlog_info!("game entry point returned code {code}"); + crate::hle::d3d12x::real::flush_pipeline_library(); crate::report::write_final(None); crate::log::flush(); code as i32 From 82d5eea89cef51ac6948a5d1a9923bfc2b88deea Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:24:16 +0100 Subject: [PATCH 047/175] Shaders: count per-variant pipeline builds in preparation progress UI Worker processes previously reported record scan counts (hitting 99% before building any compute pipelines) and did not emit per-pipeline variant progress during make_pipelines; single-process preparation also counted once per record even when a record produced multiple split variants. - Track actual pipeline variants (including split dispatch-chain pieces) in Pipelines and emit per-variant progress lines (pipelines: done/total) from workers on every completed variant. - Surface pipelines_done / pipelines_total in LaunchPreparation and preparation.rs so both the progress bar and StallClock advance on every built pipeline variant. - Also fix debug-mode wrapping arithmetic in texture_upload::tests::some_ranges. --- .../xcl/src/hle/d3d12x/present/preparation.rs | 46 +++-- crates/xcl/src/hle/d3d12x/texture_upload.rs | 2 +- crates/xcl/src/shaders.rs | 159 ++++++++++++++---- 3 files changed, 163 insertions(+), 44 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs index 0ba6728da3..48d5f53dac 100644 --- a/crates/xcl/src/hle/d3d12x/present/preparation.rs +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -73,14 +73,24 @@ pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { said = Instant::now(); let workers = progress.workers.load(Ordering::Relaxed); let graphics = progress.graphics.load(Ordering::Relaxed); - crate::xlog_info!( - "Shader preparation: {} of {} {} {} after {} s", - progress.done.load(Ordering::Relaxed), - progress.total.load(Ordering::Relaxed), - if graphics { "graphics pipelines" } else { "records" }, - if graphics { format!("built by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "translated".to_string() }, - began.elapsed().as_secs() - ); + let pipe_total = progress.pipelines_total.load(Ordering::Relaxed); + let pipe_done = progress.pipelines_done.load(Ordering::Relaxed); + if !graphics && pipe_total > 0 { + crate::xlog_info!( + "Shader preparation: {pipe_done} of {pipe_total} compute pipelines built{} after {} s", + if workers != 0 { format!(" by {workers} workers") } else { String::new() }, + began.elapsed().as_secs() + ); + } else { + crate::xlog_info!( + "Shader preparation: {} of {} {} {} after {} s", + progress.done.load(Ordering::Relaxed), + progress.total.load(Ordering::Relaxed), + if graphics { "graphics pipelines" } else { "records" }, + if graphics { format!("built by {workers} workers") } else if workers != 0 { format!("checked for pipelines by {workers} workers") } else { "translated".to_string() }, + began.elapsed().as_secs() + ); + } } if let Some(parent) = &parent { if unsafe { WaitForSingleObject(parent.as_raw_handle(), 80) } == WAIT_OBJECT_0 { @@ -171,13 +181,19 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { let x = (rc.right - width) / 2; let y = ((rc.bottom - scale(150)) / 2).max(0); let row = |top, bottom| RECT { left: x, right: x+width, top: y+scale(top), bottom: y+scale(bottom) }; - let done = s.progress.done.load(Ordering::Relaxed); - let total = s.progress.total.load(Ordering::Relaxed); - let pct = percent(done, total, s.ready); - let (quiet, last) = s.clock.sample(done, s.start.elapsed()); let workers = s.progress.workers.load(Ordering::Relaxed); let graphics = workers != 0 && s.progress.graphics.load(Ordering::Relaxed); - let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if graphics { "Building graphics pipelines" } else if workers != 0 { "Building pipelines" } else { "Preparing shaders" }; + let pipe_total = s.progress.pipelines_total.load(Ordering::Relaxed); + let pipe_done = s.progress.pipelines_done.load(Ordering::Relaxed); + let building_compute = !graphics && pipe_total > 0; + let (done, total) = if building_compute { + (pipe_done, pipe_total) + } else { + (s.progress.done.load(Ordering::Relaxed), s.progress.total.load(Ordering::Relaxed)) + }; + let pct = percent(done, total, s.ready); + let (quiet, last) = s.clock.sample(done, s.start.elapsed()); + let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else if graphics { "Building graphics pipelines" } else if building_compute || workers != 0 { "Building pipelines" } else { "Preparing shaders" }; let mut title = row(0,48); title.right -= scale(84); text(dc, title, heading, scale(31), 600, 0xf7f5f1, DT_LEFT); @@ -187,10 +203,12 @@ unsafe fn paint(hwnd: HWND, s: &mut Screen) { fill(dc, RECT {right: x+(width as i64 * pct as i64/100) as i32, ..bar}, 0xbdb458); let count = if total == 0 { "Reading shader records…".into() } else if graphics { format!("{done} of {total} graphics pipelines built by {workers} worker processes") } + else if building_compute && workers != 0 { format!("{done} of {total} compute pipelines built by {workers} worker processes") } + else if building_compute { format!("{done} of {total} compute pipelines built") } else if workers != 0 { format!("{done} of {total} records checked by {workers} worker processes") } else { format!("{done} of {total} records processed") }; text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); - let mut times = if workers != 0 { format!("Large pipelines compile in the driver: {quiet} s since the last record") } else { format!("No shader progress for {quiet} s") }; + let mut times = if graphics || building_compute { format!("Large pipelines compile in the driver: {quiet} s since the last pipeline") } else if workers != 0 { format!("Scanning shader records: {quiet} s since the last record") } else { format!("No shader progress for {quiet} s") }; if let Some(ago) = last { times.push_str(&format!(" · Last stall ended {ago} s ago")); } text(dc, row(117,145), ×, scale(14), 400, 0xb4aaa4, DT_LEFT); BitBlt(dest, 0, 0, rc.right, rc.bottom, dc, 0, 0, SRCCOPY); diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index f53d9e8604..46201de8d7 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -1147,7 +1147,7 @@ mod tests { let mut at = seed * 37 % size.div_ceil(PAGE) * PAGE; let mut n = seed; while at < size && out.len() < 6 { - n = n * 1103515245 + 12345; + n = n.wrapping_mul(1103515245).wrapping_add(12345); let to = (at + PAGE * (1 + n / 65536 % 4)).min(size); out.push((at, to)); at = to + PAGE * (1 + n / 16 % (size / PAGE / 5 + 2)); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9a77dd71c7..6ad60a53d9 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1290,6 +1290,11 @@ struct Pipelines { most: usize, /// DXIL bytes a pipeline is still handed to the driver (`XCL_PIPELINE_MAX_KB`, 8 MiB; 0: off) max_dxil: usize, + /// actual pipeline variants (including split pieces) completed and queued for progress reporting + progress_done: AtomicUsize, + progress_total: AtomicUsize, + emit_progress: bool, + started: std::time::Instant, #[cfg(test)] cache_dir: Option, } @@ -1516,13 +1521,14 @@ impl Pipelines { unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; let sel = crate::gpu::adapter::Selector::from_env_or(adapter); - let dev = if sel == crate::gpu::adapter::Selector::Warp { + let (dev, vendor) = if sel == crate::gpu::adapter::Selector::Warp { let warp: IDXGIAdapter = factory.EnumWarpAdapter().map_err(|e| e.to_string())?; - crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())? + (crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?, 0) } else { - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; - crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())? + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + (crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?, desc.VendorId) }; + crate::hle::d3d12x::real::driver_cache::note_vendor(vendor); let most = pipeline_threads(); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); Ok(Pipelines { @@ -1539,21 +1545,47 @@ impl Pipelines { running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil, + progress_done: AtomicUsize::new(0), + progress_total: AtomicUsize::new(0), + emit_progress: std::env::var_os("XCL_PRECOMPILE_PARENT").is_some(), + started: std::time::Instant::now(), #[cfg(test)] cache_dir: None, }) } } + fn note_variant_done(&self, live_done: Option<&AtomicUsize>) { + let pd = self.progress_done.fetch_add(1, Ordering::Relaxed) + 1; + if let Some(live) = live_done { + live.fetch_add(1, Ordering::Relaxed); + } + if self.emit_progress { + let pt = self.progress_total.load(Ordering::Relaxed); + if pt > 0 { + eprintln!(" pipelines: {pd}/{pt} ({:.0} s)", self.started.elapsed().as_secs_f64()); + } + } + } + + /// Number of driver pipeline variants `make` will build for `c` (each split piece is its own pipeline). + fn variant_count(c: &recomp::pso::Compiled) -> usize { + c.dispatch_chain.as_deref().filter(|chain| chain.pieces.len() >= 2).map_or(1, |chain| chain.pieces.len()) + } + /// The compute pipeline of `c` (made and released). When direct translation split the program /// into a dispatch chain of at least two pieces, each piece is built and cached under the /// dispatch-chain root signature (`.chain.pso`) as the runtime does (`dispatch_chain::build`), /// instead of the unsplit whole container. fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); + self.make_with_progress(c, None, None); } fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { + self.make_with_progress(c, path_override, None); + } + + fn make_with_progress(&self, c: &recomp::pso::Compiled, path_override: Option, live_done: Option<&AtomicUsize>) { if path_override.is_none() { if let Some(chain) = c.dispatch_chain.as_deref().filter(|chain| chain.pieces.len() >= 2) { self.split_programs.fetch_add(1, Ordering::Relaxed); @@ -1561,7 +1593,7 @@ impl Pipelines { let workers = chain.pieces.len().min(self.most); if workers <= 1 { for piece in &chain.pieces { - self.make_one(piece, &c.samplers, true, None); + self.make_one_with_progress(piece, &c.samplers, true, None, live_done); } } else { let next = AtomicUsize::new(0); @@ -1570,7 +1602,7 @@ impl Pipelines { s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); let Some(piece) = chain.pieces.get(i) else { break }; - self.make_one(piece, &c.samplers, true, None); + self.make_one_with_progress(piece, &c.samplers, true, None, live_done); }); } }); @@ -1578,10 +1610,17 @@ impl Pipelines { return; } } - self.make_one(&c.dxil, &c.samplers, false, path_override); + self.make_one_with_progress(&c.dxil, &c.samplers, false, path_override, live_done); } - fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option) { + fn make_one_with_progress(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option, live_done: Option<&AtomicUsize>) { + struct DoneGuard<'a>(&'a Pipelines, Option<&'a AtomicUsize>); + impl Drop for DoneGuard<'_> { + fn drop(&mut self) { + self.0.note_variant_done(self.1); + } + } + let _done_guard = DoneGuard(self, live_done); use windows::Win32::Graphics::Direct3D12::*; let key: (bool, Vec) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); let rs = { @@ -1616,9 +1655,9 @@ impl Pipelines { let path = path_override.or_else(|| { #[cfg(test)] if let Some(dir) = self.cache_dir.as_deref() { - return Some(dir.join(driver_cache::name_for(dxil, desc.Flags.0, chained))); + return Some(dir.join(driver_cache::name_for_root(dxil, desc.Flags.0, chained, samplers))); } - driver_cache::path_for(dxil, desc.Flags.0, chained) + driver_cache::path_for_root(dxil, desc.Flags.0, chained, samplers) }); let mut cached = path.as_deref().and_then(driver_cache::load); let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; @@ -1740,11 +1779,26 @@ fn order_pipeline_jobs(jobs: &mut [PipelineJob]) { jobs.sort_by(|a, b| b.used.cmp(&a.used).then(b.compiled.dxil.len().cmp(&a.compiled.dxil.len()))); } -fn make_pipelines(pipelines: &Pipelines, mut jobs: Vec) { +fn make_pipelines(pipelines: &Pipelines, mut jobs: Vec, startup: Option<&LaunchPreparation>) { order_pipeline_jobs(&mut jobs); let used = jobs.iter().filter(|job| job.used).count(); - println!("pipelines: {} compute programs ({used} used earlier: first), {} driver compiles at once", jobs.len(), pipelines.most); - run_pipeline_jobs(jobs, pipelines.most, |job| pipelines.make(&job.compiled)); + let total_variants: usize = jobs.iter().map(|job| Pipelines::variant_count(&job.compiled)).sum(); + pipelines.progress_total.store(total_variants, Ordering::Relaxed); + if let Some(p) = startup { + p.pipelines_done.store(0, Ordering::Relaxed); + p.pipelines_total.store(total_variants, Ordering::Relaxed); + } + if pipelines.emit_progress && total_variants > 0 { + eprintln!(" pipelines: 0/{total_variants} ({:.0} s)", pipelines.started.elapsed().as_secs_f64()); + } + println!("pipelines: {} compute programs ({total_variants} variants, {used} used earlier: first), {} driver compiles at once", jobs.len(), pipelines.most); + let live_done = startup.map(|p| &p.pipelines_done); + run_pipeline_jobs(jobs, pipelines.most, |job| { + if startup.is_some_and(|p| p.cancel.load(Ordering::Relaxed)) { + return; + } + pipelines.make_with_progress(&job.compiled, None, live_done); + }); } fn run_pipeline_jobs(jobs: Vec, workers: usize, build: impl Fn(&T) + Sync) { @@ -1813,6 +1867,27 @@ mod pipeline_selection_tests { assert_eq!(matched, expected); assert_eq!(parse_pipeline_keys("not-a-key\n0000000000000000\n0000000000001234\n"), [0x1234].into_iter().collect()); } + + #[test] + fn pipeline_progress_parser_and_variant_counts_track_split_pieces() { + assert_eq!(pipeline_progress_count(" pipelines: 0/48 (0 s)"), Some((0, 48))); + assert_eq!(pipeline_progress_count(" pipelines: 17/48 (12 s)"), Some((17, 48))); + assert_eq!(pipeline_progress_count(" pipelines: 25 made, 0 refused"), None); + assert_eq!(pipeline_progress_count(" 400/26503 (12 s)"), None); + assert_eq!(progress_count(" 400/26503 (12 s)"), Some(400)); + + let single = job(true, 64).compiled; + assert_eq!(Pipelines::variant_count(&single), 1); + let split = recomp::pso::Compiled { + dispatch_chain: Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { + pieces: vec![vec![1], vec![2], vec![3]], + dwords_per_group: 4, + })), + dxil: vec![0; 64], + samplers: Vec::new(), + }; + assert_eq!(Pipelines::variant_count(&split), 3); + } } #[derive(Default)] @@ -1826,6 +1901,11 @@ pub(crate) struct LaunchPreparation { pub workers: AtomicUsize, /// The workers build graphics pipelines (`graphics_in_workers`): `done` and `total` count those. pub graphics: std::sync::atomic::AtomicBool, + /// Actual compute pipeline variants (including split pieces) built and queued across workers + /// or in-process (`make_pipelines`). Non-zero `pipelines_total` switches the counter from + /// record scanning to real per-pipeline progress. + pub pipelines_done: AtomicUsize, + pub pipelines_total: AtomicUsize, /// The shaders earlier runs used (`pso_async::earlier_used_shaders`), when there are any: /// only their records are translated before the title starts, and it translates another /// when it first uses it. `XCL_PREPARE_ALL=1`: every record, as without the list. @@ -1924,6 +2004,15 @@ fn progress_count(line: &str) -> Option { d.parse().ok() } +/// The per-variant pipeline count of a worker's progress line (` pipelines: 12/48 (7 s)`). +fn pipeline_progress_count(line: &str) -> Option<(usize, usize)> { + let rest = line.trim().strip_prefix("pipelines: ")?; + let (d, rest) = rest.split_once('/')?; + let (n, rest) = rest.split_once(' ')?; + if !rest.starts_with('(') { return None; } + Some((d.parse().ok()?, n.parse().ok()?)) +} + /// A pipeline one process builds: a file beside the driver blob it will write (`.claim`), /// made when the build starts and gone when it ends. A second process that finds it leaves the /// pipeline to the first. One left behind by a process that died is taken over after `STALE`. @@ -2026,8 +2115,12 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut let (done_before, total_before) = (progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed)); progress.done.store(0, Ordering::Relaxed); progress.total.store(records, Ordering::Relaxed); + progress.pipelines_done.store(0, Ordering::Relaxed); + progress.pipelines_total.store(0, Ordering::Relaxed); progress.workers.store(workers, Ordering::Relaxed); let counts: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); + let pipe_done: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); + let pipe_total: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); let summaries: Vec> = (0..workers).map(|_| Mutex::new(String::new())).collect(); let mut children = Vec::new(); for i in 0..workers { @@ -2039,14 +2132,19 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut let cancelled = std::thread::scope(|s| { for (i, child) in children.iter_mut() { let Some(err) = child.stderr.take() else { continue }; - let (count, summary) = (&counts[*i], &summaries[*i]); + let (count, pd, pt, summary) = (&counts[*i], &pipe_done[*i], &pipe_total[*i], &summaries[*i]); s.spawn(move || { // (a builder ends its progress lines with a line feed; others pass by) let mut r = std::io::BufReader::new(err); let mut buf = Vec::new(); while r.read_until(b'\n', &mut buf).is_ok_and(|n| n > 0) { for part in String::from_utf8_lossy(&buf).split(['\r', '\n']) { - if let Some(d) = progress_count(part) { count.store(d, Ordering::Relaxed); } + if let Some((done_p, total_p)) = pipeline_progress_count(part) { + pd.store(done_p, Ordering::Relaxed); + pt.store(total_p, Ordering::Relaxed); + } else if let Some(d) = progress_count(part) { + count.store(d, Ordering::Relaxed); + } if graphics_summary(part).is_some() { *summary.lock().unwrap() = part.to_string(); } } buf.clear(); @@ -2054,9 +2152,15 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut }); } loop { - // (a worker counts the records of its own slice) + // (a worker counts the records of its own slice, then each pipeline variant it builds) let d: usize = counts.iter().map(|c| c.load(Ordering::Relaxed)).sum(); progress.done.store(d.min(records), Ordering::Relaxed); + let pt: usize = pipe_total.iter().map(|c| c.load(Ordering::Relaxed)).sum(); + if pt > 0 { + let pd: usize = pipe_done.iter().map(|c| c.load(Ordering::Relaxed)).sum(); + progress.pipelines_total.store(pt, Ordering::Relaxed); + progress.pipelines_done.store(pd.min(pt), Ordering::Relaxed); + } if progress.cancel.load(Ordering::Relaxed) { for (_, child) in children.iter_mut() { let _ = child.kill(); } return true; @@ -2074,6 +2178,8 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut } } progress.workers.store(0, Ordering::Relaxed); + progress.pipelines_done.store(0, Ordering::Relaxed); + progress.pipelines_total.store(0, Ordering::Relaxed); progress.total.store(total_before, Ordering::Relaxed); progress.done.store(done_before, Ordering::Relaxed); (cancelled, failed, summaries.into_iter().map(|s| s.into_inner().unwrap()).collect()) @@ -2366,16 +2472,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { - if let Some(p) = pipelines { - if startup.is_some() { - p.make(&c); - if c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { - p.make_one(&c.dxil, &c.samplers, true, None); - } - } else { - let used = used_earlier.contains(&pipeline_key(&blob)); - pipeline_jobs.lock().unwrap().push(PipelineJob { used, compiled: c }); - } + if let Some(_p) = pipelines { + let used = used_earlier.contains(&pipeline_key(&blob)); + pipeline_jobs.lock().unwrap().push(PipelineJob { used, compiled: c }); } compiled.fetch_add(1, Ordering::Relaxed) } @@ -2465,8 +2564,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on println!("compute programs passed over (XCL_RT_LEAVE_OUT): {}", crate::gpu::rt_leave_out::left_out_count()); } if let Some(p) = pipelines { - if startup.is_none() { - make_pipelines(p, pipeline_jobs.into_inner().unwrap()); + make_pipelines(p, pipeline_jobs.into_inner().unwrap(), startup); + if let Some(progress) = startup { + progress.pipelines_done.store(0, Ordering::Relaxed); + progress.pipelines_total.store(0, Ordering::Relaxed); } println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); From f33df5a76b18d5805c4384d9f3fbc3eaf51a1849 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:48:46 +0100 Subject: [PATCH 048/175] D3D12.X: disable ID3D12PipelineLibrary1 by default on AMD (0x1002) On AMD RDNA4 (RX 9070 XT), ID3D12PipelineLibrary1 only serializes tiny stub entries (~0.2 MiB for 1,024+ pipelines) and loading/serializing two-pass pipelines through it triggers GPU page faults (0x887a0006 / DRED page fault). Default XCL_PSO_LIBRARY off on AMD (0x1002), where the driver's own DxCache handles cross-run shader caching, while keeping it enabled by default on NVIDIA/Intel (overridable via XCL_PSO_LIBRARY=1 or 0). Verified with a 140 s retail world run (1,597 frames, 0 device removals, 0 AMD TDR events). --- crates/xcl/src/hle/d3d12x/pso_library.rs | 49 ++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 3 +- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_library.rs b/crates/xcl/src/hle/d3d12x/pso_library.rs index f7f5ae2a5a..f3a440bcaf 100644 --- a/crates/xcl/src/hle/d3d12x/pso_library.rs +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -29,10 +29,45 @@ use windows_sys::Win32::System::Memory::{ const D3D12_ERROR_ADAPTER_NOT_FOUND_HR: i32 = 0x887E_0001u32 as i32; const D3D12_ERROR_DRIVER_VERSION_MISMATCH_HR: i32 = 0x887E_0002u32 as i32; -/// Whether the on-disk memory-mapped pipeline library is enabled (`XCL_PSO_LIBRARY=0` disables). +static AMD_VENDOR: AtomicBool = AtomicBool::new(false); + +fn env_override() -> Option { + static OVERRIDE: OnceLock> = OnceLock::new(); + *OVERRIDE.get_or_init(|| match std::env::var("XCL_PSO_LIBRARY") { + Ok(v) => match v.trim() { + "" => None, + "0" => Some(false), + _ => Some(true), + }, + Err(_) => None, + }) +} + +fn enabled_for(env: Option, amd: bool) -> bool { + match env { + Some(v) => v, + None => !amd, + } +} + +/// Record the adapter PCI vendor ID. On AMD (`0x1002`), `ID3D12PipelineLibrary1` stores only tiny +/// stub entries (e.g. ~0.2 MiB for 1,000+ pipelines) and loading/serializing two-pass pipelines +/// through it triggers GPU page faults (`0x887a0006`) on RDNA4. Default it off on AMD (which +/// relies on the driver's own DxCache) unless `XCL_PSO_LIBRARY=1` forces it on. +pub fn note_vendor(vendor: u32) { + let is_amd = vendor == 0x1002; + let was = AMD_VENDOR.fetch_or(is_amd, Ordering::Relaxed); + if is_amd && !was && !enabled() { + crate::xlog_info!( + "D3D12.X: pipeline library off on AMD by default (XCL_PSO_LIBRARY=1: force on)" + ); + } +} + +/// Whether the on-disk memory-mapped pipeline library is enabled (`XCL_PSO_LIBRARY=0` disables, +/// `XCL_PSO_LIBRARY=1` forces on; defaults off on AMD `0x1002` and on for other vendors). pub fn enabled() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_PSO_LIBRARY").map_or(true, |v| v.trim() != "0")) + enabled_for(env_override(), AMD_VENDOR.load(Ordering::Relaxed)) } fn wide_path(path: &Path) -> Vec { @@ -632,4 +667,12 @@ mod tests { assert!(!path1.exists(), "older generation should be cleaned up once unmapped"); drop(blob2); } + + #[test] + fn vendor_default_disables_pipeline_library_on_amd_unless_overridden() { + assert!(!enabled_for(None, true)); + assert!(enabled_for(None, false)); + assert!(enabled_for(Some(true), true)); + assert!(!enabled_for(Some(false), false)); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 0f8d6a9415..757ee9c1c5 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -704,6 +704,7 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result() { @@ -6051,7 +6052,7 @@ pub(crate) mod driver_cache { let references = reference_blob_vendor(vendor); let was = REFERENCE_BLOBS.fetch_or(references, Ordering::Relaxed); if references && !was && !enabled() { - crate::xlog_info!("D3D12.X: driver-blob disk cache off on AMD (using pipeline library; XCL_PSO_DISK_CACHE=1: force on)"); + crate::xlog_info!("D3D12.X: driver-blob disk cache off on AMD (driver manages its own DxCache; XCL_PSO_DISK_CACHE=1: force on)"); } } From 23d0f365d06af6301fbf688787c59efb8d78bdf9 Mon Sep 17 00:00:00 2001 From: Enrique Villa Date: Sun, 29 Nov 2026 18:39:50 +0800 Subject: [PATCH 049/175] D3D12.X: XMemVirtualAlloc GPU heaps go to the coherent window again Decoding the XMemFlags graphics bit (108cbafa) gave every XMemVirtualAlloc commit with that bit MEM_GRAPHICS, so a retail title's ~4.4 GB of GPU heaps went to the sparse windows (video memory for each tile plus the CPU's copy) instead of the coherent window, which was still committed at its stored size and stayed empty (64 of 4095 MB used). A commit with a GPU-accessible PAGE_GRAPHICS_* protection and only the XMemFlags graphics bit now gets no MEM_GRAPHICS and takes VirtualAlloc's GPU-heap path again (coherent window, or the sparse windows with XCL_COHERENT_HEAPS=sparse). Reservations, PAGE_GRAPHICS_NOACCESS commits and legacy XALLOC_ATTRIBUTES memory types keep MEM_GRAPHICS. Signed-off-by: Enrique Villa --- crates/xcl/src/hle/kernelx.rs | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 0d8e1fee37..36cc005dd6 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1532,9 +1532,17 @@ pub unsafe fn runtime_free(p: usize, attrs: u64) { /// Map `XMemVirtualAlloc`'s `XMemFlags` (bit 1 marks graphics memory: `XMEM_GRAPHICS = 0x3`, /// `XMEM_GRAPHICS_32BIT_ADDRESS = 0x7`; also tolerating legacy `XALLOC_ATTRIBUTES` with /// `memory_type != 0` in bits 29..=32) into `VirtualAlloc` allocation flags. -fn xmem_virtual_alloc_flags(t: u32, xmem_flags: u64) -> u32 { +/// +/// A commit with a GPU-accessible protection (`p`) and only the `XMemFlags` graphics bit is one of +/// the title's GPU heaps: it gets no `MEM_GRAPHICS`, so `VirtualAlloc` puts it in the coherent +/// window (one copy, as before the bit was decoded). With `MEM_GRAPHICS` a retail title's 4.4 GB +/// of heaps went to the sparse windows (as much video memory again, and the CPU's copy) while the +/// coherent window, sized for them from the last run, was committed empty: 25.4 GB peak commit in +/// a 60 s smoke run, 14.5 GB with the heaps in the window. +fn xmem_virtual_alloc_flags(t: u32, xmem_flags: u64, p: u32) -> u32 { let legacy = XAllocAttrs::decode(xmem_flags); - let is_graphics = (xmem_flags & 0x2 != 0) || legacy.memory_type != 0; + let heap = t & 0x1000 != 0 && p & PAGE_GRAPHICS_GPU_ACCESS != 0; + let is_graphics = (xmem_flags & 0x2 != 0 && !heap) || legacy.memory_type != 0; let mut out = if is_graphics { t | MEM_GRAPHICS } else { t }; if legacy.memory_type != 0 && legacy.page_size == 2 { out |= 0x8000_0000; @@ -1546,7 +1554,7 @@ fn xmem_virtual_alloc_flags(t: u32, xmem_flags: u64) -> u32 { /// DWORD protect)`: VirtualAlloc with Xbox memory flags – graphics flags route to GPU-visible /// memory (`MEM_GRAPHICS`). pub unsafe extern "system" fn XMemVirtualAlloc(addr: *const c_void, size: usize, t: u32, attrs: u64, p: u32) -> *mut c_void { - VirtualAlloc(addr, size, xmem_virtual_alloc_flags(t, attrs), p) + VirtualAlloc(addr, size, xmem_virtual_alloc_flags(t, attrs, p), p) } /// Fast-path `VirtualQuery` / `VirtualQueryEx` / `XMemVirtualQuery` for a committed coherent @@ -3676,11 +3684,17 @@ mod tests { assert_eq!(sanitize_protect(0x1204), mem::PAGE_READWRITE); assert_eq!(sanitize_protect(mem::PAGE_READWRITE | mem::PAGE_GUARD), mem::PAGE_READWRITE | mem::PAGE_GUARD); // XMemVirtualAlloc XMemFlags decoding: XMEM_CPU (0x1) stays CPU-only, XMEM_GRAPHICS (0x3) / 32BIT (0x7) set MEM_GRAPHICS - assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x1), 0x3000); - assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x11), 0x3000); - assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x3), 0x3000 | MEM_GRAPHICS); - assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x7), 0x3000 | MEM_GRAPHICS); - assert_eq!(xmem_virtual_alloc_flags(0x2040_6000, 0x27), 0x2040_6000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x1, 0x04), 0x3000); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x11, 0x04), 0x3000); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x3, 0x04), 0x3000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x7, 0x04), 0x3000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x2040_6000, 0x27, 0x04), 0x2040_6000 | MEM_GRAPHICS); + // a GPU heap (a commit with a GPU-accessible protection) stays out of MEM_GRAPHICS: the coherent window + assert_eq!(xmem_virtual_alloc_flags(0x2000_3000, 0x3, 0x2404), 0x2000_3000); + assert_eq!(xmem_virtual_alloc_flags(0x2000_3000, 0x3, 0x2_2004), 0x2000_3000); + // reserving it, or committing with PAGE_GRAPHICS_NOACCESS only, still does + assert_eq!(xmem_virtual_alloc_flags(0x2000_2000, 0x3, 0x2404), 0x2000_2000 | MEM_GRAPHICS); + assert_eq!(xmem_virtual_alloc_flags(0x3000, 0x3, 0x801), 0x3000 | MEM_GRAPHICS); // PAGE_GRAPHICS_NOACCESS alone is not GPU-accessible, whereas READONLY/READWRITE/COHERENT are let null = std::ptr::null(); assert!(!gpu_visible_fallback(null, 0x2000, mem::PAGE_READWRITE | 0x800)); From 18a38829a29c2f86583a85b2d1ae695e28180332 Mon Sep 17 00:00:00 2001 From: Prime1997 Date: Sat, 28 Nov 2026 17:08:21 -0700 Subject: [PATCH 050/175] D3D12.X: strip Xbox root signature flags for PC and honor FORCE_MEMORY_BASED_ABI Merge of pull request #3244 from Kalmarv/samplers/rootsig-xbox-flags. Picked onto amd-dev from origin/main (merge commit, first-parent diff); applied cleanly with no conflicts in console_list.rs or real.rs. (cherry picked from commit b10cc4c6766adc947c2054ada4a2af98be15108d) (cherry picked from commit 20c195fc106b08743408891c0c6187849faf3e0e) --- crates/xcl/src/hle/d3d12x/console_list.rs | 68 +++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 109 +++++++++++++++++++++- 2 files changed, 173 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 625f315b9f..ce65563b16 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -83,6 +83,46 @@ pub struct Layout { const CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED: u32 = 0x400; const SAMPLER_HEAP_DIRECTLY_INDEXED: u32 = 0x800; +/// Xbox-only root signature flags rejected by PC `CreateRootSignature`: +/// `FORCE_MEMORY_BASED_ABI` / `RAYTRACING` (`0x0100_0000`) spills all root parameters into the +/// memory argument table; `FORCE_COMPUTE_2_SPILL_AREA` (`0x0200_0000`) reserves a second compute +/// spill area on console hardware. +const FORCE_MEMORY_BASED_ABI: u32 = 0x0100_0000; +const XBOX_ROOT_SIGNATURE_FLAGS: u32 = 0x0300_0000; + +/// Locate the `RTS0` payload byte range inside a DXBC container or bare `RTS0` blob. +fn rts0_range(blob: &[u8]) -> Option<(usize, usize)> { + match crate::gpu::shader::container_parts(blob) { + Some(parts) => { + let p = parts.into_iter().find(|p| p.fourcc == "RTS0")?; + let end = p.offset.checked_add(p.size)?; + (end <= blob.len()).then_some((p.offset, end)) + } + None => Some((0, blob.len())), + } +} + +/// Strip Xbox-only high-bit root signature flags (`0x0300_0000`) from `RTS0` and recompute the +/// DXBC container digest so PC `CreateRootSignature` accepts the real root signature instead of +/// falling back to an empty one. Returns `None` when no Xbox-only flags are set. +pub fn pc_root_signature_blob(blob: &[u8]) -> Option> { + let (start, end) = rts0_range(blob)?; + let flags_off = start.checked_add(20)?; + if flags_off + 4 > end { + return None; + } + let flags = u32::from_le_bytes(blob[flags_off..flags_off + 4].try_into().ok()?); + if flags & XBOX_ROOT_SIGNATURE_FLAGS == 0 { + return None; + } + let mut out = blob.to_vec(); + out[flags_off..flags_off + 4].copy_from_slice(&(flags & !XBOX_ROOT_SIGNATURE_FLAGS).to_le_bytes()); + if out.len() >= 32 && &out[..4] == b"DXBC" { + let digest = crate::gpu::dxil::container::hash(&out[20..]); + out[4..20].copy_from_slice(&digest); + } + Some(out) +} /// User SGPRs the console's compiler gives root arguments: compute s4…s15 (s0…s3 are the /// driver's), graphics stages (VS, PS) s8…s31 (s0…s7: the driver's, s[4:5] of a VS the @@ -114,8 +154,10 @@ pub fn layout_from_blob(blob: &[u8]) -> Option { let mut l = Layout { heaps: [CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, SAMPLER_HEAP_DIRECTLY_INDEXED].map(|f| flags & f != 0), ..Default::default() }; // the parameters go into user SGPRs in order while each fits whole; from the first one // that does not, the rest go to the table (packed from its start) – as the console's - // compiler expects them (HANDOFF: root argument binding) - let (mut spilled, mut spilled_gfx, mut spilled_ms) = (false, false, false); + // compiler expects them (HANDOFF: root argument binding). Under FORCE_MEMORY_BASED_ABI every + // parameter starts spilled in the memory table. + let force_mem = flags & FORCE_MEMORY_BASED_ABI != 0; + let (mut spilled, mut spilled_gfx, mut spilled_ms) = (force_mem, force_mem, force_mem); for k in 0..n { let (ty, pay) = (r(poff + 12 * k)?, r(poff + 12 * k + 8)? as usize); let p = match ty { @@ -1262,6 +1304,28 @@ mod tests { assert_eq!(&got[16..], &[1, 2, 0x5000, 4, 0x80]); } + #[test] + fn force_memory_based_abi_spills_all_parameters_and_strips_xbox_flags() { + let mut blob = rts0(&[(1, 2), (2, 0), (0, 0)]); + assert!(pc_root_signature_blob(&blob).is_none()); + let flags = CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | FORCE_MEMORY_BASED_ABI | 0x0200_0000; + blob[20..24].copy_from_slice(&flags.to_le_bytes()); + let l = layout_from_blob(&blob).expect("layout"); + assert_eq!((l.size, l.inline, l.inline_gfx, l.inline_ms), (20, 0, 0, 0)); + assert_eq!(l.heaps, [true, false]); + let pc = pc_root_signature_blob(&blob).expect("sanitized blob"); + assert_eq!(u32::from_le_bytes(pc[20..24].try_into().unwrap()), CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED); + assert!(pc_root_signature_blob(&pc).is_none()); + + // FORCE_COMPUTE_2_SPILL_AREA alone is stripped for PC without forcing memory-based ABI. + let mut spill2 = rts0(&[(1, 2), (2, 0)]); + spill2[20..24].copy_from_slice(&0x0200_0000u32.to_le_bytes()); + let l2 = layout_from_blob(&spill2).expect("layout2"); + assert_eq!((l2.inline, l2.inline_gfx, l2.inline_ms), (16, 16, 16)); + let pc2 = pc_root_signature_blob(&spill2).expect("sanitized spill2"); + assert_eq!(u32::from_le_bytes(pc2[20..24].try_into().unwrap()), 0); + } + #[test] fn default_dispatch_heaps_binds_and_upgrades_missing_view_or_sampler() { // 0 heaps bound: binds both under heap_windows, or sampler alone when view == None. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 757ee9c1c5..b8dc289d2e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9831,10 +9831,19 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 crate::gpu::shader::capture("rootsig", blob as usize, len); type F = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const GUID, *mut *mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRootSignature"))); - let mut hr = f(this, mask, blob, len, riid, ppv); + let sanitized = if !blob.is_null() { + super::console_list::pc_root_signature_blob(std::slice::from_raw_parts(blob as *const u8, len)) + } else { + None + }; + let (pc_blob, pc_len) = match sanitized.as_ref() { + Some(b) => (b.as_ptr() as *const c_void, b.len()), + None => (blob, len), + }; + let mut hr = f(this, mask, pc_blob, pc_len, riid, ppv); if hr == E_NOINTERFACE { let iid = pc_iid(Kind::RootSignature); - hr = f(this, mask, blob, len, &iid, ppv); + hr = f(this, mask, pc_blob, pc_len, &iid, ppv); } if hr < 0 && !super::title_textures::is_own_work() { // console root signature rejected → empty one so the title keeps going @@ -9863,6 +9872,102 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 hr } +#[cfg(test)] +mod root_signature_tests { + use super::*; + + /// A DXBC-wrapped root signature carrying Xbox high-bit flags (`0x0300_0000`: + /// `FORCE_MEMORY_BASED_ABI | FORCE_COMPUTE_2_SPILL_AREA`) is rejected by PC + /// `CreateRootSignature`, so `dev_create_root_signature` strips those flags and recomputes the + /// DXBC digest instead of substituting an empty root signature, while preserving the original + /// `FORCE_MEMORY_BASED_ABI` flag for `console_list`'s layout. On WARP. + #[test] + fn dev_create_root_signature_strips_xbox_flags_and_keeps_parameters() { + let mut dev: Option = None; + unsafe { + let Ok(warp) = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) else { + return crate::gpu::recomp::runner::skip_test("no WARP adapter"); + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no WARP device"); + } + let Some(dev) = dev else { return crate::gpu::recomp::runner::skip_test("no WARP device") }; + adopt(dev.as_raw(), Kind::Device); + + let param = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 }, + }, + }; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: 1, + pParameters: ¶m, + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }; + let mut ser = None; + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).expect("serialize root sig"); + let b = ser.expect("blob"); + let mut xbox_blob = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec(); + let parts = crate::gpu::shader::container_parts(&xbox_blob).expect("DXBC container"); + let rts0 = parts.into_iter().find(|p| p.fourcc == "RTS0").expect("RTS0 chunk"); + let foff = rts0.offset + 20; + let orig_flags = u32::from_le_bytes(xbox_blob[foff..foff + 4].try_into().unwrap()); + xbox_blob[foff..foff + 4].copy_from_slice(&(orig_flags | 0x0300_0000).to_le_bytes()); + let digest = crate::gpu::dxil::container::hash(&xbox_blob[20..]); + xbox_blob[4..20].copy_from_slice(&digest); + + // Prove unhooked PC CreateRootSignature itself rejects the Xbox flags. + let riid = &ID3D12RootSignature::IID as *const windows::core::GUID as *const GUID; + type CreateRsFn = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const GUID, *mut *mut c_void) -> HRESULT; + let raw_create_rs: CreateRsFn = std::mem::transmute(orig_fn(dev.as_raw(), slot_of(dev.as_raw(), "CreateRootSignature"))); + let mut raw_out = std::ptr::null_mut(); + let raw_hr = raw_create_rs(dev.as_raw(), 0, xbox_blob.as_ptr() as *const c_void, xbox_blob.len(), riid, &mut raw_out); + assert!(raw_hr < 0 && raw_out.is_null(), "unhooked PC D3D12 must reject Xbox high-bit root signature flags, got {raw_hr:#x}"); + + // dev_create_root_signature strips the Xbox flags and creates the real root signature. + let mut out = std::ptr::null_mut(); + let hr = dev_create_root_signature(dev.as_raw(), 0, xbox_blob.as_ptr() as *const c_void, xbox_blob.len(), riid, &mut out); + assert!(hr >= 0 && !out.is_null(), "dev_create_root_signature failed: {hr:#x}"); + let rs = ID3D12RootSignature::from_raw(out); + + // Prove the returned root signature kept parameter 0 (not the empty fallback). + 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: 0, + DestOffsetIn32BitValues: 0, + Num32BitValuesToSet: 4, + }, + }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }, + ]; + let cs_desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 28, + NumArgumentDescs: args.len() as u32, + pArgumentDescs: args.as_ptr(), + NodeMask: 0, + }; + let mut cmd_sig: Option = None; + dev.CreateCommandSignature(&cs_desc, &rs, &mut cmd_sig) + .expect("real root signature must keep parameter 0 for CreateCommandSignature"); + + // And console_list saw the original FORCE_MEMORY_BASED_ABI flag -> inline == 0. + let layout = super::super::console_list::layout_of(rs.as_raw() as usize).expect("recorded layout"); + assert_eq!((layout.size, layout.inline, layout.inline_gfx, layout.inline_ms), (16, 0, 0, 0)); + } + } +} + // --------------------------------------------------------------------------------------- // presentation tracking // --------------------------------------------------------------------------------------- From 24bc619dbd36a06a0a881c0a4bd36cb9403d8f50 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:13:23 +0100 Subject: [PATCH 051/175] D3D12.X: cache invariant slots in hot hooks Picked onto amd-dev from origin/main. amd-dev already looks up the PC slot once in 14 of the 15 hooks upstream changes (pc_slot!, from 2987c19b), so all 15 conflicts in real.rs were resolved to amd-dev's side and upstream's slot!/cached_slot helpers were not taken. What is left of the change is the allocator Reset that reset_pc_allocator (alloc_pool / list_x allocator resets) still looked up by name under the adopted-class lock: it now uses pc_slot!("ID3D12CommandAllocator", "Reset"). Upstream's slot test is covered by layout.rs's a_method_stays_at_its_slot_in_later_versions, which now also checks ID3D12CommandAllocator. (cherry picked from commit f05846e76832db38ca78302fff22dc6175db0833) (cherry picked from commit 5654842563b6ce73071373a2b78960f31a34de86) --- crates/xcl/src/hle/d3d12x/layout.rs | 2 +- crates/xcl/src/hle/d3d12x/real.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/layout.rs b/crates/xcl/src/hle/d3d12x/layout.rs index 59575f94b8..d6a6e21538 100644 --- a/crates/xcl/src/hle/d3d12x/layout.rs +++ b/crates/xcl/src/hle/d3d12x/layout.rs @@ -60,7 +60,7 @@ mod tests { /// A method is at the same slot in every version of an interface (`real::pc_slot!`). #[test] fn a_method_stays_at_its_slot_in_later_versions() { - for base in ["ID3D12GraphicsCommandList", "ID3D12CommandQueue", "ID3D12Fence", "ID3D12Resource"] { + for base in ["ID3D12GraphicsCommandList", "ID3D12CommandQueue", "ID3D12Fence", "ID3D12Resource", "ID3D12CommandAllocator"] { let b = find(base).unwrap(); let versions = chain(base); assert!(!versions.is_empty()); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index b8dc289d2e..1c77e3cf6a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -10217,7 +10217,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { /// Reset the (adopted) PC allocator `raw` itself. pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; - let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); + let f: F = std::mem::transmute(orig_fn(raw, pc_slot!("ID3D12CommandAllocator", "Reset"))); let hr = f(raw); if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } hr From 12f791fdac33d46764b79a54cb06a7713d256279 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:28:06 +0300 Subject: [PATCH 052/175] D3D12.X: drop CreatePlacedResourceX alias table once logged and avoid hot-path formatting Eliminate hot-path formatting, mutex contention, and unbounded session-lifetime memory growth in `device_x::note_alias`: - Store a `Copy` `PlacedDescSummary` (`dim`, `width`, `height`, `format`, `flags`) with `Display` formatting `"dimension {} {}x{} format {} flags {:#x}"` only when an alias is actually logged (zero heap allocation on non-aliasing calls). - Add a lock-free `N.load(Ordering::Relaxed) >= MAX_ALIAS_LOGS` (`16`) fast-path in `note_alias`, drop the tracking `HashMap` (`*seen = None`) once 16 aliases have been logged, bound transient entries to `MAX_ALIAS_TRACKED` (`16_384`), and release `SEEN` before calling `xlog_info!`. - Add CPU unit tests (`note_alias_logs_first_16_and_drops_table_after_cap`, `note_alias_bounds_tracked_entries_without_aliases`, `note_alias_short_circuits_when_cap_already_reached`). Part of #1773 Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) Picked onto amd-dev from origin/main. The only conflict was in device_x.rs's test module, where amd-dev added base-shader pool tests at the same place: both sets of tests are kept. (cherry picked from commit ce86b00e30e7a4eedfabf215cb3e0a0b2b6b6a89) (cherry picked from commit 10b8133fd1f4f28db270ecec2326155ab3525221) --- crates/xcl/src/hle/d3d12x/device_x.rs | 137 ++++++++++++++++++++++++-- 1 file changed, 128 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index fa9940d2d5..008d3490ee 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1136,19 +1136,78 @@ pub(super) unsafe extern "system" fn get_custom_heap_properties_x(a: *mut c_void ret } +const MAX_ALIAS_LOGS: u64 = 16; +const MAX_ALIAS_TRACKED: usize = 16_384; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PlacedDescSummary { + dim: u32, + width: u64, + height: u32, + format: u32, + flags: u32, +} + +impl PlacedDescSummary { + fn from_desc(x: &[u8; 0x38]) -> Self { + let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + Self { + dim: u(0), + width: u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), + height: u(0x18), + format: u(0x20), + flags: u(0x30), + } + } +} + +impl std::fmt::Display for PlacedDescSummary { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "dimension {} {}x{} format {} flags {:#x}", self.dim, self.width, self.height, self.format, self.flags) + } +} + +fn record_alias_in( + seen: &mut Option>, + logged: &AtomicU64, + va: usize, + cur: PlacedDescSummary, + max_tracked: usize, +) -> Option { + if logged.load(Ordering::Relaxed) >= MAX_ALIAS_LOGS { + *seen = None; + return None; + } + let m = seen.get_or_insert_with(std::collections::HashMap::new); + if let Some(slot) = m.get_mut(&va) { + let prev = std::mem::replace(slot, cur); + let prev_count = logged.fetch_add(1, Ordering::Relaxed); + if prev_count + 1 >= MAX_ALIAS_LOGS { + *seen = None; + } + return (prev_count < MAX_ALIAS_LOGS).then_some(prev); + } + if m.len() < max_tracked { + m.insert(va, cur); + } + None +} + /// Resources the title placed at an address an earlier one was placed at: on the console they /// share that memory (aliasing – transient render targets reuse it). Logged (first 16). fn note_alias(va: usize, x: &[u8; 0x38]) { - static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); static N: AtomicU64 = AtomicU64::new(0); - let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); - let what = format!("dimension {} {}x{} format {} flags {:#x}", u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u(0x20), u(0x30)); - let mut g = SEEN.lock().unwrap(); - let m = g.get_or_insert_with(std::collections::HashMap::new); - if let Some(prev) = m.insert(va, what.clone()) { - if N.fetch_add(1, Ordering::Relaxed) < 16 { - crate::xlog_info!("D3D12.X: CreatePlacedResourceX at {va:#x} ({what}) – aliases an earlier resource there ({prev})"); - } + if N.load(Ordering::Relaxed) >= MAX_ALIAS_LOGS { + return; + } + let cur = PlacedDescSummary::from_desc(x); + let prev = { + let mut g = SEEN.lock().unwrap(); + record_alias_in(&mut g, &N, va, cur, MAX_ALIAS_TRACKED) + }; + if let Some(prev) = prev { + crate::xlog_info!("D3D12.X: CreatePlacedResourceX at {va:#x} ({cur}) – aliases an earlier resource there ({prev})"); } } @@ -1940,4 +1999,64 @@ mod tests { let dead = g.as_ref().map_or(0, |p| p.map.values().filter(|w| w.strong_count() == 0).count()); assert!(dead < 2 * super::super::real::SHADER_POOL_SWEEP, "{dead} dead entries kept"); } + + fn placed_desc(dim: u32, width: u64, height: u32, format: u32, flags: u32) -> [u8; 0x38] { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&dim.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&width.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&height.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&format.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + x + } + + #[test] + fn note_alias_logs_first_16_and_drops_table_after_cap() { + let first = PlacedDescSummary::from_desc(&placed_desc(3, 1920, 1080, 28, 0x5)); + assert_eq!(first.to_string(), "dimension 3 1920x1080 format 28 flags 0x5"); + + let mut seen = None; + let logged = AtomicU64::new(0); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, first, MAX_ALIAS_TRACKED), None); + let mut expected_prev = first; + for i in 1..=MAX_ALIAS_LOGS { + let next = PlacedDescSummary::from_desc(&placed_desc(3, 1920 + i, 1080, 28, i as u32)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, next, MAX_ALIAS_TRACKED), Some(expected_prev), "alias #{i}"); + expected_prev = next; + if i < MAX_ALIAS_LOGS { + assert!(seen.is_some(), "table stays active before cap (alias #{i})"); + } + } + assert!(seen.is_none(), "16th alias must drop the tracking table"); + let after = PlacedDescSummary::from_desc(&placed_desc(1, 4096, 1, 0, 0)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, after, MAX_ALIAS_TRACKED), None); + assert_eq!(record_alias_in(&mut seen, &logged, 0x2000, after, MAX_ALIAS_TRACKED), None); + assert!(seen.is_none(), "calls after cap must not reallocate the tracking table"); + } + + #[test] + fn note_alias_bounds_tracked_entries_without_aliases() { + let mut seen = None; + let logged = AtomicU64::new(0); + let max_tracked = 8; + let d0 = PlacedDescSummary::from_desc(&placed_desc(3, 64, 64, 28, 1)); + for i in 0..(max_tracked + 5) { + assert_eq!(record_alias_in(&mut seen, &logged, 0x10000 + i * 0x1000, d0, max_tracked), None); + } + assert_eq!(seen.as_ref().unwrap().len(), max_tracked, "tracked VA count must stay bounded"); + let d1 = PlacedDescSummary::from_desc(&placed_desc(3, 128, 128, 28, 2)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x10000, d1, max_tracked), Some(d0), "aliasing a tracked entry still fires"); + assert_eq!(logged.load(Ordering::Relaxed), 1); + } + + #[test] + fn note_alias_short_circuits_when_cap_already_reached() { + let d0 = PlacedDescSummary::from_desc(&placed_desc(3, 32, 32, 28, 0)); + let mut seen = Some(std::collections::HashMap::from([(0x5000usize, d0)])); + let logged = AtomicU64::new(MAX_ALIAS_LOGS); + let d1 = PlacedDescSummary::from_desc(&placed_desc(3, 64, 64, 28, 4)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x5000, d1, MAX_ALIAS_TRACKED), None); + assert!(seen.is_none(), "residual map must be freed once cap is reached"); + assert_eq!(logged.load(Ordering::Relaxed), MAX_ALIAS_LOGS); + } } From 91581c8aa417ea4ba2f1212d2ff1e18f46c6180e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 06:02:47 +0100 Subject: [PATCH 053/175] D3D12.X: forget a command list before the runtime frees it cl_release dropped XCL state keyed by a PC command list address only after the runtime's final Release had freed the list. A list created on another thread could immediately reuse that address and lose its bind state, allocator, last submit, and DRED marks. Probe the final reference and forget keyed state before the freeing Release, matching the established resource-release pattern. A fake list whose Release reuses its address immediately verifies the new list keeps its state. Assisted-by: Claude Code (Claude Opus 5.5) Assisted-by: Codex (GPT-5.6-sol) Picked onto amd-dev from origin/main. cl_release on amd-dev was the same as upstream's parent; the only conflict was the new list_release_tests module landing where amd-dev's test modules end: both are kept. The title_list.rs follow-up (6ae88983) is not needed on amd-dev, which already skips that second forget for adopted primaries. (cherry picked from commit 309e35572a5a522b33e5fd7ca3d0e8e3e661b90b) (cherry picked from commit 7413dcac2100f82d3ee489df82dde9af49a54402) --- crates/xcl/src/hle/d3d12x/real.rs | 76 +++++++++++++++++++++++++++++-- 1 file changed, 71 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 1c77e3cf6a..4b5acce86e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -10143,17 +10143,30 @@ unsafe extern "system" fn cl_execute_indirect( f(this, sig, max_count, arg_buf, arg_off, cnt_buf, cnt_off); } +/// The last reference: what XCL keeps by the list's address goes before the runtime frees it, +/// as a list created on another thread can get the address at once. (Two last-but-one releases +/// at once miss each other here; the list's state then goes after it, as before.) unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let add: RefFn = std::mem::transmute(orig_fn(this, 1)); + let f: RefFn = std::mem::transmute(orig_fn(this, 2)); + let last = add(this) == 2; + f(this); + if last { + forget_command_list(this); + } let n = f(this); - if n == 0 { - super::list_x::on_release(this as usize); - super::bind::forget(this); - super::dred::forget_list(this); + if n == 0 && !last { + forget_command_list(this); } n } +fn forget_command_list(list: *mut c_void) { + super::list_x::on_release(list as usize); + super::bind::forget(list); + super::dred::forget_list(list); +} + unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); @@ -13639,3 +13652,56 @@ mod pso_lib { } } } + +#[cfg(test)] +mod list_release_tests { + use super::*; + + #[repr(C)] + struct FakeList { + vtable: usize, + refs: u32, + } + + const ALLOC: usize = 0x7E57_A130; + const PSO: usize = 0x7E57_D002; + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let l = &mut *(this as *mut FakeList); + l.refs += 1; + l.refs + } + + // the runtime frees the list, and a list created on another thread gets its address at once + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let l = &mut *(this as *mut FakeList); + l.refs -= 1; + if l.refs == 0 { + super::super::bind::reset(this, ALLOC, PSO); + super::super::alloc_pool::created_on(this as usize, ALLOC, 0); + } + l.refs + } + + #[test] + fn a_new_list_at_a_released_lists_address_keeps_its_state() { + let pc = [0, add_ref as usize, release as usize]; + let ext = [pc.as_ptr() as usize, 0]; + let mut list = FakeList { vtable: ext.as_ptr() as usize + 8, refs: 2 }; + let this = &mut list as *mut FakeList as *mut c_void; + super::super::bind::reset(this, ALLOC + 0x10, PSO + 0x10); + let (kept, n) = unsafe { + assert_eq!(cl_release(this), 1); + (super::super::bind::tracked_pso(this), cl_release(this)) + }; + let pso = super::super::bind::tracked_pso(this); + let backing = super::super::alloc_pool::recording_backing_for_test(this as usize); + super::super::bind::forget(this); + super::super::alloc_pool::forget_list(this as usize); + assert_eq!(kept, PSO + 0x10, "another reference is left"); + assert_eq!(n, 0); + assert_eq!(pso, PSO, "the new list's bind state"); + assert_eq!(backing, Some(ALLOC), "the new list's allocator"); + } +} + From 633f59c0ab6301afc1e80d02a22a63b058a1ab7e Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Wed, 25 Nov 2026 23:23:06 -0800 Subject: [PATCH 054/175] DirectStorage: precompute BCPack bit packing Replace per-block bit-spread, residual-mask, and anchor scans with compile-time lookup tables and fixed masks while preserving every existing BCPack output. Add exhaustive helper equivalence checks and baseline hashes for the shipped fixtures and all BC6H/BC7 modes. Assisted-by: Google Antigravity (Gemini 4 Neon) Co-authored-by: Decodere <98278826+Decodere@users.noreply.github.com> Assisted-by: Codex (GPT-5.6-sol) Picked onto amd-dev from origin/main. The only conflict was the new test module landing where amd-dev's BC7 rotation_tests module is: both are kept. amd-dev's rotation() fix (rotation read only in BC7 modes 4 and 5) is untouched, and upstream's fixture baseline hashes still match with it. (cherry picked from commit ec5c3e2135f0901fd842618460b16996e563e14d) (cherry picked from commit 98841490194fe9242cbe6cb066925d42434db813) --- crates/xcl/src/hle/bcpack/victory.rs | 375 ++++++++++++++++++++++----- 1 file changed, 316 insertions(+), 59 deletions(-) diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index 49094c3be2..f805001172 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -330,10 +330,39 @@ fn references(s: &[u8], paired: bool) -> (usize, usize) { (usize::from(ix.wrapping_add(delta)), usize::from(ix)) } +/// Spreads a 4-bit symbol onto even bit positions `0, 2, 4, 6`. +const SPREAD4: [u8; 16] = [ + 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, + 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55, +]; + +/// Spreads an 8-bit symbol onto even bit positions `0, 2, ..., 14`. +const SPREAD8: [u16; 256] = { + let mut t = [0u16; 256]; + let mut v = 0usize; + while v < 256 { + let mut out = 0u16; + let mut k = 0; + while k < 8 { + out |= (((v >> k) & 1) as u16) << (2 * k); + k += 1; + } + t[v] = out; + v += 1; + } + t +}; + /// Two 4-bit symbols, the first on the even bits. +#[inline(always)] fn interleave(a: u8, b: u8) -> u8 { - let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); - spread(a) | spread(b) << 1 + SPREAD4[usize::from(a & 15)] | (SPREAD4[usize::from(b & 15)] << 1) +} + +/// Two 8-bit symbols, the first on the even bits. +#[inline(always)] +fn wide_interleave(a: u8, b: u8) -> u16 { + SPREAD8[usize::from(a)] | (SPREAD8[usize::from(b)] << 1) } /// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first @@ -347,26 +376,40 @@ fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: } /// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. +#[inline(always)] fn zz(v: u8, bits: u32) -> u8 { let mask = ((1u32 << bits) - 1) as u8; ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask } -/// Element widths of the plain formats' endpoints and indices. +/// Element masks and active counts of the plain formats' endpoints and indices. struct Widths { - ep: [u8; 8], - ix: [u8; 32], + ep_mask: [u8; 8], + ep_len: usize, + ix_mask: [u8; 32], + ix_len: usize, paired: bool, } const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { - let mut ix = [0; 32]; + let mut ep_mask = [0u8; 8]; + let mut ep_len = 0; + let mut k = 0; + while k < 8 { + if ep[k] != 0 { + ep_mask[k] = ((1u16 << ep[k]) - 1) as u8; + ep_len = k + 1; + } + k += 1; + } + let mut ix_mask = [0u8; 32]; + let ix_len = ix3 + ix2; let mut k = 0; - while k < ix3 + ix2 { - ix[k] = if k < ix3 { 3 } else { 2 }; + while k < ix_len { + ix_mask[k] = if k < ix3 { 7 } else { 3 }; k += 1; } - Widths { ep, ix, paired } + Widths { ep_mask, ep_len, ix_mask, ix_len, paired } } const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); @@ -389,11 +432,17 @@ fn plain<'a>( let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; let mut v = residual(s); - for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { - *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + for ((v, &r), &mask) in v.ep[..w.ep_len].iter_mut().zip(ep_ref).zip(&w.ep_mask) { + *v = v.wrapping_add(r) & mask; } - for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { - *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + if w.ix_len == 16 { + for ((v, &r), &mask) in v.ix[..16].iter_mut().zip(&ix_ref[..16]).zip(&w.ix_mask[..16]) { + *v = v.wrapping_add(r) & mask; + } + } else { + for ((v, &r), &mask) in v.ix[..w.ix_len].iter_mut().zip(ix_ref).zip(&w.ix_mask) { + *v = v.wrapping_add(r) & mask; + } } history[i % HISTORY] = v; pack(&v, block); @@ -402,22 +451,26 @@ fn plain<'a>( } /// 2-bit index residuals: one symbol per 2x2 quad. -fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { +#[inline(always)] +fn quads(rank: &[u8; 256], s: &[u8; 4], ix: &mut [u8; 16]) { for (q, &sym) in s.iter().enumerate() { let v = rank[usize::from(sym)]; let base = (q >> 1) * 8 + (q & 1) * 2; - for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { - ix[base + p] = v >> (2 * k) & 3; - } + ix[base] = v & 3; + ix[base + 1] = (v >> 2) & 3; + ix[base + 4] = (v >> 4) & 3; + ix[base + 5] = (v >> 6) & 3; } } /// 3-bit index residuals: one symbol per two pixels in raster order. +#[inline(always)] fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { - for (k, &sym) in s.iter().enumerate() { + let (chunks, _) = ix.as_chunks_mut::<2>(); + for (&sym, dst) in s.iter().zip(chunks) { let v = rank[usize::from(sym & 63)]; - ix[2 * k] = v & 7; - ix[2 * k + 1] = v >> 4 & 7; + dst[0] = v & 7; + dst[1] = (v >> 4) & 7; } } @@ -426,7 +479,7 @@ fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { v.ep[k] = zz(s[2 + k], bits); } - quads(&t.rank1, &s[8..12], &mut v.ix); + quads(t.rank1, s[8..12].try_into().unwrap(), (&mut v.ix[..16]).try_into().unwrap()); v } @@ -446,7 +499,7 @@ fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { ..Default::default() }; pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); - quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); + quads(t.rank3c, s[20..24].try_into().unwrap(), (&mut v.ix[16..]).try_into().unwrap()); v } @@ -470,54 +523,88 @@ fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; -fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { +#[inline(always)] +fn bc1_color(ep: &[u8; 6], ix: &[u8; 16], out: &mut [u8; 8]) { let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); - let bits = (0..16).fold(0, |acc, p| { - acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) - }); - out[..2].copy_from_slice(&c0.to_le_bytes()); - out[2..4].copy_from_slice(&c1.to_le_bytes()); - out[4..8].copy_from_slice(&bits.to_le_bytes()); + let mut bits = 0u32; + for (p, &val) in ix.iter().enumerate() { + bits |= BC1_CODE[usize::from(val & 3)] << (2 * p); + } + let word = u64::from(c0) | (u64::from(c1) << 16) | (u64::from(bits) << 32); + *out = word.to_le_bytes(); } /// BC4 half: endpoints are kept 128 below their stored value. -fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { - let bits = (0..16).fold(0u64, |acc, p| { - acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) - }); +#[inline(always)] +fn bc4_alpha(e0: u8, e1: u8, ix: &[u8; 16], out: &mut [u8; 8]) { + let mut bits = 0u64; + for (p, &val) in ix.iter().enumerate() { + bits |= BC4_CODE[usize::from(val & 7)] << (16 + 3 * p); + } let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; - out[..8].copy_from_slice(&v.to_le_bytes()); + *out = v.to_le_bytes(); } fn bc1_pack(v: &Plain, out: &mut [u8]) { - bc1_color(&v.ep, &v.ix, out); + bc1_color( + v.ep[..6].try_into().unwrap(), + v.ix[..16].try_into().unwrap(), + (&mut out[..8]).try_into().unwrap(), + ); } fn bc3_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); - bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); + let (a, c) = out.split_at_mut(8); + bc4_alpha(v.ep[6], v.ep[7], v.ix[..16].try_into().unwrap(), a.try_into().unwrap()); + bc1_color( + v.ep[..6].try_into().unwrap(), + v.ix[16..].try_into().unwrap(), + (&mut c[..8]).try_into().unwrap(), + ); } fn bc4_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); + bc4_alpha(v.ep[0], v.ep[1], v.ix[..16].try_into().unwrap(), (&mut out[..8]).try_into().unwrap()); } fn bc5_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); - bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); + let (a, b) = out.split_at_mut(8); + bc4_alpha(v.ep[0], v.ep[1], v.ix[..16].try_into().unwrap(), a.try_into().unwrap()); + bc4_alpha(v.ep[2], v.ep[3], v.ix[16..].try_into().unwrap(), (&mut b[..8]).try_into().unwrap()); } +/// Even and odd bit nibbles of every byte, zigzag-decoded to signed 4-bit residuals. +const NIBBLES: [[i16; 2]; 256] = { + let mut t = [[0i16; 2]; 256]; + let mut b = 0usize; + while b < 256 { + let mut even = 0u8; + let mut odd = 0u8; + let mut k = 0; + while k < 4 { + even |= (((b as u8) >> (2 * k)) & 1) << k; + odd |= (((b as u8) >> (2 * k + 1)) & 1) << k; + k += 1; + } + let ze = (even >> 1) as i16 ^ -((even & 1) as i16); + let zo = (odd >> 1) as i16 ^ -((odd & 1) as i16); + t[b] = [ze, zo]; + b += 1; + } + t +}; + /// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +#[inline(always)] fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { - let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); - let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); - let (even, odd) = (z(half(b)), z(half(b >> 1))); + let [even, odd] = NIBBLES[usize::from(b)]; if odd_first { [odd, even] } else { [even, odd] } } /// Index residual plus reference, both left-aligned to 16 bits at their own /// widths, back to `bits` bits (signed). +#[inline(always)] fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { let up = |v: i16, b: u8| { if b == 0 || b > 16 { @@ -538,9 +625,11 @@ struct Bits { } impl Bits { + #[inline(always)] fn put(&mut self, value: u64, n: u32) { if n > 0 && self.at < 128 { - self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; + let masked = if n < 64 { value & ((1u64 << n) - 1) } else { value }; + self.v |= u128::from(masked) << self.at; } self.at += n; } @@ -745,15 +834,15 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), _ => {} } - let anchors: &[u8] = match subsets { - 2 => &[0, ANCHOR2[part]], - 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], - _ => &[0], + let anchor_mask: u16 = match subsets { + 2 => 1 | (1 << ANCHOR2[part]), + 3 => 1 | (1 << ANCHOR3A[part]) | (1 << ANCHOR3B[part]), + _ => 1, }; let mut indices = |set: usize| { - let bits = ix.bits[set]; + let bits = u32::from(ix.bits[set]); for (p, &v) in ix.ix[set].iter().enumerate() { - let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + let n = bits - u32::from((anchor_mask >> p) & 1); w.put(u64::from(v as u16), n); } }; @@ -930,11 +1019,7 @@ fn bc6<'a>( }, ); let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); - let wide = |a: u8, b: u8| { - (0..8).fold(0u16, |acc, k| { - acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) - }) - }; + let wide = wide_interleave; for (i, (s, block)) in records.zip(out).enumerate() { let (ep_ref, ix_ref) = references(s, true); let mode = s[30].wrapping_add(1); @@ -1009,11 +1094,11 @@ fn bc6<'a>( ); } } - let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + let anchor_mask: u16 = if two { 1 | (1 << ANCHOR2[usize::from(part)]) } else { 1 }; + let bias = 1u16 << (bits - 1); for (p, &v) in ix.ix.iter().enumerate() { - let short = p == 0 || p == usize::from(anchor); - let v = (v as u16).wrapping_add(1 << (bits - 1)); - w.put(v.into(), u32::from(bits) - u32::from(short)); + let v = (v as u16).wrapping_add(bias); + w.put(v.into(), u32::from(bits) - u32::from((anchor_mask >> p) & 1)); } block.copy_from_slice(&w.v.to_le_bytes()); } @@ -1040,3 +1125,175 @@ mod rotation_tests { } } +#[cfg(test)] +mod tests { + use super::*; + + fn fnv1a(bytes: &[u8]) -> u64 { + let mut h = 0xcbf29ce484222325u64; + for &b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(0x100000001b3); + } + h + } + + #[test] + fn lut_helpers_match_scalar_reference_exhaustively() { + let spread4 = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> k) & 1) << (2 * k)); + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> (2 * k)) & 1) << k); + let z4 = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + for a in 0..=255u8 { + let (even, odd) = (z4(half(a)), z4(half(a >> 1))); + assert_eq!(nibbles(a, false), [even, odd]); + assert_eq!(nibbles(a, true), [odd, even]); + for b in 0..=255u8 { + assert_eq!(interleave(a, b), spread4(a) | (spread4(b) << 1)); + let wide_ref = (0..8).fold(0u16, |acc, k| { + acc | (u16::from((a >> k) & 1) << (2 * k)) | (u16::from((b >> k) & 1) << (2 * k + 1)) + }); + assert_eq!(wide_interleave(a, b), wide_ref); + } + } + + // Precomputed Widths masks and active lengths for BC1/BC3/BC4/BC5. + for (w, ep_bits, ix3, ix2) in [ + (&BC1, [5u8, 6, 5, 5, 6, 5, 0, 0], 0usize, 16usize), + (&BC3, [5, 6, 5, 5, 6, 5, 8, 8], 16, 16), + (&BC4, [8, 8, 0, 0, 0, 0, 0, 0], 16, 0), + (&BC5, [8, 8, 8, 8, 0, 0, 0, 0], 32, 0), + ] { + let want_ep_len = ep_bits.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + assert_eq!(w.ep_len, want_ep_len); + assert_eq!(w.ix_len, ix3 + ix2); + for (k, &bits) in ep_bits.iter().enumerate() { + assert_eq!(w.ep_mask[k], ((1u16 << bits) - 1) as u8); + } + for (k, &mask) in w.ix_mask.iter().enumerate() { + let bits = if k < ix3 { 3 } else if k < ix3 + ix2 { 2 } else { 0 }; + assert_eq!(mask, (1u8 << bits) - 1); + } + } + + // BC7 and BC6H u16 anchor bitmasks match slice/branch anchor predicates. + for part in 0..64usize { + for subsets in [1usize, 2, 3] { + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], + }; + let mask: u16 = match subsets { + 2 => 1 | (1 << ANCHOR2[part]), + 3 => 1 | (1 << ANCHOR3A[part]) | (1 << ANCHOR3B[part]), + _ => 1, + }; + for p in 0..16usize { + assert_eq!(((mask >> p) & 1) != 0, anchors.contains(&(p as u8))); + } + } + if part < 32 { + for two in [false, true] { + let anchor = if two { ANCHOR2[part] } else { 0 }; + let mask: u16 = if two { 1 | (1 << ANCHOR2[part]) } else { 1 }; + for p in 0..16usize { + assert_eq!(((mask >> p) & 1) != 0, p == 0 || p == usize::from(anchor)); + } + } + } + } + + // Bits::put matches u128 reference across n = 0, small widths, 64, and overflow past 128. + let mut got = Bits::default(); + let mut ref_v = 0u128; + let mut ref_at = 0u32; + for (val, n) in [(0xFFFFu64, 0u32), (0x55, 5), (0xDEAD_BEEF_CAFE_BABE, 64), (0x3FF, 10), (0xFFFF, 60)] { + got.put(val, n); + if n > 0 && ref_at < 128 { + ref_v |= (u128::from(val) & ((1u128 << n) - 1)) << ref_at; + } + ref_at += n; + assert_eq!((got.v, got.at), (ref_v, ref_at)); + } + } + + #[test] + fn all_bc_fixtures_and_packers_match_baseline() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/bcpack"); + let tables = Tables::builtin(); + let cases: [(&str, u8, usize, u64); 12] = [ + ("bc1-2-0", 1, 2 * 8, 0x00241ed045f935b7), + ("bc1-16-1", 1, 16 * 8, 0xaa27d5c23c617a11), + ("bc1-16-9", 1, 16 * 8, 0x5af81e16cde0f88b), + ("bc1-700-2", 1, 700 * 8, 0x6c1294776a5e0f7f), + ("bc1-8192-3", 1, 8192 * 8, 0xa0d8a27ea25cb660), + ("bc3-16-1", 3, 16 * 8, 0xc9b128a6e1beda7b), + ("bc4-16-1", 4, 16 * 8, 0x80173d43d3e12784), + ("bc5-16-1", 5, 16 * 8, 0x4338d58b289e83fc), + ("bc6-16-1", 6, 16 * 8, 0x4312c31241f68f5f), + ("bc7-2-0", 7, 2 * 8, 0xb3e3f4cd147b0999), + ("bc7-16-1", 7, 16 * 8, 0x013a7ec1ceec8b71), + ("bc7-8192-3", 7, 8192 * 8, 0x0b54870998ec2325), + ]; + for (stem, mode, out_len, want_hash) in cases { + let src = std::fs::read(dir.join(format!("{stem}.bin"))).unwrap(); + let mut dst = vec![0u8; out_len]; + decode(mode, &src, &mut dst, tables).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(fnv1a(&dst), want_hash, "{stem} output diverged from baseline"); + } + let bad_src = std::fs::read(dir.join("bc7-700-2.bin")).unwrap(); + let mut bad_dst = vec![0u8; 700 * 8]; + assert_eq!(decode(7, &bad_src, &mut bad_dst, tables), Err(Error("unused BC7 control code"))); + + // Verify fixed-size bc1_color/bc4_alpha and every BC6H mode 1..=14 / BC7 mode 0..=7. + let ep6 = [19u8, 45, 7, 29, 12, 31]; + let ix16: [u8; 16] = std::array::from_fn(|p| ((p * 5 + 3) & 7) as u8); + let (mut got1, mut got4) = ([0u8; 8], [0u8; 8]); + bc1_color(&ep6, &ix16, &mut got1); + let c0 = u16::from(ep6[0]) << 11 | u16::from(ep6[1]) << 5 | u16::from(ep6[2]); + let c1 = u16::from(ep6[3]) << 11 | u16::from(ep6[4]) << 5 | u16::from(ep6[5]); + let ref_bits1 = (0..16).fold(0u32, |acc, p| acc | (BC1_CODE[usize::from(ix16[p] & 3)] << (2 * p))); + assert_eq!(&got1[..2], &c0.to_le_bytes()); + assert_eq!(&got1[2..4], &c1.to_le_bytes()); + assert_eq!(&got1[4..8], &ref_bits1.to_le_bytes()); + bc4_alpha(0x2A, 0xD5, &ix16, &mut got4); + let ref_v4 = u64::from(0x2Au8 ^ 0x80) + | (u64::from(0xD5u8 ^ 0x80) << 8) + | (0..16).fold(0u64, |acc, p| acc | (BC4_CODE[usize::from(ix16[p] & 7)] << (16 + 3 * p))); + assert_eq!(got4, ref_v4.to_le_bytes()); + + // Exercise all 14 BC6H modes (1..=14) and all 8 BC7 modes (0..=7) end-to-end. + let bc6_recs: Vec<[u8; 32]> = (1u8..=14) + .map(|m| { + let mut r = [0u8; 32]; + for (k, slot) in r.iter_mut().enumerate().take(30) { + *slot = (m.wrapping_mul(17).wrapping_add((k as u8).wrapping_mul(11))) & 0x7F; + } + r[30] = m - 1; + r[31] = (m * 3) & 31; + r + }) + .collect(); + let mut bc6_out = [[0u8; 16]; 14]; + bc6(bc6_recs.iter().map(|r| &r[..]), bc6_out.iter_mut().map(|b| &mut b[..]), tables.bc6).unwrap(); + assert!(bc6_out.iter().all(|b| b.iter().any(|&x| x != 0))); + + let mut bc7_recs = Vec::new(); + for mode in 0u16..8 { + let idx = tables.ctrl7.iter().position(|&c| c != 0 && (c & 7) == mode).unwrap(); + let mut r = [0u8; 32]; + for (k, slot) in r.iter_mut().enumerate().take(30) { + *slot = ((mode as u8 + 1).wrapping_mul(13).wrapping_add((k as u8).wrapping_mul(7))) & 0x3F; + } + r[30] = (idx & 31) as u8; + r[31] = ((idx >> 5) & 15) as u8; + bc7_recs.push(r); + } + let mut bc7_out = [[0u8; 16]; 8]; + bc7(bc7_recs.iter().map(|r| &r[..]), bc7_out.iter_mut().map(|b| &mut b[..]), tables).unwrap(); + for (mode, block) in bc7_out.iter().enumerate() { + assert_eq!(block[0].trailing_zeros() as usize, mode, "BC7 mode {mode} header bit"); + } + } +} + From 785fcb5e6b8e14810e334bd4d6a3eda40a12048a Mon Sep 17 00:00:00 2001 From: Tarosul Date: Tue, 24 Nov 2026 16:46:36 +0100 Subject: [PATCH 055/175] D3D12.X: XG CopyInto/FromSubresource take the newer library's added argument A retail game crashed during its world loading, every run: an access violation in a memcpy writing to title memory that was never reserved, mapped or committed. The writer was XCL's XGTextureAddressComputer::CopyFromSubresource (vtable #9), called by the game as (linear dst, plane, subresource, 0, tiled src, row pitch, slice pitch): its library has a 32-bit argument before the source pointer, which the library the oracle test uses (XDefiant's) does not. Read the 6-argument way, the source was the 0 dword with the stack slot's old upper half, and the row pitch the low half of the real source pointer, so the second row went gigabytes past the destination. The game calls both forms, so they are told apart per call: a value of 16 bits or less in the fourth slot with address space in use at the fifth is the newer form (address space, not readable memory: title pages are committed on first use). A nonzero added argument is logged once and ignored; its meaning is not known. New test: both forms tile the same bytes and read them back, with garbage in the upper half of the added argument's slot. Picked onto amd-dev from origin/main; applied without conflicts. (cherry picked from commit adccb7d80fd1be9219ca534db84a472627ebc0c6) Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e0947692e49ba5665aadf3b46d2bc7d2553c378f) --- crates/xcl/src/hle/xg.rs | 76 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 0eec7dc16e..e816ef0e0a 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -11,7 +11,8 @@ //! GetResourceSizeBytes, GetResourceBaseAlignmentBytes, GetMipLevelOffsetBytes(plane, mip), //! GetTexelElementOffsetBytes(plane, mip, x, y, slice, sample, bit*), GetTexelCoordinate, //! CopyIntoSubresource(dst, plane, subresource, src, row pitch, slice pitch), -//! CopyFromSubresource(dst, plane, subresource, src, row pitch, slice pitch), then 2 more. +//! CopyFromSubresource(dst, plane, subresource, src, row pitch, slice pitch) – a newer library +//! has a 32-bit argument before `src` (`copy_args`) –, then 2 more. //! * XG_RESOURCE_LAYOUT (0x1B40): size @0, alignment @8, mips @0x10, planes @0x14, planes //! from 0x18, 0x6C8 bytes each (usage @0, size @8, slice size @0x10, alignment @0x20, bytes //! per element @0x28, first mip in the tail @0x2C, mips in the tail @0x30, then 15 mips of @@ -671,8 +672,41 @@ fn subresource(t: &Texture, plane: u32, sub: u32) -> Option<(&Surface, u64, usiz (k < s.array as usize).then_some((s, at, i, k)) } +/// The arguments after `subresource` of CopyIntoSubresource / CopyFromSubresource: (pointer, row +/// pitch, slice pitch). The library XDefiant and Fortnite ship takes (pointer, row pitch, slice +/// pitch); a newer one (a retail game's) has a 32-bit argument before the pointer – passed as 0, +/// stored as a dword, so the slot's upper half is whatever the stack held. Read the older way, +/// that call gave the low half of a pointer as the row pitch and the copy wrote rows gigabytes +/// past the destination. Told apart per call: a small value there with a readable pointer after +/// it is the newer form. +unsafe fn copy_args(a4: usize, a5: usize, a6: usize, a7: usize) -> (*const u8, u32, u32) { + // (address space, not readable memory: the title's pages are committed on first use) + let in_use = |a: usize| { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_FREE}; + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + a >= 0x1_0000 && VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 && m.State != MEM_FREE + }; + let newer = a4 as u32 <= 0xFFFF && in_use(a5); + // (a retail game calls both forms) + static SEEN: AtomicU32 = AtomicU32::new(0); + let bit = 1 << newer as u32; + if SEEN.fetch_or(bit, Ordering::Relaxed) & bit == 0 { + crate::xlog_info!("xg: CopyInto/FromSubresource called in the {} form", if newer { "newer 7-argument" } else { "6-argument" }); + } + if newer { + if a4 as u32 != 0 { + static EXTRA: std::sync::Once = std::sync::Once::new(); + EXTRA.call_once(|| crate::xlog_warn!("xg: CopyInto/FromSubresource with {:#x} in its added argument (meaning unknown, ignored)", a4 as u32)); + } + (a5 as *const u8, a6 as u32, a7 as u32) + } else { + (a4 as *const u8, a5 as u32, a6 as u32) + } +} + /// rows of `src` (`row_pitch` apart) → the level's place in `dst` (the whole resource) -unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, slice_pitch: u32) -> HRESULT { +unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, a4: usize, a5: usize, a6: usize, a7: usize) -> HRESULT { + let (src, row_pitch, slice_pitch) = copy_args(a4, a5, a6, a7); let Some((t, at, i, k)) = subresource(tex(p), plane, sub).filter(|_| !dst.is_null() && !src.is_null()) else { return E_INVALIDARG }; let m = t.chain.levels[i]; let row = m.width * t.bpe as usize; @@ -695,7 +729,8 @@ unsafe extern "system" fn copy_into(p: *mut c_void, dst: *mut u8, plane: u32, su } /// the level's place in `src` (the whole resource) → rows of `dst` (`row_pitch` apart) -unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, src: *const u8, row_pitch: u32, slice_pitch: u32) -> HRESULT { +unsafe extern "system" fn copy_from(p: *mut c_void, dst: *mut u8, plane: u32, sub: u32, a4: usize, a5: usize, a6: usize, a7: usize) -> HRESULT { + let (src, row_pitch, slice_pitch) = copy_args(a4, a5, a6, a7); let Some((t, at, i, k)) = subresource(tex(p), plane, sub).filter(|_| !dst.is_null() && !src.is_null()) else { return E_INVALIDARG }; let m = t.chain.levels[i]; let row = m.width * t.bpe as usize; @@ -732,6 +767,41 @@ mod tests { d } + /// CopyInto / CopyFromSubresource in both forms: the 6-argument one, and the newer one with a + /// 32-bit argument before the pointer whose stack slot's upper half holds garbage – the same + /// bytes tiled and read back, the pitch not taken from the pointer. + #[test] + fn subresource_copies_take_both_argument_forms() { + type Six = unsafe extern "system" fn(*mut c_void, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT; + type Seven = unsafe extern "system" fn(*mut c_void, *mut u8, u32, u32, usize, *const u8, u32, u32) -> HRESULT; + let d = desc(64, 32, 1, 1, 28, 0x109); + let mut c: *mut c_void = std::ptr::null_mut(); + unsafe { + assert!(XGCreateTextureComputer(d.as_ptr(), &mut c) >= 0); + let t = Texture::new(&d).unwrap(); + let size = t.size() as usize; + let pitch = 64 * 4 + 32; + let lin: Vec = (0..pitch * 32).map(|i| (i * 7 + i / 251) as u8).collect(); + let slot = |k: usize| *(*(c as *const *const usize)).add(k); + let (into6, from6): (Six, Six) = (std::mem::transmute(slot(8)), std::mem::transmute(slot(9))); + let (into7, from7): (Seven, Seven) = (std::mem::transmute(slot(8)), std::mem::transmute(slot(9))); + let (mut a, mut b) = (vec![0u8; size], vec![0u8; size]); + assert_eq!(into6(c, a.as_mut_ptr(), 0, 0, lin.as_ptr(), pitch as u32, 0), S_OK); + let garbage = 0x0000_0016_0000_0000usize; // a dword 0 under an old stack value + assert_eq!(into7(c, b.as_mut_ptr(), 0, 0, garbage, lin.as_ptr(), pitch as u32, 0), S_OK); + assert_eq!(a, b, "both forms tile the same bytes"); + let (mut back6, mut back7) = (vec![0u8; pitch * 32], vec![0u8; pitch * 32]); + assert_eq!(from6(c, back6.as_mut_ptr(), 0, 0, a.as_ptr(), pitch as u32, 0), S_OK); + assert_eq!(from7(c, back7.as_mut_ptr(), 0, 0, garbage, a.as_ptr(), pitch as u32, 0), S_OK); + for y in 0..32 { + let row = y * pitch..y * pitch + 64 * 4; + assert_eq!(back6[row.clone()], lin[row.clone()], "6-argument form, row {y}"); + assert_eq!(back7[row.clone()], lin[row], "7-argument form, row {y}"); + } + release(c); + } + } + /// As the console's library answers (seen on it): RGBA8 256×256, full chain, 64KB_S. #[test] fn rgba8_64kb_s_layout() { From 3ebfffc8ba08b33f9fe7630c91534000eaba3175 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:42:48 +0100 Subject: [PATCH 056/175] Recompiler: the HLSL NaN guard keeps finite PS exports, as the direct one does The HLSL path's `XCL_NAN_GUARD` (on by default) wrote every float colour export as clamp(v, -65504, 65504): NaN became 0 as intended, but every finite value was also cut to the f16 range. A 32-bit float target holds more: gpu_ps_readfirstlane_loop_on_a_primitive_edge_ends exports a 16-bit mask word as a float and read 0xFFFF back as 65504 (0xFFE0), so it failed on clean amd-dev (RX 9070 XT, 51 of 1024 pixels). The direct translator's `nan_guard_bits` only maps NaN to 0 and +-Inf to +-65504; the HLSL path now does the same. Test: gpu_ps_nan_guard_keeps_finite_exports exports (NaN, -Inf, 1e6, -70000) through both translators and expects (0, -65504, 1e6, -70000). (cherry picked from commit 957c8add81e54f1683d0a3ee975855f712e92a28) --- crates/xcl/src/gpu/recomp/emit.rs | 5 ++++- crates/xcl/src/gpu/recomp/tests.rs | 35 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index af1b0ee9ea..c03a9dc07f 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2419,8 +2419,11 @@ impl Em { (2, false) => format!("(int){raw}"), (_, _) => raw, }; + // NaN → 0, ±Inf → ±65504, finite values as they are (the direct + // translator's `nan_guard_bits`): a clamp of every value to the f16 range + // cut what a 32-bit float target holds above 65504 let v = if e.component_type == 3 && crate::gpu::dxil::kernel::nan_guard_enabled() { - format!("((asuint({v}) & 0x7FFFFFFFu) > 0x7F800000u ? 0.0f : clamp({v}, -65504.0f, 65504.0f))") + format!("select((asuint({v}) & 0x7FFFFFFFu) > 0x7F800000u, 0.0f, select((asuint({v}) & 0x7FFFFFFFu) == 0x7F800000u, asfloat((asuint({v}) & 0x80000000u) | 0x477FE000u), {v}))") } else { v }; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index f63767557d..66b10c726f 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -11207,6 +11207,41 @@ fn gpu_ps_readfirstlane_loop_on_a_primitive_edge_ends() { assert!(bad.is_empty(), "{} pixels wrong (iterations, wave OR, own word, lane count), first {:?}", bad.len(), &bad[..bad.len().min(8)]); } +/// The float color exports of a pixel shader with `XCL_NAN_GUARD` on (the default), through both +/// translators: NaN becomes 0 and ±Inf ±65504, finite values stay as they are – also past +/// 65504, which a 32-bit float target holds (the HLSL path clamped them to it). +#[test] +fn gpu_ps_nan_guard_keeps_finite_exports() { + if !gpu_ready() { + return; + } + if !crate::gpu::dxil::kernel::nan_guard_enabled() { + println!("XCL_NAN_GUARD=0: nothing to check"); + return; + } + use crate::gpu::dxil::kernel::{self, KernelOptions}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + let words = [0x7FC0_0000u32, 0xFF80_0000, 1.0e6f32.to_bits(), (-70000.0f32).to_bits()]; + let mut code = Vec::new(); + for (k, &w) in words.iter().enumerate() { + code.extend(encode("V_MOV_B32", "ENC_VOP1", &[("VDST", 4 + k as u64), ("SRC0", 255)], Some(w)).unwrap()); + } + code.extend(encode("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let psi = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; + let t = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let hlsl = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let direct = kernel::translate_pixel(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS").dxil; + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + for (form, ps) in [("HLSL", &hlsl), ("direct DXIL", &direct)] { + let px = runner::draw(&vs, ps, &layout, &quad, 8, &[], &[], 8, [9.0; 4]).unwrap(); + assert!(px.iter().all(|p| *p == [0.0, -65504.0, 1.0e6, -70000.0]), "{form}: (NaN, -Inf, 1e6, -70000) exported as {:?}", px[0]); + } +} + /// A wave32 pixel program under `s_wqm` with the march loop of a retail volumetric PS after /// another loop: every lane counts steps in a vector register, and the loop goes on as long as /// a lane of the mask taken from EXEC has not reached 6 (`v_cmp_le_f32`, `s_andn2 mask, mask, From 8c79f57ec025d2a78a8bee08e3d5ed9066141b2a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:44:21 +0100 Subject: [PATCH 057/175] Recompiler: direct DXIL wave32 PS / VS reductions count every live lane The console's compiler reduces a value over a wave32 wave with `s_or_saveexec -1`, `v_cndmask` of the value in the live lanes, three DPP8 steps, a row mirror, `v_permlanex16`, one more step and `v_readlane s, v, 0`. The HLSL path recognises this (`wave32_reductions`, 12f25f14) and takes a WaveActive op over the live lanes; the direct DXIL translator, which the tested configuration (`XCL_DIRECT_DXIL=all`) uses for these shaders, ran the steps one by one. They pass partial results through lanes that are not there on the host: lanes never launched in a partly filled wave read 0, and a helper lane's wave reads give it 0, which every lane then reads back from lane 0. On two triangles sharing a diagonal (RX 9070 XT) the min of a wave was 0 for 105 of 1024 pixels, all in waves along the diagonal; the HLSL form was right everywhere. A retail clustered-lighting pixel shader takes the slice range (min / max) and the bit-or of its pixels' light lists this way in its light loop, and loops over the lights of the result: a wave on a primitive's edge whose lane 0 is a helper lane got the lights of lane 0's quad only. That matches the small dark triangles along the 16-pixel tiles' diagonals in its output (visual defect 9). VIctory-Neo (findings: square holes and dashed edges in shadows) traced the same class of fault to pixel shaders whose wave reads leave helper lanes out on AMD. The direct translator now finds the same reductions (`Lw::reductions`), keeps the seed in a temporary, and at the `v_readlane` takes the operation over the live lanes of its console wave (each half of a 64-lane hardware wave is one); a helper lane takes the result from a live lane of its quad, as the HLSL `xcl_red_share` does. Test: gpu_ps_wave32_reductions_count_live_lanes_only (min / max / or of a constant over the live lanes, both translators, two triangles). (cherry picked from commit 571cab1be4529053672020536a94fab3119a008a) --- crates/xcl/src/gpu/dxil/kernel.rs | 6 +++ crates/xcl/src/gpu/dxil/lanes.rs | 52 ++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower.rs | 14 +++++- crates/xcl/src/gpu/dxil/lower_valu.rs | 8 +++ crates/xcl/src/gpu/recomp/mod.rs | 2 +- crates/xcl/src/gpu/recomp/tests.rs | 71 +++++++++++++++++++++++++++ 6 files changed, 151 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 8034916dab..e0063a5a14 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -730,6 +730,8 @@ impl Lw { gfx_half: None, whole_live: Default::default(), ps_masks: Default::default(), + reductions: Default::default(), + red_seeds: HashMap::new(), guard_override: None, mask_override: None, local_masks: false, @@ -766,6 +768,10 @@ impl Lw { } } lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders, matches!(entry, Entry::Vertex(_) | Entry::Pixel(_))); + // (as the HLSL path finds them: `recomp::translate`) + if !o.wave64 && matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)) { + lw.reductions = crate::gpu::recomp::wave32_reductions(insts, leaders); + } let group_threads: Option = match entry { Entry::Vertex(_) | Entry::Pixel(_) => None, Entry::Kernel => None, diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index ed5fe2c783..aad87b77b4 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -930,6 +930,58 @@ impl Lw { self.first_lane(lo, hi) } + /// The end of a whole-wave reduction of a wave32 VS / PS (`recomp::wave32_reductions`, the + /// HLSL `xcl_red_`): `op` over the seed `x` of every live lane of this console wave (a + /// half of a 64-lane hardware wave is one). The console's DPP and permlane steps pass partial + /// results through lanes that are not here: lanes never launched read 0, and a helper lane's + /// wave reads give it 0 too, which every lane then read back from lane 0 (`v_readlane s, v, 0`) + /// – the min of a partly filled wave on a primitive's edge was 0. A helper lane takes the + /// result from a live lane of its quad (every quad has one). + pub fn wave32_reduction(&mut self, x: Value, op: &str) -> Value { + use super::ops::{WaveBit, WaveOp}; + let identity = if matches!(op, "and" | "min") { u32::MAX } else { 0 }; + let reduce = |lw: &mut Lw, v: Value| match op { + "or" => lw.s.wave_active_bit(v, WaveBit::Or), + "and" => lw.s.wave_active_bit(v, WaveBit::And), + "max" => lw.s.wave_active_op(v, WaveOp::Max, true), + _ => lw.s.wave_active_op(v, WaveOp::Min, true), + }; + let r = match self.gfx_half { + Some(h) => { + let id = self.c(identity); + let lo = self.sel(h, id, x); + let hi = self.sel(h, x, id); + let a = reduce(self, lo); + let b = reduce(self, hi); + self.sel(h, b, a) + } + None => reduce(self, x), + }; + if !self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) { + return r; + } + let hw = self.s.wave_lane_index(); + let t = self.s.m.i1c(true); + let lv = self.s.wave_ballot(t); + let upper = self.cmpc(Pred::UGe, hw, 32); + let w = self.sel(upper, lv[1], lv[0]); + let sh = self.andc(hw, 28); + let nib = self.bin(BinOp::LShr, w, sh); + let nib = self.andc(nib, 15); + let k = self.firstbitlow(nib); + let q: Vec = (0..4u32).map(|n| { + let kk = self.c(n); + self.s.quad_read_lane_at(r, kk) + }).collect(); + let b1 = self.andc(k, 1); + let b1 = self.nz(b1); + let b2 = self.andc(k, 2); + let b2 = self.nz(b2); + let hi = self.sel(b1, q[3], q[2]); + let lo = self.sel(b1, q[1], q[0]); + self.sel(b2, hi, lo) + } + /// `v_readfirstlane_b32`'s result `first` of `own` in a pixel shader: a helper lane takes its /// own value instead so helper-only waterfall loops converge in one pass on AMD RDNA4. pub fn helper_reads_own(&mut self, own: Value, first: Value) -> Value { diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index b672bf06e7..d42a7f93a4 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -295,6 +295,10 @@ pub struct Lw { pub whole_live: std::collections::BTreeMap, /// pixel shaders: compares whose mask needs less than the per-quad form (`recomp::ps_masks`) pub ps_masks: std::collections::BTreeMap, + /// wave32 VS / PS: the whole-wave reductions (`recomp::wave32_reductions`), and the + /// temporaries their seeds are kept in (by the seed's pc) + pub reductions: crate::gpu::recomp::Reductions, + pub red_seeds: HashMap, /// set when an exchange was needed where it is not supported pub exchange_error: Option, pub pc: u64, @@ -1014,7 +1018,7 @@ impl Lw { if NOOPS.contains(&name.as_str()) { return Ok(()); } - match d.enc.name { + let r = match d.enc.name { "ENC_SOPP" => self.sopp(d, &name), "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => self.salu(d, &name), "ENC_SMEM" => self.smem(d, &name), @@ -1026,7 +1030,15 @@ impl Lw { "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => self.flat(d, &name), e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => self.valu(d, &name), _ => err(d, "encoding"), + }; + // the seed of a whole-wave reduction, kept for the `v_readlane` that ends it + if let Some(&v) = self.reductions.seeds.get(&d.pc) { + let x = self.vreg(v); + let t = self.tmp_var(); + self.wr(t, x); + self.red_seeds.insert(d.pc, t); } + r } /// The condition of a conditional branch (i1). diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index d61ecbf3f5..c575a6e24b 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -1008,6 +1008,14 @@ impl Lw { return Ok(()); } "v_readlane_b32" => { + // the end of a whole-wave reduction (`recomp::wave32_reductions`) + if let Some(t) = self.reductions.reads.get(&self.pc).and_then(|(seed, _)| self.red_seeds.get(seed)).copied() { + let op = self.reductions.reads[&self.pc].1; + let x = self.rd(t); + let r = self.wave32_reduction(x, op); + self.write32(&dst, r); + return Ok(()); + } let l = self.andc(b, wmask); let t = self.read_lane_uniform(a, l); self.write32(&dst, t); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index ac0826e996..12433340ff 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1191,7 +1191,7 @@ pub struct Reductions { /// `s_or_saveexec_b32 s, -1` (every lane runs, launched or not), `v_cndmask v, identity, value, /// mask`, three DPP8 steps (within 2, 4 and 8 lanes), a DPP row mirror, `v_permlanex16 w, v`, one more /// step and `v_readlane s, v, 0` – nothing else in between, all in one basic block. -fn wave32_reductions(insts: &[Decoded], leaders: &std::collections::BTreeSet) -> Reductions { +pub(crate) fn wave32_reductions(insts: &[Decoded], leaders: &std::collections::BTreeSet) -> Reductions { let op_of = |d: &Decoded| match d.inst.name { "V_OR_B32" => Some(("or", 128)), "V_MAX_U32" => Some(("max", 128)), diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 66b10c726f..a01518368f 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2847,6 +2847,77 @@ fn gpu_ps_helper_lanes_see_ballots_and_quads_are_lanes_4k() { assert_eq!(quads, px.len(), "quads not at hardware lanes 4k..4k+3"); } +/// The whole-wave reductions a wave32 pixel shader of the console makes (a retail clustered- +/// lighting shader takes the range and the bit-or of its pixels' light lists this way): +/// `s_or_saveexec_b32 s, -1`, `v_cndmask` of the value in the live lanes (the entry EXEC, saved +/// before `s_wqm`) and the identity elsewhere, three DPP8 steps, a row mirror, `v_permlanex16`, +/// one more step and `v_readlane s, v, 0`. Every live lane holds 7 for the min, 5 for the max +/// and 0x10 for the bit-or; the export is the three results and 1.0. +fn wave32_reductions_ps() -> Vec { + type I = (&'static str, &'static str, Vec<(&'static str, u64)>, Option); + let sop1 = |n: &'static str, d: u64, s: u64| -> I { (n, "ENC_SOP1", vec![("SDST", d), ("SSRC0", s)], None) }; + let dpp8 = |op: &'static str, sel: [u64; 8]| -> I { + let mut f = vec![("VDST", 0), ("SRC0", 0xE9), ("VSRC0", 0), ("VSRC1", 0)]; + f.extend(["LANE_SEL_0", "LANE_SEL_1", "LANE_SEL_2", "LANE_SEL_3", "LANE_SEL_4", "LANE_SEL_5", "LANE_SEL_6", "LANE_SEL_7"].into_iter().zip(sel)); + (op, "VOP2_VOP_DPP8", f, None) + }; + let mut l: Vec = vec![sop1("S_MOV_B32", 88, 126), sop1("S_WQM_B32", 126, 126)]; + for (k, (op, identity, value)) in [("V_MIN_U32", 193, 7), ("V_MAX_U32", 128, 5), ("V_OR_B32", 128, 0x10)].into_iter().enumerate() { + l.extend([ + sop1("S_OR_SAVEEXEC_B32", 3, 193), + ("S_AND_B32", "ENC_SOP2", vec![("SDST", 2), ("SSRC0", 88), ("SSRC1", 3)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 4), ("SRC0", 128 + value)], None), + ("V_CNDMASK_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", identity), ("SRC1", V + 4), ("SRC2", 2)], None), + dpp8(op, [1, 0, 3, 2, 5, 4, 7, 6]), + dpp8(op, [2, 2, 0, 0, 6, 6, 4, 4]), + dpp8(op, [4, 4, 4, 4, 0, 0, 0, 0]), + (op, "VOP2_VOP_DPP16", vec![("VDST", 0), ("SRC0", 0xFA), ("VSRC0", 0), ("VSRC1", 0), ("DPP_CTRL", 0x140), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF), ("BOUND_CTRL", 1)], None), + ("V_PERMLANEX16_B32", "ENC_VOP3", vec![("VDST", 1), ("SRC0", V), ("SRC1", 128), ("SRC2", 128)], None), + (op, "ENC_VOP2", vec![("VDST", 0), ("SRC0", V + 1), ("VSRC1", 0)], None), + ("V_READLANE_B32", "ENC_VOP3", vec![("VDST", 10 + k as u64), ("SRC0", V), ("SRC1", 128)], None), + sop1("S_MOV_B32", 126, 3), + ]); + } + l.extend([ + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 5), ("SRC0", 10)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 6), ("SRC0", 11)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", 12)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 8), ("SRC0", 242)], None), + sop1("S_MOV_B32", 126, 88), + ("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 5), ("VSRC1", 6), ("VSRC2", 7), ("VSRC3", 8), ("DONE", 1), ("VM", 1)], None), + ("S_ENDPGM", "ENC_SOPP", vec![], None), + ]); + l.iter().flat_map(|(n, e, f, x)| encode(n, e, f, *x).unwrap_or_else(|err| panic!("{n}: {err}"))).collect() +} + +/// `wave32_reductions_ps` on the GPU, through both translators, on two triangles that share the +/// diagonal (waves there are partly filled and hold helper lanes): every pixel gets the +/// reductions of its wave's live lanes. +#[test] +fn gpu_ps_wave32_reductions_count_live_lanes_only() { + if !gpu_ready() { + return; + } + use crate::gpu::dxil::kernel::{self, KernelOptions}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + let psi = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let size = 32usize; + let code = wave32_reductions_ps(); + let t = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let hlsl = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let direct = kernel::translate_pixel(&code, KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS").dxil; + for (form, ps) in [("HLSL", &hlsl), ("direct DXIL", &direct)] { + let px = runner::draw(&vs, ps, &layout, &quad, 8, &[], &[], size as u32, [9.0; 4]).unwrap(); + let bad: Vec<(usize, usize, [f32; 4])> = (0..size * size).filter(|&i| px[i] != [7.0, 5.0, 16.0, 1.0]).map(|i| (i % size, i / size, px[i])).collect(); + println!("{form}: {} of {} pixels wrong, first {:?}", bad.len(), size * size, &bad[..bad.len().min(4)]); + assert!(bad.is_empty(), "{form}: {} pixels wrong (min 7, max 5, or 16, 1), first (x, y, got) {:?}", bad.len(), &bad[..bad.len().min(6)]); + } +} + /// XCL image descriptor (T#, GFX10 layout): BASE_ADDRESS = SRV heap index, FORMAT, TYPE. fn tsharp(index: u32, format: u32, ty: u32) -> [u32; 8] { [index, format << 20, 0, ty << 28, 0, 0, 0, 0] From 45ed56c805ea366a14c1c1e8b400ac629f1e3c9f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:49:14 +0100 Subject: [PATCH 058/175] Recompiler: quad-local lane reads of pixel shaders take quad reads alone MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A pixel shader's lane reads that stay in the reader's quad – DPP16 quad_perm and row_xmask below 4, quad-local DPP8 patterns, ds_swizzle in quad mode or a bit mode that keeps the quad – went through `rla` in both translators: four QuadReadLaneAt for the quad, plus a WaveReadLaneAt, a ballot and four more wave reads that only served lanes of other quads and were thrown away. Every derivative the console's code takes by DPP (quad sums, ddx / ddy of shading values) paid for them, in loops too, and on AMD a wave read inside a loop has left helper lanes' registers unreliable (RX 6700 XT, `first_lane_live`); the console's quad reads see helper lanes. VIctory-Neo (KyleS98/VIctory-Neo, docs/findings.md: square holes and dashed edges in shadows) lowers these reads to quad operations alone for the same reason; upstream PR #2316 does it for direct DXIL with quadOp. This uses QuadReadLaneAt with constant lanes only, as `rla` already does in every pixel shader (quadOp of values derived from wave reads crashed AMD's compiler, #134), and covers the HLSL path as well. `emit::quad_map` finds such a read from its source lane per lane (DPP16 by `dpp16_lane`, DPP8, `swizzle_lane`); `Em::quad_read` / `Lw::read_lane_quad` read each quad position the map names once and select by lane & 3 (a broadcast is one read, the identity none). The source lane's EXEC bit is still checked as before. `XCL_PS_QUAD_READS=0` restores the `rla` form in both translators (default on; in the translated cache's identity). Tests: quad_local_lane_reads (the maps), ps_quad_local_lane_reads_take_quad_reads_only (no wave read or quadOp in the PS of either translator, wave32 and wave64; a compute program keeps rla), gpu_ps_quad_reads_in_a_loop_see_helper_lanes (quad sums, diagonal, row and column neighbours inside a loop with a v_readfirstlane, on two triangles: every pixel of both translators, wave32 and wave64, RX 9070 XT; it passes on the earlier form too there). (cherry picked from commit 1855d0cb1c65c3c6a7f41a2bf4e43aeda17767eb) --- crates/xcl/src/gpu/dxil/lanes.rs | 47 +++++++ crates/xcl/src/gpu/dxil/lower_mem.rs | 5 +- crates/xcl/src/gpu/dxil/lower_valu.rs | 10 +- crates/xcl/src/gpu/recomp/emit.rs | 114 ++++++++++++++++- crates/xcl/src/gpu/recomp/pso.rs | 2 + crates/xcl/src/gpu/recomp/tests.rs | 171 ++++++++++++++++++++++++++ 6 files changed, 340 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index aad87b77b4..e0a5bfaf3c 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -823,6 +823,53 @@ impl Lw { } } + /// The quad positions a pixel shader's lane read whose source lane is `src(lane)` takes + /// (`recomp::emit::quad_map`, `ps_quad_reads_wanted`); None where it is not one. + pub fn ps_quad(&self, src: impl Fn(u32) -> Option) -> Option<[u8; 4]> { + use crate::gpu::recomp::emit; + if !self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) || self.split || !emit::ps_quad_reads_wanted() { + return None; + } + emit::quad_map(if self.wave64 { 64 } else { 32 }, src) + } + + /// `v` of quad position `map[lane & 3]` of this lane's quad (`ps_quad`), through + /// `QuadReadLaneAt` with constant lanes alone: quad reads see helper lanes, and no wave read + /// is made (the HLSL `Em::quad_read`). + pub fn read_lane_quad(&mut self, v: Value, map: [u8; 4]) -> Value { + if map == [0, 1, 2, 3] { + return v; + } + if map.iter().all(|&k| k == map[0]) { + let k = self.c(map[0].into()); + return self.s.quad_read_lane_at(v, k); + } + let mut reads: [Option; 4] = [None; 4]; + let mut vals = [v; 4]; + for (i, &k) in map.iter().enumerate() { + let k = k as usize; + if k == i { + continue; + } + if reads[k].is_none() { + let kk = self.c(k as u32); + reads[k] = Some(self.s.quad_read_lane_at(v, kk)); + } + vals[i] = reads[k].unwrap(); + } + let lane = self.lane; + let b1 = self.andc(lane, 1); + let b1 = self.nz(b1); + let lo = if vals[0] == vals[1] { vals[0] } else { self.sel(b1, vals[1], vals[0]) }; + let hi = if vals[2] == vals[3] { vals[2] } else { self.sel(b1, vals[3], vals[2]) }; + if lo == hi { + return lo; + } + let b2 = self.andc(lane, 2); + let b2 = self.nz(b2); + self.sel(b2, hi, lo) + } + /// The HLSL `rla(v, l)`: `WaveReadLaneAt(v, l + 32 · xcl_half)`; in a pixel shader, lanes /// of the reader's own quad through quad reads (they see helper lanes, wave reads do /// not), and a helper lane of another quad through a live lane of that quad. diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 58b725de43..14372057c0 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2153,7 +2153,10 @@ impl Lw { let a = self.vreg(f("ADDR")); let l = self.swizzle_lane(off16 as u64); let (el, eh) = self.exec_mask(); - let v = self.read_lane_half(a, l); + let v = match self.ps_quad(|lane| Some((lane & 0x20) | crate::gpu::recomp::emit::swizzle_lane(off16 as u64, lane))) { + Some(map) => self.read_lane_quad(a, map), + None => self.read_lane_half(a, l), + }; let on = self.lanebit_at(el, eh, l); let z = self.c(0); let t = self.sel(on, v, z); diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index c575a6e24b..54e6236ba8 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -213,7 +213,10 @@ impl Lw { let fib = self.b(fi); let ok0 = self.lor(fib, on); let ok = self.land(valid, ok0); - let r = self.read_lane_half(v, lc); + let r = match self.ps_quad(|lane| crate::gpu::recomp::emit::dpp16_lane(ctrl, lane)) { + Some(map) => self.read_lane_quad(v, map), + None => self.read_lane_half(v, lc), + }; let (rm, bm) = (fv("ROW_MASK") as u32, fv("BANK_MASK") as u32); let lane = self.lane; let row = self.lshrc(lane, 4); @@ -247,7 +250,10 @@ impl Lw { let s = self.bin(BinOp::LShr, k, sh); let s = self.andc(s, 7); let l = self.or(a, s); - let r = self.read_lane_half(v, l); + let r = match self.ps_quad(|lane| Some((lane & !7) | ((sel as u32 >> (3 * (lane & 7))) & 7))) { + Some(map) => self.read_lane_quad(v, map), + None => self.read_lane_half(v, l), + }; t = if !fi { let on = self.lanebit_at(el, eh, l); let z = self.c(0); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index c03a9dc07f..7a67654a82 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -329,6 +329,56 @@ fn dpp16_src(ctrl: u64) -> Option { }) } +/// `dpp16_src` for one lane: the source lane, None where there is none. +pub(crate) fn dpp16_lane(ctrl: u64, lane: u32) -> Option { + let n = (ctrl & 15) as u32; + let r = lane & 15; + match ctrl { + 0x000..=0x0FF => Some((lane & !3) | ((ctrl as u32 >> (2 * (lane & 3))) & 3)), + 0x101..=0x10F => (r + n < 16).then_some(lane + n), + 0x111..=0x11F => (r >= n).then(|| lane - n), + 0x121..=0x12F => Some((lane & !15) | (r.wrapping_sub(n) & 15)), + 0x140 => Some((lane & !15) | (15 - r)), + 0x141 => Some((lane & !15) | (lane & 8) | (7 - (lane & 7))), + 0x150..=0x15F => Some((lane & !15) | n), + 0x160..=0x16F => Some(lane ^ n), + _ => None, + } +} + +/// A lane read whose source `src(lane)` lies in the reader's quad for each of the wave's `lanes` +/// lanes, at a quad position that depends only on the reader's: that position for each reader's +/// (`map[lane & 3]`); None when a source leaves the quad or is missing. +pub(crate) fn quad_map(lanes: u32, src: impl Fn(u32) -> Option) -> Option<[u8; 4]> { + let mut map = [None; 4]; + for l in 0..lanes { + let s = src(l)?; + if s >> 2 != l >> 2 { + return None; + } + let k = &mut map[(l & 3) as usize]; + if k.is_some_and(|k| k != s & 3) { + return None; + } + *k = Some(s & 3); + } + Some(map.map(|k| k.unwrap_or(0) as u8)) +} + +/// Pixel shaders: lane reads that stay in the reader's quad (DPP quad_perm, row_xmask below 4, +/// such DPP8 and `ds_swizzle` patterns) read through `QuadReadLaneAt` alone (`quad_map`), not +/// `rla`, whose wave reads and ballot only served lanes of other quads; on AMD a wave read inside +/// a loop leaves helper lanes' registers unreliable, and the console's derivatives read them. +/// `XCL_PS_QUAD_READS=0`: through `rla`, the earlier form (both translators). +pub fn ps_quad_reads_wanted() -> bool { + ps_quad_reads_for(std::env::var("XCL_PS_QUAD_READS").ok().as_deref()) +} + +/// `ps_quad_reads_wanted` for the value `env` of `XCL_PS_QUAD_READS`: on unless it is `0`. +pub(crate) fn ps_quad_reads_for(env: Option<&str>) -> bool { + env.is_none_or(|v| v.trim() != "0") +} + /// The lane `lane` of a 32-lane half reads with `ds_swizzle_b32` (the RDNA ISA's DS_SWIZZLE_B32): /// offset ≥ 0xE000 FFT, ≥ 0xC000 rotate, bit 15 quad permute, otherwise the and/or/xor bit /// mode (xor = offset[14:10], so 0x401F swaps the 16-lane halves). @@ -768,6 +818,43 @@ impl Em { } } + /// The quad positions a pixel shader's lane read whose source lane is `src(lane)` takes + /// (`quad_map`, `ps_quad_reads_wanted`); None where it is not one. + fn ps_quad(&self, src: impl Fn(u32) -> Option) -> Option<[u8; 4]> { + if !matches!(self.opt.mode, Mode::Pixel(_)) || self.x64() || !ps_quad_reads_wanted() { + return None; + } + quad_map(if self.opt.wave64 { 64 } else { 32 }, src) + } + + /// `v` of quad position `map[lane & 3]` of this lane's quad (`ps_quad`), through + /// `QuadReadLaneAt` with constant lanes alone (declared as `{t}_q`). + fn quad_read(&mut self, v: &str, map: [u8; 4], t: &str) -> String { + if map == [0, 1, 2, 3] { + return v.to_string(); + } + if map.iter().all(|&k| k == map[0]) { + return format!("QuadReadLaneAt({v}, {}u)", map[0]); + } + let mut read = [false; 4]; + let mut vals: Vec = Vec::new(); + for (i, &k) in map.iter().enumerate() { + if k as usize == i { + vals.push(v.to_string()); + continue; + } + if !read[k as usize] { + read[k as usize] = true; + self.line(&format!("uint {t}_q{k} = QuadReadLaneAt({v}, {k}u);")); + } + vals.push(format!("{t}_q{k}")); + } + let pick = |a: &str, b: &str, bit: u32| if a == b { a.to_string() } else { format!("select((lane_id & {bit}u) != 0u, {b}, {a})") }; + let lo = pick(&vals[0], &vals[1], 1); + let hi = pick(&vals[2], &vals[3], 1); + pick(&lo, &hi, 2) + } + /// Lane read with the same lane index in every lane (v_readlane, v_readfirstlane). fn rla_uniform_fn(&self) -> &'static str { if self.x64() { @@ -3229,8 +3316,13 @@ impl Em { self.line(&format!( "bool {t}_ok = and({t}_l >= 0, or({fi}, lanebit_at({el}, {eh}, (uint){t}_l)));" )); - let rla = self.rla_half_fn(); - self.line(&format!("uint {t} = {rla}({v}, (uint)max({t}_l, 0));")); + if let Some(map) = self.ps_quad(|lane| dpp16_lane(ctrl, lane)) { + let r = self.quad_read(&v, map, &t); + self.line(&format!("uint {t} = {r};")); + } else { + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({v}, (uint)max({t}_l, 0));")); + } let (rm, bm) = (fv("ROW_MASK"), fv("BANK_MASK")); // write enable: row/bank masks, and an invalid source either reads 0 (bound_ctrl) or disables let mut en = format!("((({rm}u >> (lane_id >> 4)) & 1u) != 0u && (({bm}u >> ((lane_id >> 2) & 3u)) & 1u) != 0u)"); @@ -3244,8 +3336,13 @@ impl Em { let sel: u64 = (0..8).map(|i| fv(&format!("LANE_SEL_{i}")) << (3 * i)).sum(); let fi = rdna2::field_value(d.enc, &d.words, "SRC0").unwrap_or(0) == 0xEA; self.line(&format!("uint {t}_l = (lane_id & ~7u) | (({sel}u >> (3u * (lane_id & 7u))) & 7u);")); - let rla = self.rla_half_fn(); - self.line(&format!("uint {t} = {rla}({v}, {t}_l);")); + if let Some(map) = self.ps_quad(|lane| Some((lane & !7) | ((sel as u32 >> (3 * (lane & 7))) & 7))) { + let r = self.quad_read(&v, map, &t); + self.line(&format!("uint {t} = {r};")); + } else { + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({v}, {t}_l);")); + } if !fi { self.line(&format!("{t} = select(lanebit_at({el}, {eh}, {t}_l), {t}, 0u);")); } @@ -4636,8 +4733,13 @@ impl Em { let (el, eh) = (self.sreg(126), self.sreg(127)); let eh = if self.opt.wave64 { eh } else { "0u".into() }; self.line(&format!("uint {t}_l = {src};")); - let rla = self.rla_half_fn(); - self.line(&format!("uint {t} = {rla}({a}, {t}_l);")); + if let Some(map) = self.ps_quad(|lane| Some((lane & 0x20) | swizzle_lane(off16, lane))) { + let r = self.quad_read(&a, map, &t); + self.line(&format!("uint {t} = {r};")); + } else { + let rla = self.rla_half_fn(); + self.line(&format!("uint {t} = {rla}({a}, {t}_l);")); + } self.line(&format!("{t} = select(lanebit_at({el}, {eh}, {t}_l), {t}, 0u);")); let dst = Dst::V(f("VDST")); self.write32(&dst, &t); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index d596001a9f..7b704cd9c8 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -313,6 +313,8 @@ mod translated { } else { id }; // `XCL_X_LDS_ORDER=0`: the split wave64 form without its LDS order, in both translators let id = if crate::gpu::recomp::emit::lds_order_wanted() { id } else { identity_for(&id.to_string(), "xcl-x-lds-order-0") }; + // `XCL_PS_QUAD_READS=0`: pixel shaders' quad-local lane reads through `rla`, in both translators + let id = if crate::gpu::recomp::emit::ps_quad_reads_wanted() { id } else { identity_for(&id.to_string(), "xcl-ps-quad-reads-0") }; // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity if Backend::current() != Backend::Hlsl && crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index a01518368f..2e83245311 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2847,6 +2847,64 @@ fn gpu_ps_helper_lanes_see_ballots_and_quads_are_lanes_4k() { assert_eq!(quads, px.len(), "quads not at hardware lanes 4k..4k+3"); } +/// A pixel shader that reads its quad's neighbours inside a loop that also has a wave read, as +/// a retail tiled-lighting shader does (quad sums by `v_mov_b32_dpp quad_perm` in its light +/// loop, `v_readfirstlane` of uniform values beside them). Per pixel, of f = pos.x + 64 · pos.y, +/// three passes: the quad's sum by two quad_perm DPPs, the diagonal neighbour by `ds_swizzle` +/// (quad mode), the other row's by DPP8 plus the other column's by DPP16 row_xmask:1, and the +/// count of a `v_readfirstlane` of 1.0. The quads on the two triangles' shared diagonal hold +/// helper lanes, whose f the console's reads see. +fn quad_reads_in_a_loop_ps(wave64: bool) -> Vec { + let (mov, wqm) = if wave64 { ("S_MOV_B64", "S_WQM_B64") } else { ("S_MOV_B32", "S_WQM_B32") }; + type I = (&'static str, &'static str, Vec<(&'static str, u64)>, Option); + let dpp16 = |d: u64, s: u64, ctrl: u64| -> I { ("V_MOV_B32", "VOP1_VOP_DPP16", vec![("VDST", d), ("SRC0", 0xFA), ("VSRC0", s), ("DPP_CTRL", ctrl), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None) }; + let add = |d: u64, a: u64, b: u64| -> I { ("V_ADD_F32", "ENC_VOP2", vec![("VDST", d), ("SRC0", a), ("VSRC1", b)], None) }; + let head: Vec = vec![ + (mov, "ENC_SOP1", vec![("SDST", 20), ("SSRC0", 126)], None), // the live lanes + (wqm, "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 126)], None), + ("V_MUL_F32", "ENC_VOP2", vec![("VDST", 6), ("SRC0", 255), ("VSRC1", 3)], Some(64f32.to_bits())), + add(6, V + 6, 2), // v6 = f + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 11), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 12), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 13), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14), ("SRC0", 128)], None), + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 11), ("SSRC0", 242)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 15), ("SRC0", 11)], None), // 1.0 in every lane + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 8), ("SSRC0", 128)], None), + ]; + let body: Vec = vec![ + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 9), ("SRC0", V + 15)], None), + add(14, 9, 14), + dpp16(7, 6, 0xB1), // quad_perm [1,0,3,2] + add(7, V + 7, 6), + dpp16(8, 7, 0x4E), // quad_perm [2,3,0,1] + add(8, V + 8, 7), + add(13, V + 13, 8), + // quad_perm [3,2,1,0]: the diagonal + ("DS_SWIZZLE_B32", "ENC_DS", vec![("VDST", 9), ("ADDR", 6), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)], None), + add(12, V + 12, 9), + ("V_MOV_B32", "VOP1_VOP_DPP8", vec![("VDST", 10), ("SRC0", 0xE9), ("VSRC0", 6), ("LANE_SEL_0", 2), ("LANE_SEL_1", 3), ("LANE_SEL_2", 0), ("LANE_SEL_3", 1), ("LANE_SEL_4", 6), ("LANE_SEL_5", 7), ("LANE_SEL_6", 4), ("LANE_SEL_7", 5)], None), + add(11, V + 11, 10), + dpp16(10, 6, 0x161), // row_xmask:1 + add(11, V + 11, 10), + ("S_ADD_U32", "ENC_SOP2", vec![("SDST", 8), ("SSRC0", 8), ("SSRC1", 129)], None), + ("S_CMP_LT_U32", "ENC_SOPC", vec![("SSRC0", 8), ("SSRC1", 131)], None), + ]; + let tail: Vec = vec![ + (mov, "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 20)], None), + ("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 13), ("VSRC1", 12), ("VSRC2", 14), ("VSRC3", 11), ("DONE", 1), ("VM", 1)], None), + ]; + let enc = |l: &[I]| -> Vec { l.iter().flat_map(|(n, e, f, x)| encode(n, e, f, *x).unwrap_or_else(|err| panic!("{n}: {err}"))).collect() }; + let body_code = enc(&body); + let back = (-((body_code.len() as i64 + 4) / 4)) as u16 as u64; + let mut code = enc(&head); + code.extend(&body_code); + code.extend(encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back)], None).unwrap()); + code.extend(enc(&tail)); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code +} + /// The whole-wave reductions a wave32 pixel shader of the console makes (a retail clustered- /// lighting shader takes the range and the bit-or of its pixels' light lists this way): /// `s_or_saveexec_b32 s, -1`, `v_cndmask` of the value in the live lanes (the entry EXEC, saved @@ -2918,6 +2976,119 @@ fn gpu_ps_wave32_reductions_count_live_lanes_only() { } } +/// Which lane reads stay in the reader's quad (`emit::quad_map`), and `XCL_PS_QUAD_READS`. +#[test] +fn quad_local_lane_reads() { + use super::emit::{dpp16_lane, ps_quad_reads_for, quad_map, swizzle_lane}; + let dpp16 = |ctrl: u64| quad_map(64, |l| dpp16_lane(ctrl, l)); + assert_eq!(dpp16(0xB1), Some([1, 0, 3, 2]), "quad_perm [1,0,3,2]"); + assert_eq!(dpp16(0x1B), Some([3, 2, 1, 0]), "quad_perm [3,2,1,0]"); + assert_eq!(dpp16(0x00), Some([0, 0, 0, 0]), "quad_perm broadcast"); + assert_eq!(dpp16(0xE4), Some([0, 1, 2, 3]), "quad_perm identity"); + assert_eq!(dpp16(0x163), Some([3, 2, 1, 0]), "row_xmask:3"); + for ctrl in [0x101, 0x111, 0x121, 0x140, 0x141, 0x150, 0x164] { + assert_eq!(dpp16(ctrl), None, "DPP_CTRL {ctrl:#x} leaves the quad"); + } + let dpp8 = |sel: [u32; 8]| quad_map(32, |l| Some((l & !7) | sel[(l & 7) as usize])); + assert_eq!(dpp8([2, 3, 0, 1, 6, 7, 4, 5]), Some([2, 3, 0, 1])); + assert_eq!(dpp8([1, 0, 3, 2, 5, 4, 7, 6]), Some([1, 0, 3, 2])); + assert_eq!(dpp8([2, 2, 0, 0, 6, 6, 4, 4]), Some([2, 2, 0, 0])); + assert_eq!(dpp8([4, 4, 4, 4, 0, 0, 0, 0]), None); + assert_eq!(dpp8([1, 0, 3, 2, 4, 5, 6, 7]), None, "a different pattern in the second quad"); + let swizzle = |offset: u64| quad_map(64, |l| Some((l & 0x20) | swizzle_lane(offset, l))); + assert_eq!(swizzle(0x801B), Some([3, 2, 1, 0]), "quad mode"); + assert_eq!(swizzle(0x041F), Some([1, 0, 3, 2]), "bit mode, xor 1"); + assert_eq!(swizzle(0x001C), Some([0, 0, 0, 0]), "bit mode, and 0x1C"); + assert_eq!(swizzle(0x101F), None, "bit mode, xor 4"); + assert_eq!(swizzle(0x0010), None, "bit mode, and 0x10"); + assert!(ps_quad_reads_for(None) && ps_quad_reads_for(Some("1")) && ps_quad_reads_for(Some(""))); + assert!(!ps_quad_reads_for(Some("0")) && !ps_quad_reads_for(Some(" 0 "))); +} + +/// A pixel shader whose lane reads all stay in the quad (DPP16 quad_perm and row_xmask, DPP8, +/// `ds_swizzle` quad mode) reads only through `QuadReadLaneAt`, in both translators: no wave read, +/// no ballot, no `quadOp` (#134). A compute program's keep their wave reads. +#[test] +fn ps_quad_local_lane_reads_take_quad_reads_only() { + use crate::gpu::dxil::{kernel, validate}; + if !super::emit::ps_quad_reads_wanted() { + println!("XCL_PS_QUAD_READS=0: nothing to check"); + return; + } + let dpp16 = |d: u64, ctrl: u64| encode("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", d), ("SRC0", 0xFA), ("VSRC0", 2), ("DPP_CTRL", ctrl), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)], None).unwrap(); + let reads = |wqm: &str| -> Vec { + let mut c = Vec::new(); + c.extend(encode(wqm, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None).unwrap()); + c.extend(dpp16(7, 0xB1)); + c.extend(encode("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 8), ("ADDR", 2), ("OFFSET0", 0x1B), ("OFFSET1", 0x80)], None).unwrap()); + c.extend(encode("V_MOV_B32", "VOP1_VOP_DPP8", &[("VDST", 9), ("SRC0", 0xE9), ("VSRC0", 2), ("LANE_SEL_0", 2), ("LANE_SEL_1", 3), ("LANE_SEL_2", 0), ("LANE_SEL_3", 1), ("LANE_SEL_4", 6), ("LANE_SEL_5", 7), ("LANE_SEL_6", 4), ("LANE_SEL_7", 5)], None).unwrap()); + c.extend(dpp16(10, 0x161)); + c + }; + let psi = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; + for wave64 in [false, true] { + let mut code = reads(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }); + code.extend(encode("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 7), ("VSRC1", 8), ("VSRC2", 9), ("VSRC3", 10), ("DONE", 1), ("VM", 1)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let t = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let main = &t.hlsl[t.hlsl.rfind(" main(").expect("main")..]; + assert!(!main.contains("rla("), "wave64 {wave64}: a quad-local read through rla\n{main}"); + // four reads, each position of the quad from another one + assert_eq!(main.matches("QuadReadLaneAt(").count(), 16, "wave64 {wave64}\n{main}"); + let k = kernel::translate_pixel(&code, kernel::KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS"); + validate::validate(&k.dxil).expect("validate PS"); + let dis = validate::disassemble(&k.dxil).expect("disassemble PS"); + assert!(!dis.contains("dx.op.waveReadLaneAt") && !dis.contains("dx.op.quadOp"), "wave64 {wave64}: a wave read or quadOp\n{dis}"); + // (the module's CSE shares the reads of the one source register) + let n = dis.matches("call i32 @dx.op.quadReadLaneAt.i32(").count(); + assert!((4..=16).contains(&n), "wave64 {wave64}: {n} quad reads\n{dis}"); + } + // the same reads in a compute program: wave reads + let mut code = dpp16(7, 0xB1); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let t = translate(&code, &Options { wave64: false, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains("rla(v2, ") && !t.hlsl[t.hlsl.rfind(" main(").expect("main")..].contains("QuadReadLaneAt("), "{}", t.hlsl); +} + +/// `quad_reads_in_a_loop_ps` on the GPU, through both translators and as a wave32 and a wave64 +/// program: every pixel, those of the quads on the triangles' shared diagonal included, gets +/// its quad's values. +#[test] +fn gpu_ps_quad_reads_in_a_loop_see_helper_lanes() { + if !gpu_ready() { + return; + } + use crate::gpu::dxil::kernel::{self, KernelOptions}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + let psi = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let size = 32usize; + let fv = |x: usize, y: usize| (x as f32 + 0.5) + 64.0 * (y as f32 + 0.5); + let want = |x: usize, y: usize| -> [f32; 4] { + let (qx, qy) = (x & !1, y & !1); + let sum = fv(qx, qy) + fv(qx + 1, qy) + fv(qx, qy + 1) + fv(qx + 1, qy + 1); + [3.0 * sum, 3.0 * fv(x ^ 1, y ^ 1), 3.0, 3.0 * (fv(x, y ^ 1) + fv(x ^ 1, y))] + }; + for wave64 in [false, true] { + let code = quad_reads_in_a_loop_ps(wave64); + let t = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + let hlsl = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + let direct = kernel::translate_pixel(&code, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS").dxil; + for (form, ps) in [("HLSL", &hlsl), ("direct DXIL", &direct)] { + let px = runner::draw(&vs, ps, &layout, &quad, 8, &[], &[], size as u32, [9.0; 4]).unwrap(); + let bad: Vec<(usize, usize, [f32; 4], [f32; 4])> = + (0..size * size).map(|i| (i % size, i / size)).filter(|&(x, y)| px[y * size + x] != want(x, y)).map(|(x, y)| (x, y, px[y * size + x], want(x, y))).collect(); + let edge = bad.iter().filter(|b| b.0 >> 1 == b.1 >> 1).count(); + println!("{form}, wave64 {wave64}: {} of {} pixels wrong ({edge} in the diagonal's quads)", bad.len(), size * size); + assert!(bad.is_empty(), "{form}, wave64 {wave64}: {} pixels wrong ({edge} in the diagonal's quads), first (x, y, got, want) {:?}", bad.len(), &bad[..bad.len().min(4)]); + } + } +} + /// XCL image descriptor (T#, GFX10 layout): BASE_ADDRESS = SRV heap index, FORMAT, TYPE. fn tsharp(index: u32, format: u32, ty: u32) -> [u32; 8] { [index, format << 20, 0, ty << 28, 0, 0, 0, 0] From 070e2da63a119bd2b84c1515e58252f5c26ee6a6 Mon Sep 17 00:00:00 2001 From: emirduran707 Date: Tue, 24 Nov 2026 16:43:07 +0300 Subject: [PATCH 059/175] Recompiler: PS sample index and fixed-point position VGPRs get values A console PS with SPI_PS_INPUT_ENA bit 13 (ANCILLARY) or bit 15 (POS_FIXED_PT) found those VGPRs at 0: the start values covered only pos x/y/z/w, front face and sample coverage, and XclIn never declared SV_SampleIndex. A per-sample PS (MSAA resolve, sample-rate shading) read sample 0 on every sample and was not run per sample on the PC. The layout is Mesa's (src/amd/common/nir/ac_nir_lower_intrinsics_to_args.c): load_sample_id unpacks ancillary bits [11:8], load_pixel_coord unpacks pos_fixed_pt as two 16-bit halves (x low, y high). - ancillary: SV_SampleIndex is declared, and the VGPR starts at (index & 0xF) << 8, only when the input signature has system value 10; SV_SampleIndex makes the PC PS run per sample (D3D11.3 functional spec, 16.3: requesting sampleIndex forces sample-frequency execution), so a PS that does not ask for it keeps per-pixel rate. - the render-target array index (ancillary [28:16]) stays 0: in the PS SV_RenderTargetArrayIndex links to the previous stage's output (spec 24.4: "must be at the same Element/component"), which the translated VS / GS never write (ranked() drops system values). - POS_FIXED_PT starts from the integer SV_Position coordinates. (amd-dev: the test's PsInterface takes early_depth: false, a field amd-dev has and main had not when the PR was written.) (cherry picked from commit 00e3c4a56a4dace9892180267e832cb57d62f505) Assisted-by: Claude Code (Claude Opus 5.5) Co-Authored-By: Claude Opus 5.5 (cherry picked from commit a4f67320beefb2bc9ae3de55aec77585594052a4) --- crates/xcl/src/gpu/recomp/emit.rs | 14 +++++++++++ crates/xcl/src/gpu/recomp/tests.rs | 40 ++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 7a67654a82..75d11f3bc4 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5533,6 +5533,15 @@ static uint xcl_cap = 1u << 16; if ps.input_ena >> 14 & 1 == 1 { h.push_str(" uint xcl_cov : SV_Coverage;\n"); } + // the ancillary VGPR's sample index (Mesa, ac_nir_lower_intrinsics_to_args.c: + // load_sample_id is ancillary bits [11:8]); SV_SampleIndex makes the PS run per + // sample, so only when the console's signature has it. Its render-target array + // index ([28:16]) stays 0: SV_RenderTargetArrayIndex links to an output of the + // stage before, which the translated VS / GS do not write + let si = ps.input_ena >> 13 & 1 == 1 && ps.inputs.iter().any(|e| e.system_value == 10); + if si { + h.push_str(" uint xcl_si : SV_SampleIndex;\n"); + } h.push_str("};\nstruct XclOut {\n"); for e in &ps.outputs { match e.system_value { @@ -5578,8 +5587,13 @@ static uint xcl_cap = 1u << 16; "asuint(xi.xcl_pos.w)" } else if Some(v) == sys(12) { "asuint(xi.xcl_ff ? 1.0f : 0.0f)" + } else if Some(v) == sys(13) && si { + "((xi.xcl_si & 0xFu) << 8)" } else if Some(v) == sys(14) { "xi.xcl_cov" + } else if Some(v) == sys(15) { + // POS_FIXED_PT: integer pixel x in [15:0], y in [31:16] (Mesa: load_pixel_coord) + "((uint)xi.xcl_pos.x & 0xFFFFu) | ((uint)xi.xcl_pos.y << 16)" } else { "0u" }; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 2e83245311..9c77f38bd0 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -9780,6 +9780,46 @@ fn ps_interp_p0_preserves_bits_and_p2_converts_to_float() { } } +/// The ancillary VGPR (SPI_PS_INPUT_ENA bit 13) holds the sample index in [11:8]; +/// POS_FIXED_PT (bit 15) the integer pixel x in [15:0] and y in [31:16]. Each starts from its +/// SV_ value, and SV_SampleIndex (which makes the PC PS run per sample) is declared only when +/// the console's input signature has it. +#[test] +fn ps_ancillary_and_pos_fixed_vgprs() { + use super::PsInterface; + let ps = |ena: u32, inputs: Vec, src: u64| { + let code = prog(&[ + ("V_BFE_U32", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + src), ("SRC1", 136), ("SRC2", 132)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 1), ("VSRC0", 3), ("DONE", 1), ("VM", 1)], None), + ]); + let psi = PsInterface { inputs, outputs: vec![el("SV_Target", 0, 64, 1, 0, 0xF)], input_ena: ena, attrs: None, early_depth: false }; + let pt = translate(&code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); + assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); + if super::dxc::location().is_ok() { + super::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + } + pt.hlsl + }; + // sample index (and render-target array index) in the ancillary VGPR v2 + let h = ps(0x2002, vec![el("SV_SampleIndex", 0, 10, 1, 0, 1)], 2); + assert!(h.contains("uint xcl_si : SV_SampleIndex;") && !h.contains("uint v2 = 0u;"), "{h}"); + assert!(h.contains("uint v2 = ((xi.xcl_si & 0xFu) << 8);"), "{h}"); + // SV_RenderTargetArrayIndex links to an output of the stage before, which the translated + // VS / GS do not write (`ranked` drops it): it stays undeclared, its bits 0 + let h = ps(0x2002, vec![el("SV_SampleIndex", 0, 10, 1, 0, 1), el("SV_RenderTargetArrayIndex", 0, 4, 1, 1, 1)], 2); + assert!(h.contains("uint v2 = ((xi.xcl_si & 0xFu) << 8);") && !h.contains("SV_RenderTargetArrayIndex"), "{h}"); + // the ancillary VGPR without either in the signature: no per-sample PS + let h = ps(0x2002, vec![], 2); + assert!(h.contains("uint v2 = 0u;") && !h.contains("SV_SampleIndex"), "{h}"); + // POS_FIXED_PT in v2, from SV_Position + let h = ps(0x8002, vec![], 2); + assert!(h.contains("uint v2 = ((uint)xi.xcl_pos.x & 0xFFFFu) | ((uint)xi.xcl_pos.y << 16);"), "{h}"); + // neither: the interface and start values are those of before + let h = ps(0x0302, vec![el("SV_Position", 0, 1, 3, 0, 0xF)], 2); + assert!(h.contains("struct XclIn {\n float4 xcl_pos : SV_Position;\n};\nstruct XclOut {\n uint4 t0 : SV_Target0;\n};\n"), "{h}"); + assert!(h.contains("uint v2 = asuint(xi.xcl_pos.x);") && h.contains("uint v3 = asuint(xi.xcl_pos.y);") && h.contains("uint v0 = 0u;"), "{h}"); +} + #[test] fn gpu_ds_swizzle_and_bpermute_zero_inactive_lanes() { let run_case = |wave64: bool, split_wave64: bool| { From 4877f811d48c0c2ca418bf13353b06ff5a60fd1b Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:18:14 +0100 Subject: [PATCH 060/175] D3D12.X: ambient finds the reflection resolves' image in its slot The reflection resolves (CS_TemporalResolve2_Opaque, CS_TemporalResolve1_Alpha) have several R32_UINT images bound, and the ambient pass picked the one whose size fit the dispatch best. In the runs of 2026-11-28 it clamped a 2048x512 R32_UINT image on two of eleven dispatches logged ("applied ReflectionResolve stand-in on 2048x512x1 fmt 42"), which is not the picture's reflections. VIctory-Neo (3aca295, REFLECTIONS) takes the reflections from root parameter 1's table at dword 128 (opaque) or 136 (transparent), the first of the two that holds a 2D image of their format. Do the same, with the image found by its format as before when neither slot holds one, and log which it was. The diffuse resolve's slot lookup is shared and keeps its 2D-only filters. Ported from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, bdc3f38, GPL-3.0-or-later). (cherry picked from commit cc626f0883e6f7c95e5535bf73a707f507cfc470) --- crates/xcl/src/hle/d3d12x/ambient.rs | 107 ++++++++++++++++++--------- 1 file changed, 73 insertions(+), 34 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 56cc0adc1a..46b1115fc6 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -23,6 +23,8 @@ //! //! Ported in part from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later; //! THIRD_PARTY.md): the cells, their slow mean, and the estimate made in space (2026-11-28). +//! Ported in part from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later): +//! the slots the reflections' resolves write (2026-11-29). //! //! With the depth the resolve reads, the estimate is made in space rather than on the screen: //! each cell is placed where it is seen (`LIGHT_PLACE_HLSL`), the cells' light is @@ -213,6 +215,12 @@ pub(super) enum PassRole { Radiance, } +/// Where the reflections' resolves write them: root parameter and dword of its table, the first +/// of these that holds a 2D image of their format (R32_UINT holding R9G9B9E5; the opaque +/// surfaces' resolve has it at the first, the transparent ones' at the second). From VIctory-Neo +/// (`REFLECTIONS`, 3aca295). +const REFLECTION_SLOTS: [(usize, usize); 2] = [(1, 128), (1, 136)]; + fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool { if needle.is_empty() || haystack.len() < needle.len() { return false; @@ -1847,51 +1855,74 @@ unsafe fn find_dispatch_views( } } let mut uav = uav_hit.map(|(_, r, f, w, h, d)| (r, f, w, h, d)); + // A program's own slots: the view at `dword` of root parameter `param`'s table. Where a + // program has several images of one format and size, a guess by format alone can take the + // wrong one. + let pinned = |param: usize, dword: usize| -> Option<(ViewEntry, D3D12_RESOURCE_DESC)> { + let Some(&Param::Table { at }) = layout.params.get(param) else { return None }; + let t = word(at as usize).filter(|&t| t != 0)?; + let addr = u.base().checked_add(t as usize)?.checked_add(4 * dword)?; + if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { + return None; + } + let (w0, w3) = ((addr as *const u32).read_unaligned(), ((addr + 12) as *const u32).read_unaligned()); + if (w3 >> 28) < 8 { + return None; + } + // (only views of the light's and of depth formats are noted here: any other picture + // is named by the heap's own record of its index, read in a format of its resource's) + let noted = vs.by_addr.get(&addr).or_else(|| (w0 != 0).then(|| vs.by_idx.get(&w0)).flatten()).copied(); + let named = || match super::console_heap::named_by_index(w0) { + 0 | super::console_heap::GONE => None, + res => Some(ViewEntry { res, fmt: 0, is_uav: false }), + }; + let mut ve = noted.or_else(named)?; + let ptr = ve.res as *mut c_void; + let rd = ID3D12Resource::from_raw_borrowed(&ptr)?.GetDesc(); + if ve.fmt == 0 { + ve.fmt = match rd.Format.0 { + 39..=41 => 41, + 19..=21 => 21, + 44..=46 => 46, + 53 | 55 | 56 => 56, + f => f, + }; + } + let flat = rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && rd.DepthOrArraySize == 1; + (rd.SampleDesc.Count == 1 && (flat || rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D)).then_some((ve, rd)) + }; + let flat = |rd: &D3D12_RESOURCE_DESC| rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D; + if role == PassRole::ReflectionResolve { + // The resolves' own slots (`REFLECTION_SLOTS`): the first that holds a picture of the + // reflections' format, else the one found by its format. + let held = REFLECTION_SLOTS + .iter() + .find_map(|&(param, dword)| pinned(param, dword).filter(|(ve, rd)| ve.is_uav && ve.fmt == 42 && flat(rd))); + if let Some((ve, rd)) = &held { + uav = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height, 1)); + } + static SLOTS: AtomicU64 = AtomicU64::new(0); + if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: the reflections' resolve writes {} ({:?})", + if held.is_some() { "the one in its slot" } else { "the one found by its format" }, + uav.map(|(r, f, w, h, _)| (r, f, w, h)) + ); + } + } if role == PassRole::TemporalResolve && !want_3d { // The resolve's own slots: its // light at dword 176 of root parameter 1's table, the depth it reads at dword 464 of // parameter 0's. The program has several R32_UINT outputs of the picture's size and reads // other pictures of it besides the depth: a guess by format alone can take the wrong one. - let pinned = |param: usize, dword: usize| -> Option<(ViewEntry, D3D12_RESOURCE_DESC)> { - let Some(&Param::Table { at }) = layout.params.get(param) else { return None }; - let t = word(at as usize).filter(|&t| t != 0)?; - let addr = u.base().checked_add(t as usize)?.checked_add(4 * dword)?; - if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { - return None; - } - let (w0, w3) = ((addr as *const u32).read_unaligned(), ((addr + 12) as *const u32).read_unaligned()); - if (w3 >> 28) < 8 { - return None; - } - // (only views of the light's and of depth formats are noted here: any other picture - // is named by the heap's own record of its index, read in a format of its resource's) - let noted = vs.by_addr.get(&addr).or_else(|| (w0 != 0).then(|| vs.by_idx.get(&w0)).flatten()).copied(); - let named = || match super::console_heap::named_by_index(w0) { - 0 | super::console_heap::GONE => None, - res => Some(ViewEntry { res, fmt: 0, is_uav: false }), - }; - let mut ve = noted.or_else(named)?; - let ptr = ve.res as *mut c_void; - let rd = ID3D12Resource::from_raw_borrowed(&ptr)?.GetDesc(); - if ve.fmt == 0 { - ve.fmt = match rd.Format.0 { - 39..=41 => 41, - 19..=21 => 21, - 44..=46 => 46, - 53 | 55 | 56 => 56, - f => f, - }; - } - (rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && rd.DepthOrArraySize == 1 && rd.SampleDesc.Count == 1).then_some((ve, rd)) - }; - let light = pinned(1, 176).filter(|(ve, _)| ve.is_uav && ve.fmt == 42); + let light = pinned(1, 176).filter(|(ve, rd)| ve.is_uav && ve.fmt == 42 && flat(rd)); if let Some((ve, rd)) = &light { uav = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height, 1)); } // (the depth is the picture's size, or it is another picture: none then, and the fill is // made on the screen) let same_size = |w: u64, h: u32| uav.is_some_and(|(_, _, uw, uh, _)| w == uw as u64 && h == uh); - let depth = pinned(0, 464).filter(|(ve, rd)| !ve.is_uav && matches!(ve.fmt, 21 | 41 | 46 | 54 | 56) && same_size(rd.Width, rd.Height)); + let depth = pinned(0, 464).filter(|(ve, rd)| !ve.is_uav && matches!(ve.fmt, 21 | 41 | 46 | 54 | 56) && flat(rd) && same_size(rd.Width, rd.Height)); let found = depth_hit.filter(|&(_, f, w, h)| matches!(f, 20 | 21 | 39 | 40 | 41 | 46 | 55 | 56) && same_size(w as u64, h)); static SLOTS: AtomicU64 = AtomicU64::new(0); if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { @@ -2217,6 +2248,14 @@ mod tests { assert_eq!(classify_cs(b"ILDN\0CS_CullInstances\0"), None); } + /// The reflections' slots are whole descriptors (8 dwords) of the table of root parameter 1, + /// the opaque surfaces' first, as the diffuse resolve's light is (dword 176). + #[test] + fn the_reflections_are_looked_for_in_whole_descriptor_slots_opaque_first() { + assert_eq!(REFLECTION_SLOTS, [(1, 128), (1, 136)]); + assert!(REFLECTION_SLOTS.iter().all(|&(param, dword)| param == 1 && dword % 8 == 0 && dword != 176)); + } + #[test] fn sky_dome_filter_rejects_r11g11b10_and_wrong_sizes() { let mut rd = D3D12_RESOURCE_DESC { From 2238e444425b775d1ff30cd968820b0741dbb65a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:22:14 +0100 Subject: [PATCH 061/175] D3D12.X: ambient holds resolved reflections to the light around Indoors the reflections CS_TemporalResolve2_Opaque and CS_TemporalResolve1_Alpha resolve were capped at XCL_AMBIENT_REFLECT (0.5) times the larger of the sky's level (clamped to 0.65) and the 64x36 cells under them. With rays forced to miss they come out with the sky's light, and in daylight that cap reaches 0.5 x 0.65 = 0.33 while a room's light is of 0.01 to 0.1 (VIctory-Neo's capture of a cutscene frame), so eyes, glossy floors and glass glowed. VIctory-Neo (3aca295, "hold"; from Vice-Tay #99 and avatarmanz/VIctory-7900XTX #314) holds every texel of the resolved image to n times the light around: the ambient estimate at the four of the 160x90 gathered points about the texel, with a fifth of the room's slow mean, hue kept. Neo's launcher turns it on at 1 (cfecf35): in the first house of a shared save a terrarium's glass, a table top, a patch of floor, a microwave door and a wall clock no longer show white; outside only a glass door is darker. Port it as a second bound in the existing reflection cap: the cap is now the smaller of the old one and XCL_AMBIENT_REFLECT_HOLD times the light around (the cells under the texel while no points are gathered; no hold before any frame's light is kept), so reflections are never brighter than before. On by default at 1.25: XCL's estimate is XCL_AMBIENT_FRAME (0.8) of what the surfaces send out, so this is Neo's 1. XCL_AMBIENT_REFLECT_HOLD=0 turns it off. A log line counts the holds. Tests: the switch's parsing and default, the point layout the shader reads, and a GPU run of the program on an 8x8 image (held to the points, to the cells without points, and to the sky's cap alone with the hold off; hue kept, dim texels left). Ported from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, bdc3f38, GPL-3.0-or-later). (cherry picked from commit 6eb60e9fca61b9b90afb0023f8ea36473a9b79a3) --- crates/xcl/src/hle/d3d12x/ambient.rs | 346 ++++++++++++++++++++++++++- 1 file changed, 336 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 46b1115fc6..594c07d8c9 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -12,7 +12,8 @@ //! //! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, //! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`, `XCL_AMBIENT_FRAME`, -//! `XCL_AMBIENT_KEEP`, `XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`, `XCL_AMBIENT_SPACE`, `XCL_AMBIENT_SPLIT`. +//! `XCL_AMBIENT_KEEP`, `XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`, `XCL_AMBIENT_SPACE`, `XCL_AMBIENT_SPLIT`, +//! `XCL_AMBIENT_REFLECT_HOLD`. //! //! The sky alone leaves a night scene black wherever no lamp reaches. So the fill is also raised //! to an estimate taken from the frame itself: the light the visible surfaces send out, which the @@ -24,7 +25,8 @@ //! Ported in part from Vice-Tay (https://github.com/TaynanGT/Vice-Tay, GPL-3.0-or-later; //! THIRD_PARTY.md): the cells, their slow mean, and the estimate made in space (2026-11-28). //! Ported in part from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later): -//! the slots the reflections' resolves write (2026-11-29). +//! the slots the reflections' resolves write, and their hold to the light around (its `hold`, +//! itself from Vice-Tay #99 and avatarmanz/VIctory-7900XTX #314) (2026-11-29). //! //! With the depth the resolve reads, the estimate is made in space rather than on the screen: //! each cell is placed where it is seen (`LIGHT_PLACE_HLSL`), the cells' light is @@ -37,6 +39,13 @@ //! for `XCL_AMBIENT_SKY` of itself (0.35 unless given), and the air's //! scattered light (`XCL_AMBIENT_AIR`, 1.5 unless given, 0: off) is held to that multiple of the //! light of the room and of the surface seen behind it. +//! +//! The reflections the title resolves (`CS_TemporalResolve2_Opaque`, `CS_TemporalResolve1_Alpha`) +//! are held to `XCL_AMBIENT_REFLECT` times the sky's level or the cells under them, and to +//! `XCL_AMBIENT_REFLECT_HOLD` times the light around besides (1.25 unless given, 0: off): the +//! estimate at the four gathered points about the texel, a fifth of it the slow mean (the cells +//! while no points are gathered), hue kept. Indoors the sky's level is far above the room's, and +//! eyes, glossy floors and glass glowed with it. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; @@ -75,6 +84,8 @@ struct Config { most: f32, /// the share of the sky's level every texel gets whatever the frame's light sky: f32, + /// the resolved reflections are held to this many times the light around (0: not held) + reflect_hold: f32, } impl Default for Config { @@ -91,6 +102,9 @@ impl Default for Config { frame: 0.8, most: 2.0, sky: 0.35, + // VIctory-Neo's 1 of what the surfaces around send out: the estimate is 0.8 of it + // (`frame`) + reflect_hold: 1.25, } } } @@ -107,11 +121,11 @@ fn parse_mode(raw: Option<&str>) -> Mode { } fn env_f32(name: &str, default: f32, lo: f32, hi: f32) -> f32 { - std::env::var(name) - .ok() - .and_then(|v| v.trim().parse::().ok()) - .filter(|v| v.is_finite()) - .map_or(default, |v| v.clamp(lo, hi)) + parse_f32(std::env::var(name).ok().as_deref(), default, lo, hi) +} + +fn parse_f32(raw: Option<&str>, default: f32, lo: f32, hi: f32) -> f32 { + raw.and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()).map_or(default, |v| v.clamp(lo, hi)) } fn config() -> &'static Config { @@ -131,6 +145,7 @@ fn config() -> &'static Config { frame: env_f32("XCL_AMBIENT_FRAME", def.frame, 0.0, 4.0), most: env_f32("XCL_AMBIENT_MOST", def.most, 1.0, 16.0), sky: env_f32("XCL_AMBIENT_SKY", def.sky, 0.0, 1.0), + reflect_hold: env_f32("XCL_AMBIENT_REFLECT_HOLD", def.reflect_hold, 0.0, 16.0), } }) } @@ -1181,7 +1196,8 @@ void main(uint3 tid : SV_DispatchThreadID) { /// Hue-preserving reflection luminance cap for `CS_TemporalResolve2_Opaque` / /// `CS_TemporalResolve1_Alpha` (`R9G9B9E5` packed in `R32_UINT`), with optional GPU indirect-args -/// zero-group gating so empty indirect dispatches leave the texture untouched. +/// zero-group gating so empty indirect dispatches leave the texture untouched: `reflect_scale` +/// times the sky's level or the cells', and `hold` times the light around (0: not held). const REFLECT_CLAMP_R9_HLSL: &str = r#" ByteAddressBuffer indirect_args : register(t0); RWTexture2D out_uav : register(u0); @@ -1193,7 +1209,7 @@ cbuffer C : register(b0) { uint indirect_off; uint _u4; float reflect_scale; - float _p6; + float hold; float _p7; }; float3 unpack_r9g9b9e5(uint v) { @@ -1229,6 +1245,23 @@ float3 frame_light(uint2 tid) { float3 found = lerp(sum, mean.rgb, 0.2); return all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); } +// The light gathered at the four of the 160x90 points about this texel (each colour's mean in +// the fourth part of its float4, from `sky_level[4610]` on); none while no points are gathered. +float3 points_light(uint2 tid) { + float2 g = (float2(tid) + 0.5) / float2(max(width, 1u), max(height, 1u)) * float2(160.0, 90.0) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float3 sum = float3(0.0, 0.0, 0.0); + [unroll] + for (uint k = 0u; k < 4u; ++k) { + int2 q = clamp(g0 + int2(int(k & 1u), int(k >> 1)), int2(0, 0), int2(159, 89)); + float wx = (k & 1u) != 0u ? f.x : 1.0 - f.x; + float wy = (k >> 1) != 0u ? f.y : 1.0 - f.y; + uint at0 = 4610u + uint(q.y * 160 + q.x) * 3u; + sum += wx * wy * float3(sky_level[at0].w, sky_level[at0 + 1u].w, sky_level[at0 + 2u].w); + } + return all(isfinite(sum)) ? max(sum, 0.0) : float3(0.0, 0.0, 0.0); +} [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { if (indirect_flag != 0u && any(indirect_args.Load3(indirect_off) == 0u)) return; @@ -1241,6 +1274,15 @@ void main(uint3 tid : SV_DispatchThreadID) { float3 amb = max(clamp(sky_level[0].rgb, 0.0, 0.65), frame_light(tid.xy)); float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.005); float cap_lum = max(amb_lum * reflect_scale, 0.005); + // And no brighter than `hold` times the light around: the four points about the texel, a + // fifth of it the slow mean (the cells under it while no points are gathered). Indoors the + // sky's level above is far brighter than the room: eyes, glossy floors and glass glowed. + float4 mean = sky_level[1]; + if (hold > 0.0 && mean.a > 0.0 && all(isfinite(mean.rgb))) { + float3 around = points_light(tid.xy); + around = dot(around, float3(0.2126, 0.7152, 0.0722)) > 0.0 ? lerp(around, mean.rgb, 0.2) : frame_light(tid.xy); + cap_lum = min(cap_lum, hold * dot(around, float3(0.2126, 0.7152, 0.0722))); + } float cur_lum = dot(cur, float3(0.2126, 0.7152, 0.0722)); if (cur_lum > cap_lum) { cur *= (cap_lum / max(cur_lum, 1e-6)); @@ -2135,7 +2177,7 @@ pub(super) unsafe fn after_compute_dispatch( ), PassRole::ReflectionResolve => ( ad.reflect_r9_pso.as_raw(), - [w, h, indirect_flag, 0, 0, cfg.reflect.to_bits(), 0, 0], + [w, h, indirect_flag, 0, 0, cfg.reflect.to_bits(), cfg.reflect_hold.to_bits(), 0], (w.div_ceil(8), h.div_ceil(8), 1), ), PassRole::InscatteringVolume => ( @@ -2200,6 +2242,16 @@ pub(super) unsafe fn after_compute_dispatch( return; } list_x::restore_after_internal_pass(list, false, true); + if role == PassRole::ReflectionResolve && cfg.reflect_hold > 0.0 { + static HELD: AtomicU64 = AtomicU64::new(0); + let n = HELD.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: ambient: reflections held to {}x the light around after their resolve, {w}x{h} ({n} so far)", + cfg.reflect_hold + ); + } + } static LOGGED: AtomicU64 = AtomicU64::new(0); if LOGGED.fetch_add(1, Ordering::Relaxed) < 6 { @@ -2452,6 +2504,280 @@ mod tests { note_descriptor(cpu_slot_b, 0, 0, 0, 0, false); } + /// The hold is on at VIctory-Neo's strength unless the switch says 0; another value is taken + /// within 0 to 16, a word that is not a number leaves the default. + #[test] + fn the_reflection_hold_is_on_unless_switched_off() { + assert_eq!(Config::default().reflect_hold, 1.25); + assert!((Config::default().reflect_hold * Config::default().frame - 1.0).abs() < 1e-6, "Neo's 1 of what the surfaces send out"); + assert_eq!(parse_f32(None, 1.25, 0.0, 16.0), 1.25); + assert_eq!(parse_f32(Some(" 0 "), 1.25, 0.0, 16.0), 0.0, "0: not held"); + assert_eq!(parse_f32(Some("2.5"), 1.25, 0.0, 16.0), 2.5); + assert_eq!(parse_f32(Some("99"), 1.25, 0.0, 16.0), 16.0); + assert_eq!(parse_f32(Some("-1"), 1.25, 0.0, 16.0), 0.0); + assert_eq!(parse_f32(Some("off"), 1.25, 0.0, 16.0), 1.25); + assert_eq!(parse_f32(Some("nan"), 1.25, 0.0, 16.0), 1.25); + // the points the hold reads are where the gather writes them + let point_at = 2 + 2 * FRAME_CELLS.0 * FRAME_CELLS.1; + assert!(REFLECT_CLAMP_R9_HLSL.contains(&format!("{point_at}u + uint(q.y * {} + q.x) * 3u", GATHER_POINTS.0))); + assert!(REFLECT_CLAMP_R9_HLSL.contains(&format!("float2({}.0, {}.0)", GATHER_POINTS.0, GATHER_POINTS.1))); + } + + /// R9G9B9E5 as the programs pack it. + fn pack_r9(c: [f32; 3]) -> u32 { + let c = c.map(|v| v.clamp(0.0, 65408.0)); + let top = c[0].max(c[1]).max(c[2]); + let mut e = (top.max(1e-9).log2().floor() as i32 + 16).clamp(0, 31); + let mut scale = 2f32.powi(24 - e); + if top * scale >= 511.5 { + e = (e + 1).min(31); + scale = 2f32.powi(24 - e); + } + let m = c.map(|v| ((v * scale + 0.5) as u32).min(511)); + m[0] | m[1] << 9 | m[2] << 18 | (e as u32) << 27 + } + + fn unpack_r9(v: u32) -> [f32; 3] { + let s = 2f32.powi((v >> 27) as i32 - 24); + [(v & 511) as f32 * s, ((v >> 9) & 511) as f32 * s, ((v >> 18) & 511) as f32 * s] + } + + fn luma(c: [f32; 3]) -> f32 { + 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] + } + + /// One dispatch of an ambient program (`pick`) over an 8x8 R32_UINT image holding `texels`, + /// with the level buffer holding `level` and the root constants `consts`; the image after it. + /// `t0` is the indirect arguments' raw buffer (`raw_t0`) or a depth. None (skipped) without a + /// D3D12 device. + unsafe fn run_on_r9_image( + pick: impl Fn(&AmbientDevice) -> &ID3D12PipelineState, + raw_t0: bool, + consts: [u32; 8], + texels: &[u32; 64], + level: &[[f32; 4]], + ) -> Option<[u32; 64]> { + assert_eq!(level.len(), LEVEL_ELEMENTS as usize); + let mut dev: Option = None; + if D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let dev = dev.unwrap(); + let dev_raw = dev.as_raw(); + real::adopt(dev_raw, real::Kind::Device); + let ad = build_device(&dev).expect("build_device must succeed"); + + type CreateResFn = unsafe extern "system" fn( + *mut c_void, + *const D3D12_HEAP_PROPERTIES, + D3D12_HEAP_FLAGS, + *const D3D12_RESOURCE_DESC, + D3D12_RESOURCE_STATES, + *const D3D12_CLEAR_VALUE, + *const c_void, + *mut *mut c_void, + ) -> i32; + let create_res: CreateResFn = std::mem::transmute(real::orig_fn(dev_raw, 27)); + let make = |ty: D3D12_HEAP_TYPE, rd: &D3D12_RESOURCE_DESC, init: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let hp = D3D12_HEAP_PROPERTIES { Type: ty, ..Default::default() }; + let mut raw = std::ptr::null_mut(); + let hr = create_res(dev_raw, &hp, D3D12_HEAP_FLAG_NONE, rd, init, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const c_void, &mut raw); + assert!(hr >= 0 && !raw.is_null(), "CreateCommittedResource: {hr:#x}"); + ID3D12Resource::from_raw(raw) + }; + let buffer = |bytes: u64| 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, + ..Default::default() + }; + const PITCH: usize = 256; + let level_bytes = LEVEL_ELEMENTS as usize * 16; + let image_at = level_bytes.next_multiple_of(512); + let upload = make(D3D12_HEAP_TYPE_UPLOAD, &buffer((image_at + 8 * PITCH) as u64), D3D12_RESOURCE_STATE_GENERIC_READ); + let readback = make(D3D12_HEAP_TYPE_READBACK, &buffer((8 * PITCH) as u64), D3D12_RESOURCE_STATE_COPY_DEST); + let image = make( + D3D12_HEAP_TYPE_DEFAULT, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::copy_nonoverlapping(level.as_ptr() as *const u8, p as *mut u8, level_bytes); + for y in 0..8 { + std::ptr::copy_nonoverlapping(texels[y * 8..].as_ptr(), (p as *mut u8).add(image_at + y * PITCH) as *mut u32, 8); + } + upload.Unmap(0, None); + + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let list_raw = list.as_raw(); + real::adopt(list_raw, real::Kind::CommandList); + list_x::on_create(list_raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + let copy_buffer: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = std::mem::transmute(real::orig_fn(list_raw, 15)); + copy_buffer(list_raw, ad.sky_level.as_raw(), 0, upload.as_raw(), 0, level_bytes as u64); + list_x::transition(list_raw, ad.sky_level.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + let footprint = |offset: usize| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset as u64, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R32_UINT, Width: 8, Height: 8, Depth: 1, RowPitch: PITCH as u32 }, + }; + let in_image = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&image), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let in_upload = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(image_at) }, + }; + let in_readback = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint(0) }, + }; + list_x::pc_copy_texture_region(list_raw, &in_image, 0, 0, 0, &in_upload, std::ptr::null()); + list_x::transition(list_raw, image.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + let (cpu0, gpu0) = ad.alloc_group(); + let inc = ad.inc as u64; + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + let (t0, t0_view) = if raw_t0 { + ( + ad.dummy_indirect.as_raw(), + D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { FirstElement: 0, NumElements: 4, StructureByteStride: 0, Flags: D3D12_BUFFER_SRV_FLAG_RAW }, + }, + }, + ) + } else { + ( + ad.dummy_depth.as_raw(), + D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() } }, + }, + ) + }; + let image_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 } }, + }; + let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_ELEMENTS, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, t0, &t0_view, cpu0 as usize); + create_uav(dev_raw, image.as_raw(), std::ptr::null_mut(), &image_uav, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list_raw, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list_raw, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list_raw, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list_raw, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list_raw, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list_raw, 14)); + set_heaps(list_raw, 1, &heap_raw); + set_cs_rs(list_raw, ad.rs.as_raw()); + set_pso(list_raw, pick(&ad).as_raw()); + set_cs_consts(list_raw, 0, 8, consts.as_ptr(), 0); + set_cs_table(list_raw, 1, gpu0); + set_cs_table(list_raw, 2, gpu0 + inc); + dispatch(list_raw, 1, 1, 1); + list_x::transition(list_raw, image.as_raw() as usize, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_x::pc_copy_texture_region(list_raw, &in_readback, 0, 0, 0, &in_image, std::ptr::null()); + list.Close().unwrap(); + + let cl: ID3D12CommandList = list.cast().unwrap(); + q.ExecuteCommandLists(&[Some(cl)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let ev = windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap(); + q.Signal(&fence, 1).unwrap(); + fence.SetEventOnCompletion(1, ev).unwrap(); + windows::Win32::System::Threading::WaitForSingleObject(ev, 5000); + let _ = windows::Win32::Foundation::CloseHandle(ev); + assert_eq!(fence.GetCompletedValue(), 1, "the ambient program must complete (device removed: {:?})", dev.GetDeviceRemovedReason()); + + let mut out = [0u32; 64]; + let mut r = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut r)).unwrap(); + for y in 0..8 { + std::ptr::copy_nonoverlapping((r as *const u8).add(y * PITCH) as *const u32, out[y * 8..].as_mut_ptr(), 8); + } + readback.Unmap(0, None); + Some(out) + } + + /// A reflection far brighter than the room is held to `hold` times the light around (the + /// four gathered points about it, a fifth of it the slow mean), its hue kept; a dim one is + /// left as it was. With no points gathered the cells under it stand for them, and with the + /// hold off the sky's cap alone holds it. + #[test] + fn reflections_are_held_to_the_light_around_on_gpu() { + let bright = pack_r9([4.0, 2.0, 1.0]); + let dim = pack_r9([0.05, 0.05, 0.05]); + let mut texels = [dim; 64]; + texels[..32].fill(bright); + let mut level = vec![[0.0f32; 4]; LEVEL_ELEMENTS as usize]; + // the sky's level, the cells' slow mean, the cells, and the points (each colour's mean) + level[0] = [0.6, 0.6, 0.6, 0.6]; + level[1] = [0.05, 0.05, 0.05, 1.0]; + let cells = (FRAME_CELLS.0 * FRAME_CELLS.1) as usize; + level[2..2 + cells].fill([0.05, 0.05, 0.05, 1.0]); + let gathered = |level: &mut [[f32; 4]], light: f32| level[2 + 2 * cells..].fill([0.0, 0.0, 0.0, light]); + gathered(&mut level, 0.1); + let consts = |hold: f32| [8, 8, 0, 0, 0, 0.5f32.to_bits(), hold.to_bits(), 0]; + let run = |hold: f32, level: &[[f32; 4]]| unsafe { run_on_r9_image(|ad| &ad.reflect_r9_pso, true, consts(hold), &texels, level) }; + let check = |out: &[u32; 64], bright_lum: f32| { + let (b, d) = (unpack_r9(out[0]), unpack_r9(out[63])); + assert!((luma(b) - bright_lum).abs() < 0.02 * bright_lum, "bright reflection {b:?}, its light {} for {bright_lum}", luma(b)); + assert!((b[0] / b[1] - 2.0).abs() < 0.05 && (b[1] / b[2] - 2.0).abs() < 0.05, "hue kept: {b:?}"); + assert!((luma(d) - 0.05).abs() < 0.001, "dim reflection left: {d:?}"); + assert!(out[..32].iter().all(|&v| v == out[0]) && out[32..].iter().all(|&v| v == out[63])); + }; + let Some(held) = run(1.25, &level) else { return }; + // 1.25 x (0.1 at the points, a fifth of it the mean of 0.05) + check(&held, 1.25 * 0.09); + let Some(sky_only) = run(0.0, &level) else { return }; + // XCL_AMBIENT_REFLECT 0.5 x the sky's 0.6 + check(&sky_only, 0.5 * 0.6); + gathered(&mut level, 0.0); + let Some(by_cells) = run(1.25, &level) else { return }; + // no points: 1.25 x the cells under it (0.05, a fifth of it the mean of 0.05) + check(&by_cells, 1.25 * 0.05); + } + #[test] fn scan_cbv_indices_resolves_each_64k_mirror_page_independently() { const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; From 89680f2ca9d0db289e8f33421be0fad91d9a44bf Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:25:13 +0100 Subject: [PATCH 062/175] D3D12.X: ambient bounds the light of transparent surfaces and particles The title lights its transparent surfaces and particles from a volume before the eye (32x16x64 in VIctory-Neo's notes, a mean and a direction a cell) that rays of its own fill: CS_GatherAlphaVBuffer, CS_ShadeAlpha, then a variance and a spatial filter. With rays that find nothing they find the sky from everywhere, and the dust in a room's air is lit as under the open sky: white specks all over the picture. XCL had no pass for it. VIctory-Neo (a6e85c6, VICTORY_AMBIENT_ALPHA) bounds that volume right after CS_SpatialFilterAlpha, the last program that writes it, with the pass that bounds the air's light, and found the volume at dword 24 of root parameter 1's table (R11G11B10_FLOAT; the direction is at dword 16). Neo's launcher turns it on at 4 (cfecf35); flipped in one view, the specks are there without it and gone with it, at 1 and at 4, and outdoors the picture is the same. Port it: a new AlphaLight role recognised by the program's name like the others, its volume taken from that slot only (a 3D R11G11B10_FLOAT UAV; no guess by format, which could take the direction's volume), held by AIR_CAP_HLSL to XCL_AMBIENT_ALPHA times the light around. On by default at 5: XCL's estimate is 0.8 of what the surfaces send out, so this is Neo's 4. XCL_AMBIENT_ALPHA=0 leaves the title's light. Log lines say whether the slot held the volume and count the bounds. Ported from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, bdc3f38, GPL-3.0-or-later). (cherry picked from commit f45034f9667823cee35b65916f8a71dd89e3163e) --- crates/xcl/src/hle/d3d12x/ambient.rs | 88 ++++++++++++++++++++++++++-- 1 file changed, 82 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 594c07d8c9..046bf61e08 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -13,7 +13,7 @@ //! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, //! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`, `XCL_AMBIENT_FRAME`, //! `XCL_AMBIENT_KEEP`, `XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`, `XCL_AMBIENT_SPACE`, `XCL_AMBIENT_SPLIT`, -//! `XCL_AMBIENT_REFLECT_HOLD`. +//! `XCL_AMBIENT_REFLECT_HOLD`, `XCL_AMBIENT_ALPHA`. //! //! The sky alone leaves a night scene black wherever no lamp reaches. So the fill is also raised //! to an estimate taken from the frame itself: the light the visible surfaces send out, which the @@ -26,7 +26,8 @@ //! THIRD_PARTY.md): the cells, their slow mean, and the estimate made in space (2026-11-28). //! Ported in part from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later): //! the slots the reflections' resolves write, and their hold to the light around (its `hold`, -//! itself from Vice-Tay #99 and avatarmanz/VIctory-7900XTX #314) (2026-11-29). +//! itself from Vice-Tay #99 and avatarmanz/VIctory-7900XTX #314), and the bound of the +//! transparent surfaces' light (its `Role::Alpha`, `ALPHA`) (2026-11-29). //! //! With the depth the resolve reads, the estimate is made in space rather than on the screen: //! each cell is placed where it is seen (`LIGHT_PLACE_HLSL`), the cells' light is @@ -46,6 +47,11 @@ //! estimate at the four gathered points about the texel, a fifth of it the slow mean (the cells //! while no points are gathered), hue kept. Indoors the sky's level is far above the room's, and //! eyes, glossy floors and glass glowed with it. +//! +//! Transparent surfaces and particles take their light from a volume before the eye that the +//! title's rays fill (`CS_SpatialFilterAlpha` writes it last): with rays that find nothing it holds +//! the sky's light everywhere, and the dust of a room shows as white specks. It is held as the +//! air's is, to `XCL_AMBIENT_ALPHA` times the light around (5 unless given, 0: off). use std::collections::{HashMap, HashSet}; use std::ffi::c_void; @@ -86,6 +92,9 @@ struct Config { sky: f32, /// the resolved reflections are held to this many times the light around (0: not held) reflect_hold: f32, + /// the light of transparent surfaces and particles is held to this many times the light + /// around (0: as the title has it) + alpha: f32, } impl Default for Config { @@ -105,6 +114,8 @@ impl Default for Config { // VIctory-Neo's 1 of what the surfaces around send out: the estimate is 0.8 of it // (`frame`) reflect_hold: 1.25, + // VIctory-Neo's 4, as `reflect_hold` + alpha: 5.0, } } } @@ -146,6 +157,7 @@ fn config() -> &'static Config { most: env_f32("XCL_AMBIENT_MOST", def.most, 1.0, 16.0), sky: env_f32("XCL_AMBIENT_SKY", def.sky, 0.0, 1.0), reflect_hold: env_f32("XCL_AMBIENT_REFLECT_HOLD", def.reflect_hold, 0.0, 16.0), + alpha: env_f32("XCL_AMBIENT_ALPHA", def.alpha, 0.0, 16.0), } }) } @@ -228,6 +240,9 @@ pub(super) enum PassRole { InscatteringVolume, /// keeps the light visible surfaces send out (`CS_CacheScreenSpaceRadiance`) Radiance, + /// filters the light of transparent surfaces and particles, a 3D volume before the eye + /// (`CS_SpatialFilterAlpha`, the last program that writes it) + AlphaLight, } /// Where the reflections' resolves write them: root parameter and dword of its table, the first @@ -236,6 +251,11 @@ pub(super) enum PassRole { /// (`REFLECTIONS`, 3aca295). const REFLECTION_SLOTS: [(usize, usize); 2] = [(1, 128), (1, 136)]; +/// Where `CS_SpatialFilterAlpha` writes the light of transparent surfaces (a volume of +/// R11G11B10_FLOAT; its direction goes to dword 16), as `REFLECTION_SLOTS`. From VIctory-Neo +/// (`ALPHA`, a6e85c6). +const ALPHA_SLOT: (usize, usize) = (1, 24); + fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool { if needle.is_empty() || haystack.len() < needle.len() { return false; @@ -264,6 +284,8 @@ fn classify_cs(blob: &[u8]) -> Option { Some(PassRole::InscatteringVolume) } else if contains_ascii_ci(blob, b"CS_CacheScreenSpaceRadiance") { Some(PassRole::Radiance) + } else if contains_ascii_ci(blob, b"CS_SpatialFilterAlpha") { + Some(PassRole::AlphaLight) } else { None } @@ -1295,7 +1317,8 @@ void main(uint3 tid : SV_DispatchThreadID) { /// `air_scale` times the light around – of the room as the last seconds showed it, and of the /// surface seen in this direction (towards a window the air outside may be as bright as the sky /// is); what is brighter is scaled down with its colour kept. Before any -/// light is kept or gathered, the sky's level stands for it. +/// light is kept or gathered, the sky's level stands for it. The light of transparent surfaces +/// after `CS_SpatialFilterAlpha` is held the same way (`air_scale`: `XCL_AMBIENT_ALPHA`). const AIR_CAP_HLSL: &str = r#" Texture2D _unused : register(t0); RWTexture3D vol_uav : register(u0); @@ -1952,6 +1975,23 @@ unsafe fn find_dispatch_views( ); } } + if role == PassRole::AlphaLight { + // Its own slot only: the filter writes the light's direction to another volume (dword + // 16), which a bound of luminance does not fit. + let slot = pinned(ALPHA_SLOT.0, ALPHA_SLOT.1); + let light = slot.filter(|(ve, rd)| { + ve.is_uav && ve.fmt == 26 && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 + }); + uav = light.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, rd.Width as u32, rd.Height, rd.DepthOrArraySize as u32)); + static SLOTS: AtomicU64 = AtomicU64::new(0); + if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: the transparent surfaces' light is {} ({:?})", + if light.is_some() { "the one in its slot" } else { "not in its slot: left as the title has it" }, + slot.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, ve.is_uav, rd.Dimension.0, rd.Width, rd.Height, rd.DepthOrArraySize)) + ); + } + } if role == PassRole::TemporalResolve && !want_3d { // The resolve's own slots: its // light at dword 176 of root parameter 1's table, the depth it reads at dword 464 of @@ -2007,11 +2047,15 @@ pub(super) unsafe fn after_compute_dispatch( | PassRole::ReflectionResolve | PassRole::InscatteringVolume | PassRole::Radiance + | PassRole::AlphaLight ) { return; } let cfg = config(); - if role == PassRole::InscatteringVolume && cfg.air <= 0.0 || role == PassRole::Radiance && cfg.frame <= 0.0 { + if role == PassRole::InscatteringVolume && cfg.air <= 0.0 + || role == PassRole::Radiance && cfg.frame <= 0.0 + || role == PassRole::AlphaLight && cfg.alpha <= 0.0 + { return; } let ty = list_x::tracked_list_type(list); @@ -2051,7 +2095,7 @@ pub(super) unsafe fn after_compute_dispatch( } } - let want_3d = role == PassRole::InscatteringVolume; + let want_3d = matches!(role, PassRole::InscatteringVolume | PassRole::AlphaLight); let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(role, layout, args, groups, view_heap_base, want_3d); // (`XCL_AMBIENT_SPACE=0`: no depth, the light is made on the screen) let depth_opt = depth_opt.filter(|_| space_light()); @@ -2065,7 +2109,7 @@ pub(super) unsafe fn after_compute_dispatch( return; }; let can_typed_load = typed_uav_load_supported(&dev, DXGI_FORMAT(uav_fmt)); - if matches!(role, PassRole::ReflectionHistory | PassRole::InscatteringVolume | PassRole::Radiance) && !can_typed_load { + if matches!(role, PassRole::ReflectionHistory | PassRole::InscatteringVolume | PassRole::Radiance | PassRole::AlphaLight) && !can_typed_load { static NO_LOAD: AtomicU64 = AtomicU64::new(0); if NO_LOAD.fetch_add(1, Ordering::Relaxed) < 2 { crate::xlog_info!("D3D12.X: ambient: {role:?} skipped (typed UAV load unsupported for fmt {uav_fmt})"); @@ -2190,6 +2234,11 @@ pub(super) unsafe fn after_compute_dispatch( [w, h, 0, 0, 0, cfg.frame.to_bits(), 0, 0], (FRAME_CELLS.0.div_ceil(8), FRAME_CELLS.1.div_ceil(8), 1), ), + PassRole::AlphaLight => ( + ad.air_pso.as_raw(), + [w, h, d, 0, 0, cfg.alpha.to_bits(), 0, 0], + (w.div_ceil(8), h.div_ceil(8), d.div_ceil(2)), + ), PassRole::SkyDome => return, }; set_heaps(list, 1, &heap_raw); @@ -2252,6 +2301,16 @@ pub(super) unsafe fn after_compute_dispatch( ); } } + if role == PassRole::AlphaLight { + static BOUND: AtomicU64 = AtomicU64::new(0); + let n = BOUND.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: ambient: the transparent surfaces' light held to {}x the light around, {w}x{h}x{d} ({n} so far)", + cfg.alpha + ); + } + } static LOGGED: AtomicU64 = AtomicU64::new(0); if LOGGED.fetch_add(1, Ordering::Relaxed) < 6 { @@ -2523,6 +2582,23 @@ mod tests { assert!(REFLECT_CLAMP_R9_HLSL.contains(&format!("float2({}.0, {}.0)", GATHER_POINTS.0, GATHER_POINTS.1))); } + /// The light of transparent surfaces is followed after its last filter, not after the + /// variance filter before it, and is not taken for the transparent reflections' resolve; it is + /// bounded at VIctory-Neo's strength unless the switch says 0, and found in a slot of its own. + #[test] + fn the_transparent_surfaces_light_is_bounded_after_its_last_filter() { + assert_eq!(classify_cs(b"..indirect_light_probes:CS_SpatialFilterAlpha_08e7839f_Wrapped.."), Some(PassRole::AlphaLight)); + assert!(is_ambient_compute(b"ILDN\0CS_SpatialFilterAlpha\0")); + assert_eq!(classify_cs(b"..CS_VarianceFilterAlpha_b92710bc_Wrapped.."), None); + assert_eq!(classify_cs(b"..CS_ShadeAlpha_1234abcd.."), None); + assert_eq!(classify_cs(b"ILDN\0CS_TemporalResolve1_Alpha_5678\0"), Some(PassRole::ReflectionResolve)); + let def = Config::default(); + assert!((def.alpha * def.frame - 4.0).abs() < 1e-6, "Neo's 4 of what the surfaces send out"); + assert_eq!(parse_f32(Some("0"), def.alpha, 0.0, 16.0), 0.0, "0: as the title has it"); + assert_eq!(ALPHA_SLOT, (1, 24)); + assert!(ALPHA_SLOT.1 % 8 == 0 && !REFLECTION_SLOTS.contains(&ALPHA_SLOT)); + } + /// R9G9B9E5 as the programs pack it. fn pack_r9(c: [f32; 3]) -> u32 { let c = c.map(|v| v.clamp(0.0, 65408.0)); From 2ba308183cb94c03fb3220ee03221a10bbc7c5c5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:28:13 +0100 Subject: [PATCH 063/175] D3D12.X: ambient drops the probes' blue garbage from the diffuse resolve What CS_ScreenProbes_TemporalResolve left is dropped where it is the probes' magenta garbage (green far below red and blue), then held to XCL_AMBIENT_MOST times the estimate by luminance. Garbage whose blue is far above its green and red passes both: the magenta test leaves it, and blue counts for 7 % of luminance, so a texel can hold many times the estimate in blue under the bound. VIctory-Neo's raise drops it too: blue over 2.5x green and over red (and over 0.02), left as a faint violet by the magenta test. The sky's light keeps green above 0.4x blue and sunsets keep blue low, so neither is touched. Port that line. It acts only where the title's own light is kept (XCL_AMBIENT_KEEP, or no XCL_RT_LEAVE_OUT); with the programs left out the fill sets it aside anyway. Test: a GPU run of the fill on an 8x8 image with garbage under the bound (it was kept before: 0.07, 0.10, 0.60 came out, the estimate 0.07 now) and the sky's blue light (bounded, hue kept). Ported from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, bdc3f38, GPL-3.0-or-later). (cherry picked from commit 6e97a1e894a619ed55b78fcf50c4fc5b3331a42e) --- crates/xcl/src/hle/d3d12x/ambient.rs | 34 ++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 046bf61e08..32c15a52ff 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -26,8 +26,9 @@ //! THIRD_PARTY.md): the cells, their slow mean, and the estimate made in space (2026-11-28). //! Ported in part from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later): //! the slots the reflections' resolves write, and their hold to the light around (its `hold`, -//! itself from Vice-Tay #99 and avatarmanz/VIctory-7900XTX #314), and the bound of the -//! transparent surfaces' light (its `Role::Alpha`, `ALPHA`) (2026-11-29). +//! itself from Vice-Tay #99 and avatarmanz/VIctory-7900XTX #314), the bound of the +//! transparent surfaces' light (its `Role::Alpha`, `ALPHA`), and the bluer kind of the probes' +//! garbage dropped from what the resolve left (its `raise`) (2026-11-29). //! //! With the depth the resolve reads, the estimate is made in space rather than on the screen: //! each cell is placed where it is seen (`LIGHT_PLACE_HLSL`), the cells' light is @@ -1100,6 +1101,9 @@ void main(uint3 tid : SV_DispatchThreadID) { if (!all(isfinite(was)) || (sky_ready & 2u) == 0u) was = float3(0.0, 0.0, 0.0); // Magenta (green far below red and blue) is what the probes' memory held, not light. if (was.g < 0.5 * min(was.r, was.b) && max(was.r, was.b) > 0.02) was = float3(0.0, 0.0, 0.0); + // And the bluer kind of it (blue over 2.5x green and over red), which the line above leaves + // as a faint violet. The sky's light keeps green above 0.4x blue, sunsets keep blue low. + if (was.b > 2.5 * was.g && was.b > was.r && was.b > 0.02) was = float3(0.0, 0.0, 0.0); // What the program left counts as far as it can be true: the sky's light outdoors, not the // blocks of other memory. float top = max(dot(found, LUMA) * MOST, 1e-6); @@ -2854,6 +2858,32 @@ mod tests { check(&by_cells, 1.25 * 0.05); } + /// What the diffuse resolve left is dropped where it is the probes' blue garbage (blue far + /// above green and above red), dim enough that the bound by the estimate keeps it, and kept + /// where it is the sky's blue light (bounded, its hue kept). + #[test] + fn the_resolves_blue_garbage_is_dropped_on_gpu() { + let cfg = config(); + let garbage = [0.05, 0.1, 0.6]; + let sky_blue = [0.3, 0.45, 0.8]; + let mut texels = [pack_r9(sky_blue); 64]; + texels[..32].fill(pack_r9(garbage)); + // the sky's level only: no frame's light kept yet (the mean's fourth part 0), no depth + let mut level = vec![[0.0f32; 4]; LEVEL_ELEMENTS as usize]; + level[0] = [0.2, 0.2, 0.2, 0.2]; + // the title's light kept (sky_ready bit 1), the sky captured (bit 0) + let consts = [8, 8, 1, 1, 0, cfg.ao.to_bits(), 3, PRE_SKY_FALLBACK.to_bits()]; + let Some(out) = (unsafe { run_on_r9_image(|ad| &ad.fill_r9_pso, false, consts, &texels, &level) }) else { return }; + let found = 0.2 * cfg.sky; + // the garbage was under the bound (MOST times the estimate) all the same + assert!(luma(garbage) < found * cfg.most, "the test needs garbage the bound keeps"); + let g = unpack_r9(out[0]); + assert!(g.iter().all(|&c| (c - found).abs() < 0.01 * found + 1e-4), "garbage dropped, the estimate left: {g:?} for {found}"); + let s = unpack_r9(out[63]); + assert!((luma(s) - found * cfg.most).abs() < 0.02 * found * cfg.most, "sky light bounded: {s:?}"); + assert!((s[2] / s[1] - sky_blue[2] / sky_blue[1]).abs() < 0.05, "sky light keeps its hue: {s:?}"); + } + #[test] fn scan_cbv_indices_resolves_each_64k_mirror_page_independently() { const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; From 0e68d6065eb097364e705a8aa366524966930a68 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:39:39 +0100 Subject: [PATCH 064/175] D3D12.X: draws that test a depth buffer left in UAV get its twin first A depth buffer that shaders write keeps those writes in a twin, which depth_uav copies into the depth plane only where the title moves the buffer out of UNORDERED_ACCESS. A draw that tests against the buffer before that, with the title leaving it in UNORDERED_ACCESS, tests the plane as it was before the shaders wrote the twin. VIctory-Neo (7da5c9d, "the depth image a pixel program wrote is brought up to date before the draws that test against it") found this in a retail title's mirrors: a pixel program (PS_Prepass_StencilCulling) writes the depth of the mirror's view through unordered access, and the draws of that view, in the same list, test against it. With the copy left for later every one of them tested the old plane and the mirror showed the sky. Neo does the copy (its plane pass) right before such a draw and sets the title's state again after it. Here, for a stretch that begins with a transition of all of a buffer into UNORDERED_ACCESS on a DIRECT list (the twin then holds the plane), the list follows which side was written last and copies it into the other before the work that uses that one (depth_uav::before_work, from list_x::prepare_draw, set_compute_pipeline and the UAV clears): - a draw whose depth target names the buffer: the twin into the plane first, once until other work may have written the twin again; - any other draw or dispatch (it may write the twin: XCL does not see which views a translated shader reaches): the plane into the twin first when such a draw tested (and may have written) the plane; - the way out of UNORDERED_ACCESS after such draws does not copy the twin over the plane. These are whole-plane CopyTextureRegion calls between states XCL knows (the buffer rests in PARK, the twin in UNORDERED_ACCESS), so nothing bound on the list changes and nothing needs to be set again. A stretch without such a draw copies exactly as before. R24G8 buffers are not followed: their copy into the plane is a draw of XCL's that a draw being bound cannot take. A list that did not see the stretch begin follows it from its first draw that tests against the buffer. XCL_DEPTH_PLANE_NOW=0 turns it off (on by default). XCL_TWIN_TRACE= logs, for depth buffers of that height (736: a mirror's view), the title's transitions into and out of UNORDERED_ACCESS, the twin copies, the DSV binds and the draws that test against them (first 600 lines), so a game run shows which of these the title does. Not seen in an XCL run yet: whether the title leaves the mirror's depth in UNORDERED_ACCESS for those draws (Neo follows uses, not transitions). (cherry picked from commit 77dfb95595855fca9c8360f73031e45061faee72) --- crates/xcl/src/hle/d3d12x/depth_uav.rs | 416 ++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 42 +++ 2 files changed, 452 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 88fca6a5e1..c47bb55fa2 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -28,7 +28,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::ManuallyDrop; -use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; use windows::core::{Interface, PCSTR}; @@ -86,9 +86,23 @@ struct Cell { /// the plane (a copy, or the two known to hold the same): only then is the twin copied back /// (`plan_barriers`) entered: AtomicBool, + /// the number of the stretch the title has had the buffer in UNORDERED_ACCESS since a + /// transition of all of it that put the twin in step (0: none): draws that test against the + /// buffer then are watched (`before_work`) + live: AtomicU64, + /// which of the depth plane and its twin holds what was written last in that stretch (`Side`) + side: AtomicU8, inner: Mutex, } +impl Drop for Cell { + fn drop(&mut self) { + if *self.live.get_mut() != 0 { + LIVE.fetch_sub(1, Ordering::Relaxed); + } + } +} + #[derive(Default)] struct Inner { /// registered objects of this buffer @@ -140,7 +154,6 @@ struct Object { } #[derive(Clone)] -#[allow(dead_code)] // (read once DSV binds are followed) struct Dsv { res: usize, /// D3D12_DSV_FLAGS of the view: 1 read-only depth, 2 read-only stencil @@ -173,6 +186,14 @@ static CELL_IDS: AtomicU64 = AtomicU64::new(1); static TO_TWIN: AtomicU64 = AtomicU64::new(0); static TO_PLANE: AtomicU64 = AtomicU64::new(0); static IN_STEP: AtomicU64 = AtomicU64::new(0); +/// Cells with a `live` stretch, and the stretches numbered. +static LIVE: AtomicUsize = AtomicUsize::new(0); +static STRETCHES: AtomicU64 = AtomicU64::new(1); +/// Copies made before draws and dispatches inside such a stretch (`before_work`): [into the +/// twin, into the plane]; copies out of UNORDERED_ACCESS not made because a draw's depth test +/// left the plane the newer side. +static WORK_COPIES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +static PLANE_KEPT: AtomicU64 = AtomicU64::new(0); /// Whether a twin is alive: the gate of the paths that record. pub(super) fn any() -> bool { @@ -217,7 +238,18 @@ fn register(res: usize, x: &[u8; 0x38], at: Option, pc_state: u32) -> boo let cells = g.get_or_insert_with(HashMap::new); let cell = cells .entry(key) - .or_insert_with(|| Arc::new(Cell { key, id: CELL_IDS.fetch_add(1, Ordering::Relaxed), console_format: u32_at(x, 0x20), twinned: AtomicBool::new(false), entered: AtomicBool::new(false), inner: Mutex::new(Inner::default()) })) + .or_insert_with(|| { + Arc::new(Cell { + key, + id: CELL_IDS.fetch_add(1, Ordering::Relaxed), + console_format: u32_at(x, 0x20), + twinned: AtomicBool::new(false), + entered: AtomicBool::new(false), + live: AtomicU64::new(0), + side: AtomicU8::new(Side::Both as u8), + inner: Mutex::new(Inner::default()), + }) + }) .clone(); { let mut inner = cell.inner.lock().unwrap(); @@ -354,10 +386,12 @@ pub(super) unsafe fn resolve_uav(dev: *mut c_void, res: *mut c_void, rd: Option< } // (its states stay the title's: the twin would never be copied) if !stencil && (o.cell.inner.lock().unwrap().made_in.unwrap_or(o.state) | o.state) & UNORDERED_ACCESS != 0 { + twin_trace(&key, || format!("a UAV of object {:#x} stays a null view: the buffer was made in UNORDERED_ACCESS", res as usize)); return Resolve::Null("the buffer was made in UNORDERED_ACCESS"); } // (the Cell holds the twin) - let Some((twin, _)) = plane_twin(&o, stencil as usize, dev) else { return Resolve::Null("the twin could not be made") }; + let Some((twin, n)) = plane_twin(&o, stencil as usize, dev) else { return Resolve::Null("the twin could not be made") }; + twin_trace(&key, || format!("a UAV of the {} plane of object {:#x} is a view of twin #{n}", if stencil { "stencil" } else { "depth" }, res as usize)); REDIRECTED.fetch_add(1, Ordering::Relaxed); let r16 = is_r16_depth(key.format, o.cell.console_format); Resolve::Twin(twin.as_raw(), if stencil { twin_view(view, key.array) } else { depth_twin_view(view, key.array, r16) }) @@ -487,6 +521,10 @@ pub(super) struct Plan { /// after them: depth planes into twins (the buffer rests in PARK; the twin /// UNORDERED_ACCESS → COPY_DEST and back, or CS UAV write for R24G8) pub to_twin: Vec, + /// buffers whose `live` stretch these barriers began: the list follows them (`Owed::add`) + pub live: Vec, + /// Cells whose stretch these barriers ended + pub settled: Vec, } /// Whether the depth plane of `o`'s buffer can have a twin: a D32, D16, D32S8 or D24S8/D16S8 @@ -587,9 +625,19 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, if leaving { before = PARK; // (a twin whose last way in was not copied holds something else than the plane: not - // copied back – what the shaders wrote into it is lost, as without a twin) + // copied back – what the shaders wrote into it is lost, as without a twin; nor one + // whose plane draws tested and wrote since the twin was last copied into it there, + // `before_work`: the plane holds the newer depth) + let plane_newer = o.cell.live.load(Ordering::Relaxed) != 0 && Side::of(&o.cell) == Side::Plane; let t = (direct && !subs.is_empty()).then(|| twin_if_made(&o)).flatten(); - if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed)) { + if plane_newer && t.is_some() { + let c = PLANE_KEPT.fetch_add(1, Ordering::Relaxed) + 1; + if c <= 4 || c.is_power_of_two() { + crate::xlog_info!("D3D12.X: depth UAV twin: the title moves depth buffer {res:#x} out of UNORDERED_ACCESS into state {after:#x} after draws tested against its plane: the twin is not copied into it ({c} such transitions so far)"); + } + } + twin_trace(&key, || format!("out of UNORDERED_ACCESS into {after:#x} (subresource {sub:#x}, direct {direct}): {}", if t.is_none() { "no twin copy (no twin, or a compute list)" } else if plane_newer { "the plane is newer, not copied" } else if entered.load(Ordering::Relaxed) { "the twin is copied into the plane" } else { "the twin's way in was not copied: not copied back" })); + if let Some((t, k)) = t.filter(|_| entered.load(Ordering::Relaxed) && !plane_newer) { before = if r24g8_steps.is_some() { DEPTH_WRITE_STATE } else { COPY_DEST }; let c = TO_PLANE.fetch_add(1, Ordering::Relaxed) + 1; if c <= 4 || c.is_power_of_two() { @@ -613,6 +661,9 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, if writes(after) { in_step.retain(|&c| c != id); } + if end_stretch(&o.cell) { + plan.settled.push(id); + } } if entering { after = PARK; @@ -650,6 +701,17 @@ fn plan_with(barriers: &mut Vec<[u32; 8]>, direct: bool, in_step: &mut Vec, entered.store(false, Ordering::Relaxed); } } + // all of a buffer whose twin now holds its plane, on a DIRECT list: a stretch whose + // draws that test against the buffer are watched (`before_work`; not an R24G8 one, + // whose copy into the plane is a pass of XCL's that a draw being bound cannot take) + let whole = direct && sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && key.format != 44 && entered.load(Ordering::Relaxed); + if whole { + let stretch = begin_stretch(&o.cell); + plan.live.push(Acting { id, stretch, cell: Arc::downgrade(&o.cell), res }); + } else if end_stretch(&o.cell) { + plan.settled.push(id); + } + twin_trace(&key, || format!("into UNORDERED_ACCESS from {before:#x} (subresource {sub:#x}, direct {direct}): the twin {}; draws testing against it are {}watched", if entered.load(Ordering::Relaxed) { "holds the plane" } else { "does not hold the plane" }, if whole { "" } else { "not " })); } (b[5], b[6]) = (before, after); if before != after { @@ -716,6 +778,246 @@ fn twin_if_made(o: &Object) -> Option<(ID3D12Resource, u64)> { o.cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n)) } +// --------------------------------------------------------------------------------------- +// Draws that test against a buffer the title has in UNORDERED_ACCESS +// +// The twin is copied into the plane where the title moves the buffer out of UNORDERED_ACCESS. +// A draw that tests against the buffer before that – with no transition in between, the title +// leaving it in UNORDERED_ACCESS – tested the plane as it was before the shaders wrote the twin. +// (VIctory-Neo, https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later, 7da5c9d "the depth +// image a pixel program wrote is brought up to date before the draws that test against it": +// the title marks a mirror's pixels with a pixel program writing the depth of the mirror's view +// through unordered access, then draws that view against it in the same list; with the copy +// left for later the mirror showed the sky.) Here, in such a stretch, the list that began it +// follows which side was written last and copies it into the other before the work that uses +// that one: the twin into the plane before a draw whose depth target names the buffer, the plane +// into the twin before any other draw or dispatch (it may write the twin: XCL does not see which +// views a translated shader reaches). Both are copies of whole planes between resources in +// states XCL knows (the buffer rests in PARK, the twin in UNORDERED_ACCESS): nothing bound on +// the list changes. An R24G8 buffer's plane is written by a pass of XCL's (`execute_r24g8_copy`) +// that a draw being bound cannot take: its stretches are not followed. On unless +// `XCL_DEPTH_PLANE_NOW=0`. +// --------------------------------------------------------------------------------------- + +/// Whether draws inside a `live` stretch are followed (`XCL_DEPTH_PLANE_NOW`, on unless "0"). +fn plane_now() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| on(std::env::var("XCL_DEPTH_PLANE_NOW").ok().as_deref(), true)) +} + +/// The stretch of `cell` in UNORDERED_ACCESS begins; its number. The two sides hold the same. +fn begin_stretch(cell: &Cell) -> u64 { + let n = STRETCHES.fetch_add(1, Ordering::Relaxed); + cell.side.store(Side::Both as u8, Ordering::Relaxed); + if plane_now() && cell.live.swap(n, Ordering::Relaxed) == 0 { + LIVE.fetch_add(1, Ordering::Relaxed); + } + n +} + +/// The stretch of `cell` ends; false: it had none. +fn end_stretch(cell: &Cell) -> bool { + let had = cell.live.swap(0, Ordering::Relaxed) != 0; + if had { + LIVE.fetch_sub(1, Ordering::Relaxed); + } + had +} + +/// Whether a buffer is in a `live` stretch: the gate of the draw and dispatch hooks. +pub(super) fn any_live() -> bool { + LIVE.load(Ordering::Relaxed) != 0 +} + +/// Which of a depth plane and its twin holds what was written last in a `live` stretch. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[repr(u8)] +enum Side { + /// the same (the twin was copied from the plane, or the other way) + Both = 0, + /// shaders may have written the twin since + Twin = 1, + /// a draw tested against the plane, and may have written it + Plane = 2, +} + +impl Side { + fn of(cell: &Cell) -> Side { + match cell.side.load(Ordering::Relaxed) { + 1 => Side::Twin, + 2 => Side::Plane, + _ => Side::Both, + } + } +} + +/// What a draw or dispatch does with a buffer in a `live` stretch. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Use { + /// tests against its plane (its depth target names the buffer); `write`: the view does not + /// make the depth read only + Depth { write: bool }, + /// anything else: it may write the twin through a UAV + Shader, +} + +/// The copy a use `u` of a buffer whose newer side is `side` needs first (Some(true): the plane +/// into the twin, Some(false): the twin into the plane), and the newer side after it. +fn step(side: Side, u: Use) -> (Option, Side) { + match u { + // (a read-only depth target leaves the two as they were after the copy) + Use::Depth { write } => ((side == Side::Twin).then_some(false), if write || side == Side::Plane { Side::Plane } else { Side::Both }), + Use::Shader => ((side == Side::Plane).then_some(true), Side::Twin), + } +} + +/// A buffer a list follows in its `live` stretch. +#[derive(Clone)] +pub(super) struct Acting { + id: u64, + stretch: u64, + cell: Weak, + /// the object the title's transition named + res: usize, +} + +/// The buffers a list follows in their `live` stretches (`before_work`). It is the list's, and +/// goes with its recording. +#[derive(Default)] +pub(super) struct Owed(Vec); + +impl Owed { + /// The buffers whose stretches `plan`'s barriers began are followed, those they ended not. + pub(super) fn apply(&mut self, plan: &Plan) { + if plan.live.is_empty() && plan.settled.is_empty() { + return; + } + self.0.retain(|a| !plan.settled.contains(&a.id) && !plan.live.iter().any(|l| l.id == a.id)); + self.0.extend(plan.live.iter().cloned()); + } +} + +/// A copy to record before a draw or dispatch (`before_work`): of the plane into the twin +/// (`to_twin`) or of the twin into the plane, all the plane's subresources. +pub(super) struct WorkCopy { + pub copy: PlaneCopy, + pub to_twin: bool, +} + +/// All of the depth plane of `res` (an object of `cell`) and its twin, and the twin's number. +fn whole_copy(cell: &Cell, res: usize) -> Option<(PlaneCopy, u64)> { + let (twin, k) = cell.inner.lock().unwrap().twins[0].as_ref().map(|t| (t.res.clone(), t.n))?; + let key = cell.key; + let n = key.mips.max(1) as u32 * key.array.max(1) as u32; + let copy = PlaneCopy { + depth: res, + sub: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + subs: (0..n).collect(), + twin, + r24g8_steps: None, + width: key.width, + height: key.height, + array: key.array.max(1), + mips: key.mips.max(1), + }; + Some((copy, k)) +} + +/// A draw whose depth target is the DSV at `dsv` (None: none, or a dispatch) is about to be +/// recorded on a DIRECT list that follows the buffers `owed`: the copies to record before it, +/// so that the side each buffer's use reads holds what was written last. A depth target of a +/// buffer in a stretch the list does not follow yet (begun on another list) is followed from +/// here on. +pub(super) fn before_work(owed: &mut Owed, dsv: Option) -> Vec { + let tested = dsv.filter(|_| DSV_ENTRIES.load(Ordering::Relaxed) != 0).and_then(|h| DSVS.get(h)).and_then(|d| Some((d.res, d.flags, d.cell.upgrade()?))); + if let Some((res, _, cell)) = &tested { + let stretch = cell.live.load(Ordering::Relaxed); + if stretch != 0 && !owed.0.iter().any(|a| a.id == cell.id) { + twin_trace(&cell.key, || format!("a list follows the stretch begun elsewhere from a draw that tests against object {res:#x}")); + owed.0.push(Acting { id: cell.id, stretch, cell: Arc::downgrade(cell), res: *res }); + } + } + let mut out = Vec::new(); + owed.0.retain(|a| { + let Some(cell) = a.cell.upgrade() else { return false }; + if cell.live.load(Ordering::Relaxed) != a.stretch { + return false; + } + let (target, u) = match &tested { + Some((res, flags, c)) if Arc::ptr_eq(c, &cell) => (*res, Use::Depth { write: flags & 1 == 0 }), + _ => (a.res, Use::Shader), + }; + let was = Side::of(&cell); + let (copy, side) = step(was, u); + if let Some(to_twin) = copy { + // (no twin: the side stays as it was) + let Some((c, k)) = whole_copy(&cell, target) else { return true }; + let n = WORK_COPIES[(!to_twin) as usize].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + if to_twin { + crate::xlog_info!("D3D12.X: depth UAV twin #{k}: work after draws that tested against depth buffer {target:#x}, which the title has in UNORDERED_ACCESS: its depth plane is copied into the twin first ({n} such copies so far)"); + } else { + crate::xlog_info!("D3D12.X: depth UAV twin #{k}: a draw tests against depth buffer {target:#x}, which the title has in UNORDERED_ACCESS, after shaders may have written its twin: the twin is copied into the depth plane first ({n} such copies so far)"); + } + } + twin_trace(&cell.key, || format!("{u:?} of object {target:#x}: the {} first", if to_twin { "plane is copied into the twin" } else { "twin is copied into the plane" })); + out.push(WorkCopy { copy: c, to_twin }); + } else if was != side && matches!(u, Use::Depth { .. }) { + twin_trace(&cell.key, || format!("{u:?} of object {target:#x}: the sides held the same, no copy")); + } + cell.side.store(side as u8, Ordering::Relaxed); + true + }); + out +} + +/// `XCL_TWIN_TRACE=` (a test aid): what XCL does with the depth buffers of that height +/// that shaders write – the title's transitions into and out of UNORDERED_ACCESS, the copies of +/// their twins, the DSVs bound and the draws that test against them – a line each for the first +/// 600 (a mirror's view is 736 high in a retail title). +fn twin_trace(key: &Key, what: impl FnOnce() -> String) { + let h = trace_height(); + if h == 0 || key.height != h { + return; + } + static SAID: AtomicU32 = AtomicU32::new(0); + if SAID.fetch_add(1, Ordering::Relaxed) >= 600 { + return; + } + crate::xlog_info!( + "D3D12.X: XCL_TWIN_TRACE: frame {}: depth buffer at {:#x} ({}x{}x{}, PC format {}): {}", + super::present::counters().1, + key.at, + key.width, + key.height, + key.array, + key.format, + what() + ); +} + +fn trace_height() -> u32 { + static HEIGHT: OnceLock = OnceLock::new(); + *HEIGHT.get_or_init(|| std::env::var("XCL_TWIN_TRACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// `XCL_TWIN_TRACE`: list `list` binds the DSV at `dsv`. +pub(super) fn trace_dsv_bind(list: usize, dsv: usize) { + if trace_height() == 0 || DSV_ENTRIES.load(Ordering::Relaxed) == 0 { + return; + } + let Some(d) = DSVS.get(dsv) else { return }; + let Some(cell) = d.cell.upgrade() else { return }; + twin_trace(&cell.key, || { + format!( + "list {list:#x} binds a DSV of object {:#x} (flags {:#x}); {}", + d.res, + d.flags, + if cell.live.load(Ordering::Relaxed) != 0 { format!("in a followed stretch in UNORDERED_ACCESS, the newer side {:?}", Side::of(&cell)) } else { "not in UNORDERED_ACCESS as far as XCL followed it".to_owned() } + ) + }); +} + struct SyncPipelines { gfx_rs: ID3D12RootSignature, gfx_pso: ID3D12PipelineState, @@ -1961,6 +2263,108 @@ mod tests { forget(in_ua); } + #[test] + fn a_draws_depth_test_and_other_work_each_get_the_side_written_last() { + let depth = |write| Use::Depth { write }; + // a draw that tests against the buffer: the twin into the plane when shaders may have + // written it; the plane is the newer side after (unless the view is read only) + assert_eq!(step(Side::Twin, depth(true)), (Some(false), Side::Plane)); + assert_eq!(step(Side::Both, depth(true)), (None, Side::Plane)); + assert_eq!(step(Side::Plane, depth(true)), (None, Side::Plane)); + assert_eq!(step(Side::Twin, depth(false)), (Some(false), Side::Both)); + assert_eq!(step(Side::Both, depth(false)), (None, Side::Both)); + assert_eq!(step(Side::Plane, depth(false)), (None, Side::Plane)); + // any other work: the plane into the twin after such draws; the twin is the newer side after + assert_eq!(step(Side::Plane, Use::Shader), (Some(true), Side::Twin)); + assert_eq!(step(Side::Both, Use::Shader), (None, Side::Twin)); + assert_eq!(step(Side::Twin, Use::Shader), (None, Side::Twin)); + } + + /// (the copies before work: (object, into the twin, subresources)) + fn work(c: &[WorkCopy]) -> Vec<(usize, bool, Vec)> { + c.iter().map(|c| (c.copy.depth, c.to_twin, c.copy.subs.clone())).collect() + } + + #[test] + fn draws_that_test_against_a_buffer_left_in_unordered_access_get_what_shaders_wrote() { + let (res, dsv, ro_dsv) = (0x7E30_0000_1000usize, 0x7E30_0001_0000usize, 0x7E30_0001_0040usize); + // a console D32 of 2 mips with unordered access and a depth twin, two DSVs of it + let mut x = desc(3, 1280, 736, 40, 1, 6); + x[0x1E..0x20].copy_from_slice(&2u16.to_le_bytes()); + assert!(register(res, &x, None, DEPTH_WRITE)); + let t = stand_in(); + plant_depth_twin(res, &t); + note_dsv(dsv, res, 0); + note_dsv(ro_dsv, res, 1); + let id = cell_of(res).unwrap().id; + let mut owed = Owed::default(); + let barrier = |b: [u32; 8], owed: &mut Owed| { + let mut v = vec![b]; + let p = plan_with(&mut v, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + owed.apply(&p); + (copies(&p.to_plane), p.settled) + }; + + // into UNORDERED_ACCESS: followed; a pixel program writes the twin (any other draw) + barrier(tr(res, ALL, DEPTH_WRITE, UA), &mut owed); + assert!(any_live()); + assert!(before_work(&mut owed, None).is_empty(), "the two hold the same"); + // the draws that test against it: the twin into the plane first, once + assert_eq!(work(&before_work(&mut owed, Some(dsv))), [(res, false, vec![0, 1])]); + assert!(before_work(&mut owed, Some(dsv)).is_empty(), "the plane holds it now"); + assert!(before_work(&mut owed, Some(ro_dsv)).is_empty()); + // work after them may read the twin: the plane, which those draws wrote, into the twin + assert_eq!(work(&before_work(&mut owed, None)), [(res, true, vec![0, 1])]); + assert!(before_work(&mut owed, None).is_empty()); + // a read-only depth target after it: the twin into the plane, and the two hold the same + assert_eq!(work(&before_work(&mut owed, Some(ro_dsv))), [(res, false, vec![0, 1])]); + assert!(before_work(&mut owed, Some(ro_dsv)).is_empty()); + assert!(before_work(&mut owed, Some(dsv)).is_empty()); + // out of UNORDERED_ACCESS after a draw tested (and wrote) the plane: the twin is not + // copied over it; the stretch ends + let kept = PLANE_KEPT.load(Ordering::Relaxed); + assert_eq!(barrier(tr(res, ALL, UA, DEPTH_READ), &mut owed), (vec![], vec![id])); + assert!(PLANE_KEPT.load(Ordering::Relaxed) > kept); + assert!(before_work(&mut owed, Some(dsv)).is_empty() && owed.0.is_empty(), "no longer followed"); + + // in and out with shaders only: copied back as before + barrier(tr(res, ALL, DEPTH_READ, UA), &mut owed); + assert!(before_work(&mut owed, None).is_empty()); + assert_eq!(barrier(tr(res, ALL, UA, DEPTH_WRITE), &mut owed), (vec![(res, ALL, vec![0, 1], t.as_raw() as usize)], vec![id])); + + // a stretch begun on another list: this one follows it from a draw that tests against it + let mut other = Owed::default(); + barrier(tr(res, ALL, DEPTH_WRITE, UA), &mut other); + assert!(before_work(&mut owed, None).is_empty(), "not followed here: nothing"); + assert!(before_work(&mut other, None).is_empty()); + assert_eq!(work(&before_work(&mut owed, Some(dsv))), [(res, false, vec![0, 1])]); + assert_eq!(owed.0.len(), 1); + barrier(tr(res, ALL, UA, DEPTH_WRITE), &mut other); + + // not followed: one subresource, or into UNORDERED_ACCESS on a compute list + barrier(tr(res, 1, DEPTH_WRITE, UA), &mut owed); + assert!(cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + barrier(tr(res, 1, UA, DEPTH_WRITE), &mut owed); + let mut v = vec![tr(res, ALL, DEPTH_WRITE, UA)]; + let p = plan_with(&mut v, false, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + assert!(p.live.is_empty() && cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + forget(res); + } + + #[test] + fn an_r24g8_buffer_in_unordered_access_is_not_followed() { + let res = 0x7E40_0000_1000usize; + // a console D16S8 (PC R24G8): its plane is written by a pass a draw being bound cannot take + assert!(register(res, &desc(3, 64, 64, 118, 1, 6), None, DEPTH_WRITE)); + let t = stand_in(); + plant_depth_twin(res, &t); + let mut v = vec![tr(res, ALL, DEPTH_WRITE, UA)]; + let p = plan_with(&mut v, true, &mut Vec::new(), &mut |_r, o| twin_if_made(o)); + assert_eq!(p.to_twin.len(), 1, "copied into its twin as before"); + assert!(p.live.is_empty() && cell_of(res).unwrap().live.load(Ordering::Relaxed) == 0); + forget(res); + } + /// The library's tests run with the switch as the process has it (by default as DEFAULT_ON). #[test] fn with_the_switch_off_the_titles_barriers_go_as_they_came() { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index b7cf57bbe2..722a398311 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -113,6 +113,8 @@ pub(super) fn tracked_list_type(list: *mut c_void) -> Option(list, PC_SET_PIPELINE_STATE)(list, pso); } @@ -718,6 +720,9 @@ pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const let handles = if read_count == 0 { Vec::new() } else { std::slice::from_raw_parts(rtvs, read_count).to_vec() }; let d = dsv.as_ref().copied(); with_bindings(this, |b| b.render_targets = Some(RenderTargets { num_targets, handles, single, dsv: d })); + if let Some(d) = d { + super::depth_uav::trace_dsv_bind(this as usize, d); + } } /// The render target views bound on `list` (each one of a single descriptor range too). @@ -832,6 +837,9 @@ struct ListState { own_alloc: Option, /// depth buffers whose depth plane and twin hold the same on this recording (`depth_uav::plan_barriers`) depth_in_step: Vec, + /// depth buffers the title has in UNORDERED_ACCESS whose draws this recording follows + /// (`depth_uav::before_work`) + depth_owed: super::depth_uav::Owed, } /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. @@ -4285,8 +4293,38 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b } } +/// Before a draw (`draw`: its depth target the one bound) or a dispatch on `list`: the copies +/// between depth planes and their twins that the buffers the title has in UNORDERED_ACCESS need +/// first (`depth_uav::before_work`). Copies and barriers only: nothing bound on the list changes. +unsafe fn depth_twins_before_work(list: *mut c_void, draw: bool) { + if !super::depth_uav::any_live() { + return; + } + let (mut owed, dsv) = { + let mut g = recording(list as usize).lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(list as usize))) else { return }; + if s.list_type != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + (std::mem::take(&mut s.depth_owed), if draw { s.bindings.render_targets.as_ref().and_then(|rt| rt.dsv) } else { None }) + }; + let copies = super::depth_uav::before_work(&mut owed, dsv); + if let Some(s) = recording(list as usize).lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.depth_owed = owed; + } + for c in copies { + plane_copies_on(list, std::slice::from_ref(&c.copy), c.to_twin); + // (into the plane: from PARK to COPY_DEST there, back where the title has it) + if !c.to_twin { + let tr = [0, 0, c.copy.depth as u32, (c.copy.depth as u64 >> 32) as u32, c.copy.sub, D3D12_RESOURCE_STATE_COPY_DEST.0 as u32, super::depth_uav::PARK, 0]; + pc::(list, PC_RESOURCE_BARRIER)(list, 1, &tr); + } + } +} + /// Apply a pending fallback `RSSetDepthBiasX` override before a draw call on `list`. pub(super) unsafe fn prepare_draw(list: *mut c_void) { + depth_twins_before_work(list, true); if !DEPTH_BIAS_USED.load(Ordering::Acquire) { return; } @@ -4934,6 +4972,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.pred_in_state = false; s.bindings = Bindings::default(); s.depth_in_step.clear(); + s.depth_owed = Default::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; super::title_textures::list_reset(this as usize); @@ -5065,6 +5104,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 let plan = super::depth_uav::plan_barriers(&mut out, direct, &mut in_step); if let Some(s) = recording(this as usize).lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { s.depth_in_step = in_step; + s.depth_owed.apply(&plan); } plan }); @@ -5481,6 +5521,8 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi return refused(); } let Some(res) = uav_clear_resource(res, gpu_slot) else { return refused() }; + // (a clear of a depth twin writes it) + depth_twins_before_work(this, false); pc::(this, slot)(this, gpu, cpu, res, values, n, rects) } From b0573e35043907dc49360105f3af199f97c1a59b Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:51:39 +0100 Subject: [PATCH 065/175] D3D12.X: a mirror's view is given the light around while rays are off A retail title lights what a mirror shows as a view of its own: one full-screen draw per material (PS_MIRROR_PBR_MATERIAL_*) into a lit image, then the sky and the air (ps_mirror_volumetric_sky) into the same image. The materials take their indirect light from the probes the title's rays fill; with the rays held back the view has the sun's direct light alone and a room is black in it. VIctory-Neo (a3af274, "the mirror's view is given the light around"; 9b61dc9 builds the pass's programs in a test) adds, right before the sky's draw, the light around times each texel's own colour. Its run mm1 (first house, bathroom, no rays): the mirror shows the character and the room behind him instead of black. mirror.rs ports it onto XCL's stand-in (ambient): - the parts by the pixel program's name, noted where the graphics pipelines are made (real.rs, next to ambient's own note); - the light around: the mean of 144 of the level buffer's 160x90 gathered points (its 64x36 cells when the light is not made in space) with a fifth of the slow mean, at least the sky's level at XCL_AMBIENT_SKY, read through ambient::level_for_mirror (one new pub(crate) fn at the end of ambient.rs); - the colour: at the draw of the view's material mask (ps_generate_material_mask), the 8-bit colour target of the mask's size bound last before it, sRGB first (Neo reads it from the mask draw's descriptor tables, which XCL does not see from list_x); - the pass: a full-screen triangle with additive blending into the lit image within the sky draw's scissor, its alpha kept. A draw is bound in bind before list_x::prepare_draw sees it, and a pass cannot go between that binding and the draw, so the pass is owed at the sky's draw and recorded at the list's next point between the title's commands (its next barriers, render targets or Close), with the title's state set again after it (restore_after_internal_pass, as the depth twin's R24G8 pass does). Only the air the sky's draw lays over the surfaces is then not laid over the added light. XCL_MIRROR_AMBIENT= (default 1; 0: off). Nothing is added while the stand-in is off or the title's rays run (ambient::active). Tests: parts by name, the switch, the colour's choice, both programs compile with D3DCompile and the root signature serializes, and on the software adapter a 4x4 pass adds colour x 0.9 inside its rect and nothing outside it. Not run on the title. (cherry picked from commit 1de7c92cee82ab0093318f3e131732247995e48a) --- THIRD_PARTY.md | 1 + crates/xcl/src/hle/d3d12x/ambient.rs | 11 + crates/xcl/src/hle/d3d12x/list_x.rs | 58 ++ crates/xcl/src/hle/d3d12x/mirror.rs | 771 +++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 3 + 6 files changed, 845 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/mirror.rs diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index c088995ee0..6202f2aaeb 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -12,6 +12,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | | [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs` (the programs left out); `crates/xcl/src/hle/d3d12x/ambient.rs`: the cells and their slow mean, and the stand-in for the indirect light made in space – `LIGHT_PLACE_HLSL`, `LIGHT_GATHER_HLSL`, the depth path of `AMBIENT_FILL_R9G9B9E5_HLSL`, `AIR_CAP_HLSL` and the resolve's descriptor slots, after `place`, `gather`, `raise`, `clear_air`, `LIGHT` and `DEPTH` of its `ambient.rs` (commit 99a7f9b) | port of the HLSL into XCL's ambient pass (2026-11-28) | +| [VIctory-Neo](https://github.com/KyleS98/VIctory-Neo) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/mirror.rs`: the light around a mirror's view – the programs' parts by name, `XCL_MIRROR_AMBIENT` and the pass and its programs, after its `crates/victory-gpu/src/mirror.rs` (commits a3af274, 9b61dc9); `crates/xcl/src/hle/d3d12x/depth_uav.rs`: a depth plane brought up to date from its twin before the draws that test against it, after 7da5c9d | port adapted to XCL's passes and state (2026-11-29) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 32c15a52ff..914f269114 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -2322,6 +2322,17 @@ pub(super) unsafe fn after_compute_dispatch( } } +/// For `mirror` (a mirror's view is given the light around): while the stand-in runs on `dev`, +/// its level buffer (used as a UAV, `LEVEL_ELEMENTS` float4s), the share the sky's level counts +/// for (`XCL_AMBIENT_SKY`) and whether a sky was captured. +pub(crate) unsafe fn level_for_mirror(dev: &ID3D12Device) -> Option<(ID3D12Resource, u32, f32, bool)> { + if !active() { + return None; + } + let ad = get_device(dev)?; + Some((ad.sky_level.clone(), LEVEL_ELEMENTS, config().sky, ad.sky_ready.load(Ordering::Acquire))) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 722a398311..dee65b213b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -723,6 +723,11 @@ pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const if let Some(d) = d { super::depth_uav::trace_dsv_bind(this as usize, d); } + if super::mirror::any() { + let rts: Vec = bound_render_targets(this).into_iter().filter_map(super::present::rtv_resource).collect(); + super::mirror::note_targets(&rts); + mirror_flush(this); + } } /// The render target views bound on `list` (each one of a single descriptor range too). @@ -840,6 +845,8 @@ struct ListState { /// depth buffers the title has in UNORDERED_ACCESS whose draws this recording follows /// (`depth_uav::before_work`) depth_owed: super::depth_uav::Owed, + /// the light around a mirror's view is owed after its sky's draw (`mirror_flush`) + mirror: Option, } /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. @@ -3849,6 +3856,7 @@ unsafe fn predication_buffer(list: *mut c_void) -> Option { /// Before `Close()` on a command list: return `pred_buf` to `COMMON` if it is currently in /// `D3D12_RESOURCE_STATE_PREDICATION`. pub(super) unsafe fn before_close(list: *mut c_void) { + mirror_flush(list); super::format_alias::before_close(list); if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { return; @@ -4322,9 +4330,55 @@ unsafe fn depth_twins_before_work(list: *mut c_void, draw: bool) { } } +/// Before a draw on `list` of a mirror view's material mask or sky (`mirror`): the colour of +/// the view's surfaces is noted, or the light around is owed the lit image (`mirror_flush`). +unsafe fn mirror_at_draw(list: *mut c_void) { + if !super::mirror::any() { + return; + } + let (pso, rt0, rect) = { + let g = recording(list as usize).lock().unwrap(); + let Some(s) = g.as_ref().and_then(|m| m.get(&(list as usize))) else { return }; + if s.list_type != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + let b = &s.bindings; + let rect = b.scissors.first().copied().or_else(|| { + b.viewports.first().map(|v| windows::Win32::Foundation::RECT { left: v.TopLeftX as i32, top: v.TopLeftY as i32, right: (v.TopLeftX + v.Width) as i32, bottom: (v.TopLeftY + v.Height) as i32 }) + }); + (s.bound_pso, b.render_targets.as_ref().and_then(|rt| rt.handles.first().copied()), rect) + }; + match super::mirror::part_of(pso) { + Some(super::mirror::Part::Mask) => { + let current: Vec = bound_render_targets(list).into_iter().filter_map(super::present::rtv_resource).collect(); + super::mirror::at_mask(¤t); + } + Some(super::mirror::Part::Sky) => { + let owed = rt0.and_then(|rtv| super::mirror::at_sky(rtv, rect)); + if let Some(s) = recording(list as usize).lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.mirror = owed; + } + } + None => {} + } +} + +/// The light around a mirror's view owed on `list` (`mirror_at_draw`), recorded here – a point +/// between the title's commands – with the title's state set again after it. +unsafe fn mirror_flush(list: *mut c_void) { + if !super::mirror::any() { + return; + } + let Some(p) = recording(list as usize).lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))).and_then(|s| s.mirror.take()) else { return }; + if super::mirror::light(list, &p) { + restore_after_internal_pass(list, true, false); + } +} + /// Apply a pending fallback `RSSetDepthBiasX` override before a draw call on `list`. pub(super) unsafe fn prepare_draw(list: *mut c_void) { depth_twins_before_work(list, true); + mirror_at_draw(list); if !DEPTH_BIAS_USED.load(Ordering::Acquire) { return; } @@ -4973,6 +5027,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.bindings = Bindings::default(); s.depth_in_step.clear(); s.depth_owed = Default::default(); + s.mirror = None; s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; super::title_textures::list_reset(this as usize); @@ -5008,6 +5063,9 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if barriers.is_null() || n == 0 { return; } + // (the light around a mirror's view, owed since its sky's draw, before the title moves its + // lit image to be read) + mirror_flush(this); let capture = super::capture::op(this, || Some(super::capture::barrier(&(0..n as usize).map(|k| barriers.add(k).read_unaligned()).collect::>()))); let mut out: Vec<[u32; 8]> = Vec::with_capacity(n as usize + 1); // a UAV barrier for all resources is in `out` / a transition from or to UNORDERED_ACCESS diff --git a/crates/xcl/src/hle/d3d12x/mirror.rs b/crates/xcl/src/hle/d3d12x/mirror.rs new file mode 100644 index 0000000000..e4cf3f9211 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/mirror.rs @@ -0,0 +1,771 @@ +//! Mirrors without the title's rays: light for a mirror's view. +//! +//! A retail title draws what a mirror shows as a second view of its own: the scene again from +//! behind the glass, into images of the view's size, lit by one full-screen draw for each kind of +//! material (`PS_MIRROR_PBR_MATERIAL_*`) into an image of its own, then the sky and the air +//! drawn into the same image (`ps_mirror_volumetric_sky`). That lighting takes its indirect +//! light from the probes the title's rays fill: without the rays the view has the sun's direct +//! light alone, and a room is black in it. +//! +//! So the light around times each texel's own colour is added to that lit image. The light +//! around is what the stand-in for the indirect light (`ambient`) gives the room itself: the +//! mean of the light gathered at its points (or of its cells, when the light is not made in +//! space) with a fifth of the picture's slow mean, at least the sky's level at its share +//! (`XCL_AMBIENT_SKY`) – so a wall in the mirror is about as bright as the wall beside it. It has +//! no direction: the view is seen from behind the glass, where the picture's points are not. The +//! colour is the view's own: at the draw that makes the view's material mask +//! (`ps_generate_material_mask`), the 8-bit colour target of its size drawn into last before it. +//! Where the view drew nothing that colour is black and nothing is added. +//! +//! Neo adds it right before the sky's draw. A draw here is bound in `bind` before XCL sees it +//! (`list_x::prepare_draw`), and a pass of XCL's cannot be put between that binding and the draw, +//! so the pass goes right after the sky's draw, at the next point between the title's commands +//! where XCL records (its next barriers, render targets or the list's close) – before the title +//! moves the lit image to be read. Only the air the sky's draw lays over the surfaces is then not +//! laid over the added light. +//! +//! `XCL_MIRROR_AMBIENT=` of that light (default 1; `0`: off). Nothing is added while +//! the stand-in is off or the title's rays run (`ambient::active`). +//! +//! Ported from VIctory-Neo (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later): +//! `crates/victory-gpu/src/mirror.rs` of a3af274 ("Mirrors: the mirror's view is given the light +//! around") and 9b61dc9 (its programs built in a test) – the programs' parts by name, the switch, +//! and the pass and its programs, adapted to XCL's level buffer, objects and state. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, RwLock}; + +use windows::core::{Interface, PCSTR}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// A pixel program's part in a mirror's view. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Part { + /// makes the view's material mask from its colour and depth + Mask, + /// draws the sky into the view's lit image, after the materials' lighting + Sky, +} + +/// The pixel program's part, by its name in the container. +fn part(container: &[u8]) -> Option { + let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name); + if has(b"ps_mirror_volumetric_sky") { + Some(Part::Sky) + } else if has(b"ps_generate_material_mask") { + Some(Part::Mask) + } else { + None + } +} + +/// The multiple of the light around a mirror's view is given (`XCL_MIRROR_AMBIENT`); 0: none. +pub(super) fn level() -> f32 { + static LEVEL: OnceLock = OnceLock::new(); + *LEVEL.get_or_init(|| parse(std::env::var("XCL_MIRROR_AMBIENT").ok().as_deref())) +} + +fn parse(set: Option<&str>) -> f32 { + match set.map(str::trim) { + None | Some("") => 1.0, + Some(v) => v.parse::().ok().filter(|l| l.is_finite() && *l >= 0.0).unwrap_or(1.0).min(16.0), + } +} + +/// The graphics pipelines (objects as the title has them) whose pixel program has a part. +static PARTS: RwLock>> = RwLock::new(None); +static ANY: AtomicBool = AtomicBool::new(false); + +/// A graphics pipeline `pso` was made with the pixel program `ps` (the console's container). +pub(super) fn note_graphics_pso(pso: usize, ps: Option<&[u8]>) { + if pso == 0 || level() == 0.0 { + return; + } + match ps.and_then(part) { + Some(p) => { + PARTS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, p); + ANY.store(true, Ordering::Release); + static SAID: AtomicU32 = AtomicU32::new(0); + if SAID.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: mirror: pipeline {pso:#x} draws a mirror view's {p:?}"); + } + } + // (another pipeline made at the address of one released) + None if ANY.load(Ordering::Relaxed) => { + if let Some(m) = PARTS.write().unwrap().as_mut() { + m.remove(&pso); + } + } + None => {} + } +} + +/// Whether a pipeline with a part was made: the gate of the draw hooks. +pub(super) fn any() -> bool { + ANY.load(Ordering::Relaxed) +} + +/// The part of the pipeline `pso` (the title's object, or what it resolves to). +pub(super) fn part_of(pso: usize) -> Option { + if pso == 0 { + return None; + } + let g = PARTS.read().unwrap(); + let m = g.as_ref()?; + m.get(&pso).or_else(|| m.get(&super::pso_async::resolve(pso))).copied() +} + +/// 8-bit colour formats (R8G8B8A8 TYPELESS, UNORM, UNORM_SRGB) and their rank as the colour of a +/// view's surfaces (the sRGB one first). +fn colour_rank(format: i32) -> Option { + match format { + 29 => Some(0), + 27 => Some(1), + 28 => Some(2), + _ => None, + } +} + +/// 2D 8-bit colour targets bound lately (newest first): (resource, width, height, format). +static TARGETS: Mutex> = Mutex::new(Vec::new()); +/// The colour of a view's surfaces as the last material mask of each size was made after it: +/// ((width, height), resource, frame). +static COLOUR: Mutex> = Mutex::new(Vec::new()); + +fn frame() -> u64 { + super::present::counters().1 +} + +/// (width, height, format) of a single-sample 2D texture `res`. +unsafe fn shape(res: usize) -> Option<(u32, u32, i32)> { + let r = res as *mut c_void; + let d = ID3D12Resource::from_raw_borrowed(&r)?.GetDesc(); + (d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && d.SampleDesc.Count == 1 && d.DepthOrArraySize == 1).then_some((d.Width as u32, d.Height, d.Format.0)) +} + +/// The title bound the render targets `rts` (resources). +pub(super) unsafe fn note_targets(rts: &[usize]) { + for &r in rts.iter().filter(|&&r| r != 0) { + let Some((w, h, f)) = shape(r).filter(|s| colour_rank(s.2).is_some()) else { continue }; + let mut g = TARGETS.lock().unwrap(); + g.retain(|t| t.0 != r); + g.insert(0, (r, w, h, f)); + g.truncate(8); + } +} + +/// The colour among `targets` (newest first) for a mask drawn into `current` (its targets, the +/// first one's size `size`): of that size, not one of `current`, the best rank, the newest. +fn pick_colour(targets: &[(usize, u32, u32, i32)], current: &[usize], size: Option<(u32, u32)>) -> Option<(usize, (u32, u32))> { + let fits = |t: &&(usize, u32, u32, i32)| !current.contains(&t.0) && size.is_none_or(|s| (t.1, t.2) == s); + let first = targets.iter().find(fits)?; + let size = (first.1, first.2); + targets.iter().filter(fits).filter(|t| (t.1, t.2) == size).min_by_key(|t| colour_rank(t.3)).map(|t| (t.0, size)) +} + +/// A draw that makes a view's material mask, into the targets `current` (resources). +pub(super) unsafe fn at_mask(current: &[usize]) { + let size = current.first().and_then(|&r| shape(r)).map(|s| (s.0, s.1)); + let picked = pick_colour(&TARGETS.lock().unwrap(), current, size); + let Some((colour, size)) = picked else { return }; + let mut g = COLOUR.lock().unwrap(); + g.retain(|c| c.0 != size); + g.push((size, colour, frame())); + g.truncate(4); +} + +/// The pass owed a list (`at_sky`), recorded at its next point between the title's commands. +pub(super) struct Pending { + /// the render target view of the lit image, its resource and format + rtv: usize, + lit: usize, + format: DXGI_FORMAT, + size: (u32, u32), + /// the colour of the view's surfaces, its SRV format and whether it is decoded in the pass + colour: usize, + view: DXGI_FORMAT, + decode: bool, + rect: RECT, +} + +/// The format a pass of ours draws into a lit image of `format` with (None: not one it can). +fn lit_format(format: i32) -> Option { + Some(match format { + // R16G16B16A16 FLOAT / TYPELESS, R11G11B10_FLOAT, R32G32B32A32 FLOAT / TYPELESS + 10 | 9 => DXGI_FORMAT_R16G16B16A16_FLOAT, + 26 => DXGI_FORMAT_R11G11B10_FLOAT, + 2 | 1 => DXGI_FORMAT_R32G32B32A32_FLOAT, + _ => return None, + }) +} + +/// A draw of the sky into a view's lit image (render target view `rtv`, the draw's scissor +/// `rect`): the pass that gives the view the light around, owed, if one can be made. +pub(super) unsafe fn at_sky(rtv: usize, rect: Option) -> Option { + if level() == 0.0 || !super::ambient::active() { + return None; + } + let lit = super::present::rtv_resource(rtv)?; + let (w, h, f) = shape(lit)?; + let Some(format) = lit_format(f) else { + static SAID: AtomicBool = AtomicBool::new(false); + if !SAID.swap(true, Ordering::Relaxed) { + crate::xlog_info!("D3D12.X: mirror: a view's lit image of format {f} is not one the light around is added to"); + } + return None; + }; + let now = frame(); + let colour = COLOUR.lock().unwrap().iter().find(|c| c.0 == (w, h) && now.saturating_sub(c.2) <= 1).map(|c| c.1)?; + if colour == lit { + return None; + } + // (still named by a render target view: not released since, and still of the view's size) + let live = super::present::view_resource(colour)?; + let (cw, ch, cf) = shape(live.as_raw() as usize)?; + if (cw, ch) != (w, h) { + return None; + } + let (view, decode) = match cf { + 27 | 29 => (DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, false), + 28 => (DXGI_FORMAT_R8G8B8A8_UNORM, true), + _ => return None, + }; + let rect = rect.unwrap_or(RECT { left: 0, top: 0, right: w as i32, bottom: h as i32 }); + Some(Pending { rtv, lit, format, size: (w, h), colour, view, decode, rect }) +} + +/// What the pass reads and writes: 4 constants, then a table of the colour (t0) and the level +/// buffer (u1), read in both programs. +const SOURCE: &str = r#" +cbuffer Set : register(b0) { float level; float decode; float sky_share; float sky_ready; }; +Texture2D colour : register(t0); +RWStructuredBuffer sky_level : register(u1); +// The level buffer as `ambient` lays it out: the sky's level, the slow mean of the cells, 64x36 +// cells, their places, then 160x90 points of three entries, each colour's light in `w`. +#define CELL_AT 2 +#define POINT_AT 4610 +#define PX 160 +struct Corner { + float4 at : SV_Position; + nointerpolation float3 around : AROUND; +}; +float3 finite(float3 c) { + return all(isfinite(c)) ? max(c, 0.0) : float3(0.0, 0.0, 0.0); +} +// The light around, once for the triangle: the mean of one point (or cell) in a hundred or so, +// with a fifth of the picture's slow mean, at least the sky's level at its share. +Corner corner(uint i : SV_VertexID) { + Corner c; + c.at = float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0); + float4 mean = sky_level[1]; + float3 around = float3(0.0, 0.0, 0.0); + if (mean.a > 0.0) { + float3 points = float3(0.0, 0.0, 0.0), cells = float3(0.0, 0.0, 0.0); + [loop] + for (uint y = 0; y < 9; y++) { + [loop] + for (uint x = 0; x < 16; x++) { + uint at0 = POINT_AT + ((y * 10 + 5) * PX + x * 10 + 5) * 3; + points += finite(float3(sky_level[at0].w, sky_level[at0 + 1].w, sky_level[at0 + 2].w)); + cells += finite(sky_level[CELL_AT + (y * 4 + 2) * 64 + x * 4 + 2].rgb); + } + } + // (the points are gathered while the light is made in space; else the cells) + float3 room = dot(points, float3(1.0, 1.0, 1.0)) > 0.0 ? points / 144.0 : cells / 144.0; + around = clamp(lerp(room, finite(mean.rgb), 0.2), 0.0, 16.0); + } + float3 sky = sky_ready > 0.0 ? clamp(finite(sky_level[0].rgb), 0.0, 0.65) : float3(0.0, 0.0, 0.0); + c.around = max(around, sky * sky_share) * level; + return c; +} +float4 light(Corner at) : SV_Target { + float3 c = max(colour.Load(int3(int2(at.at.xy), 0)).rgb, 0.0); + if (decode > 0.0) c = pow(c, 2.2); + return float4(c * at.around, 0.0); +} +"#; + +fn compile(entry: &str, target: &str) -> Option> { + unsafe { + let mut blob = None; + let (e, t) = (format!("{entry}\0"), format!("{target}\0")); + let r = D3DCompile(SOURCE.as_ptr() as *const c_void, SOURCE.len(), PCSTR::null(), None, None, PCSTR(e.as_ptr()), PCSTR(t.as_ptr()), 0, 0, &mut blob, None); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +/// The pass's root signature, serialized: [0] 4 constants (b0), [1] a table of t0 and u1. +fn root_signature() -> Option { + let ranges = [ + D3D12_DESCRIPTOR_RANGE { RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, NumDescriptors: 1, BaseShaderRegister: 0, RegisterSpace: 0, OffsetInDescriptorsFromTableStart: 0 }, + D3D12_DESCRIPTOR_RANGE { RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, NumDescriptors: 1, BaseShaderRegister: 1, RegisterSpace: 0, OffsetInDescriptorsFromTableStart: 1 }, + ]; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 } }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: ranges.len() as u32, pDescriptorRanges: ranges.as_ptr() } }, + }, + ]; + let mut blob = None; + unsafe { D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC { NumParameters: params.len() as u32, pParameters: params.as_ptr(), ..Default::default() }, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).ok()? }; + blob +} + +/// Method `slot` of the D3D12 object `obj`: past XCL's hooks when XCL adopted it +/// (`real::orig_fn`), as it is otherwise. +unsafe fn method(obj: *mut c_void, slot: usize) -> usize { + if super::real::is_adopted(obj) { + super::real::orig_fn(obj, slot) + } else { + *(*(obj as *const *const usize)).add(slot) + } +} + +/// Descriptor groups (t0, u1) of a pass in its heap, used in turn. +const GROUPS: u32 = 64; + +struct Pass { + rs: ID3D12RootSignature, + vs: Vec, + ps: Vec, + /// one pipeline for each format of a lit image met + made: Mutex)>>, + heap: ID3D12DescriptorHeap, + cpu: usize, + gpu: u64, + step: u32, + next: AtomicU32, +} + +// D3D12 objects are free-threaded +unsafe impl Send for Pass {} +unsafe impl Sync for Pass {} + +static PASSES: Mutex>>>> = Mutex::new(None); + +/// The pass on `dev`, made the first time (None: it could not be). +unsafe fn pass_on(dev: *mut c_void) -> Option> { + let mut g = PASSES.lock().unwrap(); + g.get_or_insert_with(HashMap::new) + .entry(dev as usize) + .or_insert_with(|| { + let p = make_pass(dev).map(Arc::new); + if p.is_none() { + crate::xlog_warn!("D3D12.X: mirror: the pass that gives a mirror's view the light around could not be made"); + } + p + }) + .clone() +} + +unsafe fn make_pass(dev: *mut c_void) -> Option { + let (vs, ps, blob) = (compile("corner", "vs_5_0")?, compile("light", "ps_5_0")?, root_signature()?); + type CreateRs = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + type CreateHeap = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + type Increment = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + let create_rs: CreateRs = std::mem::transmute(method(dev, 16)); + let create_heap: CreateHeap = std::mem::transmute(method(dev, 14)); + let increment: Increment = std::mem::transmute(method(dev, 15)); + let mut rs = std::ptr::null_mut(); + if create_rs(dev, 0, blob.GetBufferPointer(), blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const _, &mut rs) < 0 || rs.is_null() { + return None; + } + let rs = ID3D12RootSignature::from_raw(rs); + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + let desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: kind, NumDescriptors: 2 * GROUPS, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 }; + let mut heap = std::ptr::null_mut(); + if create_heap(dev, &desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut heap) < 0 || heap.is_null() { + return None; + } + let heap = ID3D12DescriptorHeap::from_raw(heap); + let (cpu, gpu) = (heap.GetCPUDescriptorHandleForHeapStart().ptr, heap.GetGPUDescriptorHandleForHeapStart().ptr); + Some(Pass { rs, vs, ps, made: Mutex::default(), heap, cpu, gpu, step: increment(dev, kind), next: AtomicU32::new(0) }) +} + +impl Pass { + /// The pipeline that adds into a target of `format` on `dev`. + unsafe fn pipeline(&self, dev: *mut c_void, format: DXGI_FORMAT) -> Option { + let mut made = self.made.lock().unwrap(); + if let Some((_, p)) = made.iter().find(|m| m.0 == format.0) { + return p.clone(); + } + let p = self.make(dev, format); + if p.is_none() { + crate::xlog_warn!("D3D12.X: mirror: no pipeline to add the light around into a lit image of format {}", format.0); + } + made.push((format.0, p.clone())); + p + } + + unsafe fn make(&self, dev: *mut c_void, format: DXGI_FORMAT) -> Option { + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as *const c_void, BytecodeLength: b.len() }; + let mut blend = D3D12_BLEND_DESC::default(); + // what is there, plus ours (its alpha kept) + blend.RenderTarget[0] = D3D12_RENDER_TARGET_BLEND_DESC { + BlendEnable: true.into(), + SrcBlend: D3D12_BLEND_ONE, + DestBlend: D3D12_BLEND_ONE, + BlendOp: D3D12_BLEND_OP_ADD, + SrcBlendAlpha: D3D12_BLEND_ZERO, + DestBlendAlpha: D3D12_BLEND_ONE, + BlendOpAlpha: D3D12_BLEND_OP_ADD, + RenderTargetWriteMask: 0xF, + ..Default::default() + }; + let mut formats = [DXGI_FORMAT_UNKNOWN; 8]; + formats[0] = format; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(self.rs.clone())), + VS: code(&self.vs), + PS: code(&self.ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { DepthEnable: false.into(), StencilEnable: false.into(), ..Default::default() }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + type CreateGfx = unsafe extern "system" fn(*mut c_void, *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create: CreateGfx = std::mem::transmute(method(dev, 10)); + let mut p = std::ptr::null_mut(); + let hr = create(dev, &desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut p); + ManuallyDrop::drop(&mut desc.pRootSignature); + (hr >= 0 && !p.is_null()).then(|| ID3D12PipelineState::from_raw(p)) + } +} + +/// What one pass draws: into the render target view `rtv` (format `format`, `size`), within +/// `rect`, the colour `colour` (viewed as `view`, decoded with `decode`) times the light around +/// from `level_buf` (`elements` float4s) times `multiple`, the sky's level at `sky_share` when +/// `sky_ready`. +struct Draw<'a> { + rtv: usize, + format: DXGI_FORMAT, + size: (u32, u32), + rect: RECT, + colour: &'a ID3D12Resource, + view: DXGI_FORMAT, + decode: bool, + level_buf: &'a ID3D12Resource, + elements: u32, + multiple: f32, + sky_share: f32, + sky_ready: bool, +} + +/// Records `d` on `list` (of the device `dev`) with `pass`: it leaves a view heap, a root +/// signature, a pipeline, a render target, a viewport, a scissor and a topology of its own on +/// the list. The lit image is in RENDER_TARGET, the colour readable by pixel programs, the level +/// buffer in UNORDERED_ACCESS (or COMMON). False: nothing was recorded. +unsafe fn record(list: *mut c_void, dev: *mut c_void, pass: &Pass, d: &Draw) -> bool { + let Some(pso) = pass.pipeline(dev, d.format) else { return false }; + let g = pass.next.fetch_add(1, Ordering::Relaxed) % GROUPS; + let (cpu, gpu) = (pass.cpu + (2 * g * pass.step) as usize, pass.gpu + (2 * g * pass.step) as u64); + type CreateSrv = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUav = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrv = std::mem::transmute(method(dev, 18)); + let create_uav: CreateUav = std::mem::transmute(method(dev, 19)); + let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: d.view, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, ..Default::default() } }, + }; + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: d.elements, StructureByteStride: 16, ..Default::default() } }, + }; + create_srv(dev, d.colour.as_raw(), &srv, cpu); + create_uav(dev, d.level_buf.as_raw(), std::ptr::null_mut(), &uav, cpu + pass.step as usize); + + let barrier: unsafe extern "system" fn(*mut c_void, u32, *const [u32; 8]) = std::mem::transmute(method(list, 26)); + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(method(list, 28)); + let set_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(method(list, 30)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(method(list, 25)); + let set_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(method(list, 32)); + let set_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(method(list, 36)); + let set_targets: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(method(list, 46)); + let set_viewports: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(method(list, 21)); + let set_scissors: unsafe extern "system" fn(*mut c_void, u32, *const RECT) = std::mem::transmute(method(list, 22)); + let set_topology: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(method(list, 20)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(method(list, 12)); + + // (what `ambient` wrote into the level buffer, first) + let level = d.level_buf.as_raw() as usize; + barrier(list, 1, &[2, 0, level as u32, (level as u64 >> 32) as u32, 0, 0, 0, 0]); + let heap = pass.heap.as_raw() as usize; + set_heaps(list, 1, &heap); + set_rs(list, pass.rs.as_raw()); + set_pso(list, pso.as_raw()); + let consts = [d.multiple.to_bits(), if d.decode { 1.0f32 } else { 0.0 }.to_bits(), d.sky_share.to_bits(), if d.sky_ready { 1.0f32 } else { 0.0 }.to_bits()]; + set_consts(list, 0, 4, consts.as_ptr(), 0); + set_table(list, 1, gpu); + set_targets(list, 1, &d.rtv, 0, std::ptr::null()); + let vp = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: d.size.0 as f32, Height: d.size.1 as f32, MinDepth: 0.0, MaxDepth: 1.0 }; + set_viewports(list, 1, &vp); + set_scissors(list, 1, &d.rect); + set_topology(list, windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + draw(list, 3, 1, 0, 0); + true +} + +/// Passes recorded. +static LIT: AtomicU64 = AtomicU64::new(0); + +/// Records the pass `p` owed `list`. True: it was, and it left state of its own on the list +/// (`record`): the caller sets the title's again (`list_x::restore_after_internal_pass`). +pub(super) unsafe fn light(list: *mut c_void, p: &Pending) -> bool { + let multiple = level(); + // (both still named by a view: the title has not released them) + let (Some(lit), Some(colour)) = (super::present::view_resource(p.lit), super::present::view_resource(p.colour)) else { return false }; + let Some(dev) = super::list_x::device_of_list(list) else { return false }; + let Some((level_buf, elements, sky_share, sky_ready)) = super::ambient::level_for_mirror(&dev) else { return false }; + let Some(pass) = pass_on(dev.as_raw()) else { return false }; + let d = Draw { rtv: p.rtv, format: p.format, size: p.size, rect: p.rect, colour: &colour, view: p.view, decode: p.decode, level_buf: &level_buf, elements, multiple, sky_share, sky_ready }; + if !record(list, dev.as_raw(), &pass, &d) { + return false; + } + drop(lit); + let n = LIT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 3 || n.is_power_of_two() { + let r = p.rect; + crate::xlog_info!( + "D3D12.X: mirror: a mirror's view is given the light around (XCL_MIRROR_AMBIENT={multiple}): lit image {:#x} ({}x{}, format {}), colour {:#x} (view format {}), rect [{}, {}, {}, {}] ({n} so far)", + p.lit, + p.size.0, + p.size.1, + p.format.0, + p.colour, + p.view.0, + r.left, + r.top, + r.right, + r.bottom + ); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parts_by_name() { + assert_eq!(part(b"..ps_mirror_volumetric_sky_c35156a8_Wrapped.."), Some(Part::Sky)); + assert_eq!(part(b"..ps_generate_material_mask_e3b05401_Wrapped.."), Some(Part::Mask)); + // the other mirror programs are none of ours + assert_eq!(part(b"..ps_mirror_volumetric_scattering_transmittance_c35156a8.."), None); + assert_eq!(part(b"..ps_mirror_taa_default.."), None); + assert_eq!(part(b"..PS_MIRROR_PBR_MATERIAL_STANDARD.."), None); + } + + #[test] + fn levels() { + assert_eq!(parse(None), 1.0); + assert_eq!(parse(Some("")), 1.0); + assert_eq!(parse(Some("0")), 0.0); + assert_eq!(parse(Some(" 2.5 ")), 2.5); + assert_eq!(parse(Some("-1")), 1.0); + assert_eq!(parse(Some("x")), 1.0); + assert_eq!(parse(Some("100")), 16.0); + } + + #[test] + fn the_colour_is_the_newest_8_bit_target_of_the_masks_size_srgb_first() { + let t = |r: usize, w: u32, h: u32, f: i32| (r, w, h, f); + // newest first: the mask's own target, a UNORM and an sRGB one of the view's size, one + // of the picture's size + let targets = [t(1, 1280, 736, 28), t(2, 1280, 736, 28), t(3, 1280, 736, 29), t(4, 1280, 720, 29)]; + assert_eq!(pick_colour(&targets, &[1], Some((1280, 736))), Some((3, (1280, 736))), "the sRGB one before the newer UNORM one"); + assert_eq!(pick_colour(&targets, &[1, 3], Some((1280, 736))), Some((2, (1280, 736)))); + assert_eq!(pick_colour(&targets, &[], Some((1280, 720))), Some((4, (1280, 720)))); + assert_eq!(pick_colour(&targets, &[], Some((640, 360))), None, "none of the mask's size"); + // a mask with no colour target: the newest one's size + assert_eq!(pick_colour(&targets, &[], None), Some((3, (1280, 736)))); + assert_eq!(lit_format(10), Some(DXGI_FORMAT_R16G16B16A16_FLOAT)); + assert_eq!(lit_format(26), Some(DXGI_FORMAT_R11G11B10_FLOAT)); + assert_eq!(lit_format(28), None); + } + + /// Both programs of the pass compile with D3DCompile, and its root signature serializes + /// (VIctory-Neo 9b61dc9: the pass's programs are built in a test). + #[test] + fn the_pass_builds() { + assert!(compile("corner", "vs_5_0").is_some(), "the vertex program"); + assert!(compile("light", "ps_5_0").is_some(), "the pixel program"); + assert!(root_signature().is_some()); + } + + /// An IEEE half as f32. + fn half(h: u16) -> f32 { + let (s, e, m) = ((h >> 15) as u32, ((h >> 10) & 0x1F) as i32, (h & 0x3FF) as f32); + let v = match e { + 0 => m * 2f32.powi(-24), + 31 => f32::INFINITY, + _ => (1.0 + m / 1024.0) * 2f32.powi(e - 15), + }; + if s == 1 { -v } else { v } + } + + /// On the software adapter: a 4x4 lit image holding 0.1, the view's colour (0.5, 0.25, 1) in + /// an sRGB target, a level buffer whose points hold 1 and whose slow mean is 0.5: within the + /// left half the pass adds the colour times lerp(1, 0.5, 0.2) = 0.9, the right half and the + /// alpha stay as they were. + #[test] + fn gpu_the_light_around_is_added_into_the_lit_image_within_the_rect() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let mut dev: Option = None; + let Ok(warp) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)).and_then(|f| f.EnumWarpAdapter::()) else { + return crate::gpu::recomp::runner::skip_test("no WARP device"); + }; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no WARP device"); + } + let dev = dev.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let heap = |ty| D3D12_HEAP_PROPERTIES { Type: ty, ..Default::default() }; + let texture = |format, state| { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap(D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + r.unwrap() + }; + let buffer = |ty, bytes: u64, flags, state| { + 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: flags, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap(ty), D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + r.unwrap() + }; + let lit = texture(DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_STATE_RENDER_TARGET); + let colour = texture(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, D3D12_RESOURCE_STATE_RENDER_TARGET); + // the level buffer as `ambient` lays it out + const ELEMENTS: u32 = 2 + 2 * 64 * 36 + 3 * 160 * 90; + let mut words = vec![[0f32; 4]; ELEMENTS as usize]; + words[1] = [0.5, 0.5, 0.5, 1.0]; + words[2..2306].iter_mut().for_each(|c| *c = [0.25, 0.25, 0.25, 1.0]); + words[4610..].iter_mut().for_each(|p| *p = [0.0, 0.0, 0.0, 1.0]); + let bytes = (ELEMENTS as u64 * 16).next_multiple_of(256); + let up = buffer(D3D12_HEAP_TYPE_UPLOAD, bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::copy_nonoverlapping(words.as_ptr() as *const u8, p as *mut u8, words.len() * 16); + up.Unmap(0, None); + let level_buf = buffer(D3D12_HEAP_TYPE_DEFAULT, bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + let readback = buffer(D3D12_HEAP_TYPE_READBACK, 256 * 4, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + let rtvs: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 2, ..Default::default() }).unwrap(); + let rtv0 = rtvs.GetCPUDescriptorHandleForHeapStart(); + let rtv1 = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv0.ptr + dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize }; + dev.CreateRenderTargetView(&lit, None, rtv0); + dev.CreateRenderTargetView(&colour, None, rtv1); + let tr = |r: &ID3D12Resource, before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(r), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + ..Default::default() + }; + + list.ClearRenderTargetView(rtv0, &[0.1, 0.1, 0.1, 1.0], None); + list.ClearRenderTargetView(rtv1, &[0.5, 0.25, 1.0, 1.0], None); + list.CopyBufferRegion(&level_buf, 0, &up, 0, bytes); + list.ResourceBarrier(&[ + tr(&colour, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE), + tr(&level_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]); + let pass = make_pass(dev.as_raw()).expect("the pass"); + let d = Draw { + rtv: rtv0.ptr, + format: DXGI_FORMAT_R16G16B16A16_FLOAT, + size: (4, 4), + rect: RECT { left: 0, top: 0, right: 2, bottom: 4 }, + colour: &colour, + view: DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, + decode: false, + level_buf: &level_buf, + elements: ELEMENTS, + multiple: 1.0, + sky_share: 0.35, + sky_ready: false, + }; + assert!(record(list.as_raw(), dev.as_raw(), &pass, &d), "recorded"); + list.ResourceBarrier(&[tr(&lit, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R16G16B16A16_FLOAT, Width: 4, Height: 4, Depth: 1, RowPitch: 256 }, + }; + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&lit), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + let start = std::time::Instant::now(); + while fence.GetCompletedValue() < 1 { + assert!(start.elapsed().as_secs() < 20, "the software adapter did not finish"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let texel = |x: usize, y: usize| -> [f32; 4] { std::array::from_fn(|c| half(*(p as *const u16).add(y * 128 + x * 4 + c))) }; + let (inside, outside) = (texel(1, 2), texel(3, 1)); + readback.Unmap(0, None); + let want = [0.1 + 0.5 * 0.9, 0.1 + 0.25 * 0.9, 0.1 + 1.0 * 0.9, 1.0]; + for c in 0..4 { + assert!((inside[c] - want[c]).abs() < 0.02, "inside the rect: {inside:?}, wanted {want:?}"); + assert!((outside[c] - [0.1, 0.1, 0.1, 1.0][c]).abs() < 0.002, "outside it: {outside:?}"); + } + drop(alloc); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 7f8aec0b3e..91cb0d988c 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -38,6 +38,7 @@ pub mod layout; pub mod list_x; mod look_stats; mod lut3d; +mod mirror; pub mod null; mod placements; pub mod present; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4b5acce86e..a9c3f78ffb 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7371,6 +7371,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); + super::mirror::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); TRANSLATED_GRAPHICS.insert(*ppv as usize, ()); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); if (super::gpu_profile::on() || super::gpu_times::enabled()) && !super::present::trace_frame() { @@ -8910,6 +8911,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, "MS", riid, ppv); if hr >= 0 { super::ambient::note_graphics_pso(*ppv as usize, console_ps); + super::mirror::note_graphics_pso(*ppv as usize, console_ps); super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); if super::gpu_times::enabled() || trace_ms().is_some() || trace_record_all() { let ms_h = crate::gpu::shader::fnv64(ms); @@ -9037,6 +9039,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE let hr = finish_two_pass(this, &out, tp, rs, &ps_samplers, "GS", riid, ppv); if hr >= 0 { super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); + super::mirror::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); if super::gpu_times::enabled() { PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(gs), shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64))); From c06cf419128d3e05b28a02b47c043266bfed4415 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:29:02 +0100 Subject: [PATCH 066/175] D3D12.X: a GPU-written texture stays the GPU's over later page mappings A texture the title's GPU work copied into is not uploaded over from the title's memory when the CPU writes it: that memory never got the GPU's texels. A page mapping changed under it by a later CopyPageMappingsBatchX call (and a change of its source in a GPU view) still took it back and read it again from that memory. In a retail title's open world (RX 9070 XT, two runs) 64 such textures gave way in 240 s: 12 to 352 KiB with 8 to 10 levels, two or three written by one call and given way by one mapping call 100 to 1800 calls later - the shape of the characters' GPU-made head textures, whose skin and hair render black while eyes, hats and bodies are right. XCL_GPU_WRITE_STAYS (default on) keeps such a texture as the GPU left it until it is released, as over CPU writes; it still reads its new source from then on. =0 restores the give-way. Kept writes are logged now and then ("stays over the page mapping of call N"). VIctory-Neo does the same: a texture the host GPU copied into is never refilled from title memory (victory-gpu texture.rs, host_written / upload_from). Tests: a_gpu_write_counts_from_the_submit_of_its_list and gpu_mirror_upload_follows_cpu_writes_and_later_mapping_changes check both settings; new a_gpu_written_texture_stays_over_a_change_of_its_source. cargo test -p xcl --lib title_textures: 41 passed, 0 failed (RX 9070 XT). Not tested: the retail title (whether the heads are right again). (cherry picked from commit 53b26eed63e2965ab7f25a224c891268a072ac0f) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 126 +++++++++++++++++++- 1 file changed, 122 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index abd67ce736..a6e0cb4386 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -854,15 +854,51 @@ fn recheck_gpu_view_sources() { } } +/// `XCL_GPU_WRITE_STAYS=0`: a texture the title's GPU work wrote gives way to a later page +/// mapping or source change under it, and is read again from the title's memory. On (the +/// default), it stays as the GPU left it until it is released, as over CPU writes: that memory +/// never got the GPU's texels (the copy went to the PC texture), so reading it again put stale +/// bytes over them – a retail title's GPU-written character head textures (8 to 10 levels, 12 to +/// 352 KiB, two or three written by one call) gave way to the next mapping of their page and +/// were black from then on. VIctory-Neo keeps a texture the host GPU copied into the same way +/// (`texture::host_written`). +fn gpu_write_stays() -> bool { + #[cfg(test)] + if let Some(v) = tests::STAYS.with(|s| s.get()) { + return v; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GPU_WRITE_STAYS").map_or(true, |v| v.trim() != "0")) +} + +/// GPU writes kept over a page mapping and over a source change under them (`gpu_write_stays`) +static STAYED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// `e`, written by the GPU, stays the GPU's over a change of what is under it (`k`: 0 a page +/// mapping of call `call`, 1 its source): said now and then. +fn note_stayed(e: &Entry, k: usize, call: u64) { + let n = STAYED[k].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + let what = if k == 0 { format!("the page mapping of call {call}") } else { "a change of its source".into() }; + let levels = e.tex.texels().map_or(0, |s| s.chain.levels.len()); + crate::xlog_info!("D3D12.X: the GPU's write of the title texture at {:#x} ({} bytes, {levels} levels; written by call {}) stays over {what} under it (#{n}; XCL_GPU_WRITE_STAYS=0 reads it again from memory)", e.va, e.tex.size(), e.written_call); + } +} + /// The queue's page mappings changed `parts` (from, to) of `e` by call `call`. A texture read /// through its pages sends them again with its next upload, as known changes with no comparison /// (a clean pool page newly mapped holds bytes the PC texture never had): true, and it goes into /// AGAIN. A shadowed one goes up whole once it is uncovered, as on a change of its source. The -/// GPU's write of a list submitted at or after that call stays; an older one gives way. +/// GPU's write of a list submitted at or after that call stays; an older one stays too +/// (`gpu_write_stays`), or gives way. fn mapping_changed(e: &mut Entry, call: u64, parts: Vec<(usize, usize)>, active: bool) -> bool { if !e.paged || e.pending || (e.gpu_written && e.written_call >= call) { return false; } + if e.gpu_written && gpu_write_stays() { + note_stayed(e, 0, call); + return false; + } e.gpu_written = false; REREAD.fetch_add(1, Ordering::Relaxed); if !active { @@ -875,7 +911,7 @@ fn mapping_changed(e: &mut Entry, call: u64, parts: Vec<(usize, usize)>, active: } /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is -/// uploaded at the next submit. Whether it changed. +/// uploaded at the next submit (one the GPU wrote: not, `gpu_write_stays`). Whether it changed. fn recheck_source(e: &mut Entry) -> bool { if !e.in_gpu_view { return false; @@ -888,6 +924,10 @@ fn recheck_source(e: &mut Entry) -> bool { note_paged(e.va); } (e.src, e.paged) = (src, paged); + if e.gpu_written && !e.pending && gpu_write_stays() { + note_stayed(e, 1, 0); + return true; + } if !e.pending { e.pending = true; PENDING.fetch_add(1, Ordering::Relaxed); @@ -3757,9 +3797,18 @@ pub(super) mod tests { mark_hot(kept, PAGE); refresh(queue.as_raw()); assert_eq!(read_r8(dev, &queue, &paged), vec![0xA6; 64 * 64], "the GPU's"); + // a later mapping leaves it the GPU's (`gpu_write_stays`), or with that off takes it back + let _on = Stays::set(true); + map_pages(g, &[[0, 0, 1]], home, 2); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0xA6; 64 * 64], "the GPU's write stays over a later mapping"); + let _off = Stays::set(false); + map_pages(g, &[[0, 1, 1]], home, 2); + refresh(queue.as_raw()); + assert_eq!(read_r8(dev, &queue, &paged), vec![0xB7; 64 * 64], "a later mapping takes it back"); map_pages(g, &[[0, 0, 1]], home, 2); refresh(queue.as_raw()); - assert_eq!(read_r8(dev, &queue, &paged), vec![0x62; 64 * 64], "a later mapping takes it back"); + assert_eq!(read_r8(dev, &queue, &paged), vec![0x62; 64 * 64]); std::ptr::write_bytes(home as *mut u8, 0xC8, PAGE); mark_hot(home, PAGE); refresh(queue.as_raw()); @@ -3825,6 +3874,22 @@ pub(super) mod tests { thread_local! { /// the VirtualQuery calls `mirror_source` made on this thread pub(super) static QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// `gpu_write_stays` on this thread (None: as the environment says) + pub(super) static STAYS: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// `gpu_write_stays` is `on` on this thread while it lives. + struct Stays; + impl Stays { + fn set(on: bool) -> Stays { + STAYS.with(|s| s.set(Some(on))); + Stays + } + } + impl Drop for Stays { + fn drop(&mut self) { + STAYS.with(|s| s.set(None)); + } } /// One call of the queue's page-mapping method: `ranges` (kind, start, count) from GPU-view @@ -3942,7 +4007,16 @@ pub(super) mod tests { recheck_gpu_view_sources(); assert!(state().0, "the GPU's write came after the mapping"); assert_eq!(again(), (false, Again::Nothing)); - // a mapping changed by a later call takes it back + // a mapping changed by a later call leaves it the GPU's (`gpu_write_stays`) ... + let stays = STAYED[0].load(Ordering::Relaxed); + let _on = Stays::set(true); + map_pages(gpu, &[[0, 0, 1]], home, 2); + recheck_gpu_view_sources(); + assert!(state().0, "the GPU's write stays over a later mapping"); + assert_eq!(again(), (false, Again::Nothing), "nothing of it goes up again"); + assert!(STAYED[0].load(Ordering::Relaxed) > stays, "counted"); + // ... or, with that off, takes it back + let _off = Stays::set(false); map_pages(gpu, &[[2, 0, 1]], home, 2); recheck_gpu_view_sources(); assert!(!state().0, "an older GPU write gives way"); @@ -3968,6 +4042,50 @@ pub(super) mod tests { } } + /// A texture the GPU wrote keeps the GPU's texels when its source changes (here: a page is + /// named under one read through the CPU view) with `gpu_write_stays`: it reads the new source + /// from then on, and nothing goes up. With that off it goes up again, whole, from there. + #[test] + fn a_gpu_written_texture_stays_over_a_change_of_its_source() { + use crate::hle::kernelx::mirrors::PAGE; + let _guard = TEST_LOCK.lock().unwrap(); + // (no submit looks while a texture of no resource is in the table) + let _refresh = REFRESH.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(183 * PAGE, 2); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + assert_eq!(tex.size() as usize, PAGE); + // keys of no resource, never dereferenced + let (on, off) = (0x7E57_0000_9000usize, 0x7E57_0000_A000usize); + for (res, at) in [(on, gpu), (off, gpu + 2 * PAGE)] { + assert_eq!(source_of(at, PAGE), (cpu + (at - gpu), false), "read through the CPU view"); + let e = Entry { device: 0, va: at, src: cpu + (at - gpu), in_gpu_view: true, paged: false, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, written_call: 0, placed: false, unmapped: false, seq: 0, known: Default::default(), target: false }; + TEXTURES.lock().unwrap().insert(res, e); + TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); + } + let state = |res: usize| TEXTURES.lock().unwrap().by_res.get(&res).map(|e| (e.src, e.paged, e.pending, e.gpu_written)).unwrap(); + recheck_gpu_view_sources(); + let stays = STAYED[1].load(Ordering::Relaxed); + { + let _on = Stays::set(true); + map_pages(gpu, &[[0, 0, 1]], home, 2); + recheck_gpu_view_sources(); + } + assert_eq!(state(on), (gpu, true, false, true), "the new source, and still the GPU's"); + assert!(STAYED[1].load(Ordering::Relaxed) > stays, "counted"); + { + let _off = Stays::set(false); + map_pages(gpu + 2 * PAGE, &[[0, 1, 1]], home, 2); + recheck_gpu_view_sources(); + } + assert_eq!(state(off), (gpu + 2 * PAGE, true, true, true), "it goes up again, whole, from the new source"); + forget(on); + forget(off); + drop_paged_views(cpu, gpu, pages); + } + } + /// A texture read through its pages finds its written pages through the GPU-view pages a /// write reaches: a write where a mapped page is kept, and one in the CPU view under a page /// the queue's page mappings never named; those that differ from what went up are sent. From 02ceae6499f27b8614ceb7ff3dc28bb8ea0446f2 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:33:43 +0100 Subject: [PATCH 067/175] D3D12.X: compare the pages a mapping changed under a texture before upload When CopyPageMappingsBatchX changed the pages under a texture read through its pages, those 64 KiB pages went up again with no comparison: no write watch fires for a clean pool page newly mapped. In a retail title's open world (RX 9070 XT) about 4400 textures per 1024 submits were read again that way ("25294 read again for a mapping changed under them" by 127 s), next to 7903 uploads of 2082 MB that took 1890 ms of the 1024 submits. The changed parts are now compared, page by page, with the hashes of what the PC texture got at its last upload (the same comparison CPU- written pages get; a page whose hash is not known differs), and only pages that differ go up. A page mapped again with the bytes the texture has (the same page after an unmap, a page moved in its pool) costs a hash instead of an upload. A render target or UAV texture, and one the GPU wrote that gives way, still sends its pages with no comparison. VIctory-Neo does the same: a remapped slot is digested again and only uploaded when its bytes differ. XCL_TEXTURE_REMAP_COMPARE=0 restores the old behaviour; on by default. A line every 1024 submits that upload says what went up and for what: whole textures, CPU-written pages, remapped pages, parts sent again behind another queue (count and MB each), how many remapped textures were compared and left out, and the GPU writes kept by XCL_GPU_WRITE_STAYS. It gives the breakdown the 2 GB could only be estimated from before. Tests: new title_textures::tests::remapped_pages_are_compared_with_what_ they_held. cargo test -p xcl --lib -- title_textures texture_upload: 53 passed, 0 failed (RX 9070 XT). Not measured on the title. (cherry picked from commit 01ec624f32b33c2f4115f677781432b498471111) --- crates/xcl/src/hle/d3d12x/texture_upload.rs | 26 +++ crates/xcl/src/hle/d3d12x/title_textures.rs | 183 ++++++++++++++++++-- 2 files changed, 199 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index 46201de8d7..c11f7fccc8 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -78,6 +78,9 @@ pub(super) struct Pages { last: Vec, /// what goes up again, and the uploads it has to come behind (`sent`) again: Option<(Change, Vec)>, + /// parts (from, to) a mapping changed under since they were last looked at: compared with + /// what they held at its next upload, as written pages are (`recheck`) + recheck: Vec<(usize, usize)>, } /// Where an upload went: the queue, the fence of that queue's uploads and the value behind it. @@ -108,6 +111,7 @@ pub(super) fn all_sent(known: &Known, src: usize, size: usize) { k.hashes.clear(); k.hashes.resize(pages_of(src, size), 0); k.again = None; + k.recheck.clear(); } /// Nothing is known about what the PC texture holds: its next upload is of all of it. @@ -158,6 +162,28 @@ pub(super) fn stale(known: &Known, parts: Vec<(usize, usize)>) { }); } +/// `parts` of a texture (from, to) show other pages now (a mapping changed under them): its next +/// upload compares their bytes with what its pages held when they last went up, as for written +/// pages (`take_recheck`), and sends only those that differ. A page whose hash is not known (0) +/// differs; what is known of a page is what the PC texture got (`Hashes::note`), so equal bytes +/// are what it holds there. +pub(super) fn recheck(known: &Known, parts: Vec<(usize, usize)>) { + known.lock().unwrap().recheck.extend(parts); +} + +/// The pages of a texture at `src` to compare at this upload (`recheck`): their addresses, sorted. +pub(super) fn take_recheck(known: &Known, src: usize) -> Vec { + let parts = std::mem::take(&mut known.lock().unwrap().recheck); + let mut out: Vec = parts + .into_iter() + .filter(|r| r.0 < r.1) + .flat_map(|(from, to)| ((src + from) / PAGE * PAGE..src + to).step_by(PAGE)) + .collect(); + out.sort_unstable(); + out.dedup(); + out +} + /// `changed` of a texture (None: all of it) went up on `to`. An older upload of the texture on /// another queue that has not run yet (and that `to`'s queue has not waited for: `waited`) can land /// over it: it goes up again, behind that one (`take_again`). True when there is such a thing. diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index a6e0cb4386..df48fc7e08 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -53,6 +53,10 @@ struct Due { whole: bool, /// what of it goes up again (`texture_upload::sent`) again: texture_upload::Change, + /// the pages a mapping changed under it, to be compared (`texture_upload::recheck`) + recheck: Vec, + /// the CPU wrote one of its pages since its last upload + written: bool, /// (`Entry::target`) target: bool, /// where its pages are read (`Entry::paged`) @@ -886,9 +890,10 @@ fn note_stayed(e: &Entry, k: usize, call: u64) { } /// The queue's page mappings changed `parts` (from, to) of `e` by call `call`. A texture read -/// through its pages sends them again with its next upload, as known changes with no comparison -/// (a clean pool page newly mapped holds bytes the PC texture never had): true, and it goes into -/// AGAIN. A shadowed one goes up whole once it is uncovered, as on a change of its source. The +/// through its pages compares them with what they held at its next upload (`remap_compare`; no +/// write watch fires for a clean pool page newly mapped, whose bytes the PC texture may never have +/// had), or sends them again with no comparison: true, and it goes into AGAIN. A shadowed one goes +/// up whole once it is uncovered, as on a change of its source. The /// GPU's write of a list submitted at or after that call stays; an older one stays too /// (`gpu_write_stays`), or gives way. fn mapping_changed(e: &mut Entry, call: u64, parts: Vec<(usize, usize)>, active: bool) -> bool { @@ -899,17 +904,39 @@ fn mapping_changed(e: &mut Entry, call: u64, parts: Vec<(usize, usize)>, active: note_stayed(e, 0, call); return false; } - e.gpu_written = false; + let was_gpu_written = std::mem::take(&mut e.gpu_written); REREAD.fetch_add(1, Ordering::Relaxed); if !active { e.pending = true; PENDING.fetch_add(1, Ordering::Relaxed); return false; } - texture_upload::stale(&e.known, parts); + // (a render target or UAV the GPU may have written: no comparison with what the CPU's bytes + // were; nor one the GPU wrote, whose pages' hashes are not what it holds) + if remap_compare() && !e.target && !was_gpu_written { + texture_upload::recheck(&e.known, parts); + } else { + texture_upload::stale(&e.known, parts); + } true } +/// `XCL_TEXTURE_REMAP_COMPARE=0`: the pages a mapping changed under a texture go up again with no +/// comparison. On (the default), they are compared with what they held when they last went up, +/// as written pages are, and only those that differ go up. A title's streaming can map pages with +/// the bytes a texture already has (the same page again after an unmap, a page moved within its +/// pool); in a retail title's open world about 4400 textures a 1024 submits were read again for a +/// mapping changed under them, next to 7903 uploads of 2 GB in all. VIctory-Neo does the same: a +/// remapped slot is digested again and uploaded only when its bytes differ. +fn remap_compare() -> bool { + #[cfg(test)] + if let Some(v) = tests::REMAP_COMPARE.with(|s| s.get()) { + return v; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TEXTURE_REMAP_COMPARE").map_or(true, |v| v.trim() != "0")) +} + /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is /// uploaded at the next submit (one the GPU wrote: not, `gpu_write_stays`). Whether it changed. fn recheck_source(e: &mut Entry) -> bool { @@ -2029,6 +2056,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { return None; }; let mut again = texture_upload::Change::None; + let mut recheck = Vec::new(); if waiting.contains(&res) && !e.gpu_written { let (queue, waited) = target.on(e.device); match texture_upload::take_again(&e.known, queue, waited) { @@ -2036,11 +2064,13 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { texture_upload::Again::NotYet => drop(later.insert(res)), texture_upload::Again::Nothing => {} } + recheck = texture_upload::take_recheck(&e.known, e.src); } - let wanted = whole || again != texture_upload::Change::None || (!e.gpu_written && { + let written = !e.gpu_written && { let i = dirty.partition_point(|&p| p + page as usize <= e.src); dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) - }); + }; + let wanted = whole || again != texture_upload::Change::None || !recheck.is_empty() || written; if !wanted { return None; } @@ -2052,7 +2082,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { let p = res as *mut c_void; // (its pages resolved once, for all reads of this upload) let pages = if e.paged { page_map(e.va, e.tex.size() as usize, true) } else { None }; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (active, Due { res: r.clone(), device: e.device, src: e.src, tex: Arc::clone(&e.tex), states: e.states.clone(), known: Arc::clone(&e.known), whole, again, target: e.target, pages })) + ID3D12Resource::from_raw_borrowed(&p).map(|r| (active, Due { res: r.clone(), device: e.device, src: e.src, tex: Arc::clone(&e.tex), states: e.states.clone(), known: Arc::clone(&e.known), whole, again, recheck, written, target: e.target, pages })) }) .collect(); AGAIN.lock().unwrap().extend(later); @@ -2068,6 +2098,42 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { static UNCHANGED: AtomicU64 = AtomicU64::new(0); +/// What an upload is for (`UPLOADS_FOR`). +#[derive(Clone, Copy)] +enum Why { + /// all of it: a new texture, a source changed, one uncovered or tried again + Whole, + /// pages the CPU wrote that differ + Written, + /// pages a mapping changed under it that differ (`remap_compare`), or sent with no comparison + Remapped, + /// parts sent again behind another queue's upload (`texture_upload::sent`) + Again, +} + +/// [textures, bytes] that went up for each `Why` since the last `upload_line_now` +static UPLOADS_FOR: [[AtomicU64; 2]; 4] = [const { [AtomicU64::new(0), AtomicU64::new(0)] }; 4]; +/// textures whose remapped pages were compared, and those of them (with no CPU-written page) +/// found holding what they held +static REMAPS_COMPARED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// `upload_all` calls with something to upload +static UPLOAD_CALLS: AtomicU64 = AtomicU64::new(0); + +/// Every 1024 submits that upload: what went up, and for what. +fn upload_line_now() { + if UPLOAD_CALLS.fetch_add(1, Ordering::Relaxed) % 1024 != 1023 { + return; + } + let take = |c: &AtomicU64| c.swap(0, Ordering::Relaxed); + let [whole, written, remapped, again] = UPLOADS_FOR.each_ref().map(|w| (take(&w[0]), take(&w[1]) as f64 / (1u64 << 20) as f64)); + let held = take(&REMAPS_COMPARED[1]); + let compared = take(&REMAPS_COMPARED[0]) + held; + crate::xlog_info!( + "title texture uploads in the last 1024 submits that uploaded: {} whole ({:.1} MB: new textures, sources changed, uncovered); {} for CPU-written pages ({:.1} MB); {} for pages a mapping changed under them ({:.1} MB); {} sent again behind another queue ({:.1} MB); textures remapped: {compared} compared, {held} of them held what they held (left out); GPU writes kept so far over mappings {}, over source changes {}", + whole.0, whole.1, written.0, written.1, remapped.0, remapped.1, again.0, again.1, STAYED[0].load(Ordering::Relaxed), STAYED[1].load(Ordering::Relaxed) + ); +} + /// `XCL_TEXTURE_PARTS=0`: a texture that changed goes up as a whole. fn upload_parts() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -2516,6 +2582,7 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option // The written pages that hold what they held at their texture's last upload are nothing to do: // the write watch is per page and a title writes next to its textures (and rewrites what it // wrote). + let any = !todo.is_empty(); let t = std::time::Instant::now(); let mut changes: std::collections::VecDeque = { let pages: Vec> = todo @@ -2529,10 +2596,11 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option // it would go up in part as it was and in part as it is; not for one read through // its pages, whose own address is not watched) let also = if mine.is_empty() || d.pages.is_some() || all_hot(d.src, size) { Vec::new() } else { written_pages(d.src, size) }; - if also.iter().all(|p| mine.binary_search(p).is_ok()) { + if d.recheck.is_empty() && also.iter().all(|p| mine.binary_search(p).is_ok()) { return mine.into(); } - let mut all = [mine, &also].concat(); + // (and the pages a mapping changed under it) + let mut all = [mine, &also, &d.recheck].concat(); all.sort_unstable(); all.dedup(); all.into() @@ -2555,6 +2623,17 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option }; let mut todo = todo.into_iter().filter_map(|d| { let change = if d.whole { texture_upload::Change::All } else { changes.pop_front()? }; + let found = change != texture_upload::Change::None; + let why = match () { + _ if d.whole => Why::Whole, + _ if d.written && found => Why::Written, + _ if !d.recheck.is_empty() && found => Why::Remapped, + _ => Why::Again, + }; + if !d.whole && !d.recheck.is_empty() { + // (the pages of one with no CPU-written ones held what they held: none of them goes up) + REMAPS_COMPARED[usize::from(!d.written && !found)].fetch_add(1, Ordering::Relaxed); + } let changed = match texture_upload::join(change, d.again.clone()) { texture_upload::Change::None => return None, texture_upload::Change::All => None, @@ -2579,6 +2658,8 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option let volume = d.tex.texels().is_some_and(|s| s.depth > 0); let parts = changed.as_ref().filter(|_| !volume); let bytes = parts.map_or(size, |p| p.iter().map(|r| (r.1.div_ceil(BLOCK) - r.0 / BLOCK) * BLOCK).sum::().min(size)); + UPLOADS_FOR[why as usize][0].fetch_add(1, Ordering::Relaxed); + UPLOADS_FOR[why as usize][1].fetch_add(bytes as u64, Ordering::Relaxed); Some((d, changed, bytes)) }).peekable(); while todo.peek().is_some() { @@ -2645,6 +2726,9 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option } } } + if any { + upload_line_now(); + } } /// textures of batches that could not be uploaded, and when they are tried again @@ -3876,6 +3960,8 @@ pub(super) mod tests { pub(super) static QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// `gpu_write_stays` on this thread (None: as the environment says) pub(super) static STAYS: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// `remap_compare` on this thread (None: as the environment says) + pub(super) static REMAP_COMPARE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// `gpu_write_stays` is `on` on this thread while it lives. @@ -4086,6 +4172,79 @@ pub(super) mod tests { } } + /// The pages a mapping changed under a texture read through its pages are compared with what + /// they held at its last upload (`remap_compare`): a page with the same bytes sends nothing, + /// other bytes and an unmapped page go up. With the comparison off, and for a render target, + /// they go up as they are. + #[test] + fn remapped_pages_are_compared_with_what_they_held() { + use crate::hle::kernelx::mirrors::PAGE; + use texture_upload::{Again, Change}; + let _guard = TEST_LOCK.lock().unwrap(); + // (no submit looks while a texture of no resource is in the table) + let _refresh = REFRESH.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(185 * PAGE, 3); + // pool pages 0 and 1 hold the same bytes, page 2 others + std::ptr::write_bytes(home as *mut u8, 0x3C, 2 * PAGE); + std::ptr::write_bytes((home + 2 * PAGE) as *mut u8, 0x4D, PAGE); + map_pages(gpu, &[[0, 0, 1]], home, 3); + map_pages(gpu + PAGE, &[[0, 0, 1]], home, 3); + recheck_gpu_view_sources(); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + assert_eq!(tex.size() as usize, PAGE); + // keys of no resource, never dereferenced: a texture, a render target + let (res, rt) = (0x7E57_0000_B000usize, 0x7E57_0000_C000usize); + let known: texture_upload::Known = Default::default(); + let rt_known: texture_upload::Known = Default::default(); + for (r, at, k, target) in [(res, gpu, &known, false), (rt, gpu + PAGE, &rt_known, true)] { + texture_upload::all_sent(k, at, PAGE); + let e = Entry { device: 0, va: at, src: at, in_gpu_view: true, paged: true, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, placed: false, unmapped: false, seq: 0, known: Arc::clone(k), target }; + TEXTURES.lock().unwrap().insert(r, e); + TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); + } + let all: Vec = (gpu..gpu + PAGE).step_by(0x1000).collect(); + // what an upload compares (and remembers) + let look = |dirty: &[usize]| { + let m = page_map(gpu, PAGE, false).unwrap(); + texture_upload::changed(&[texture_upload::Written { src: gpu, size: PAGE, dirty, known: &known, pages: Some(&m) }], true).0.remove(0) + }; + let whole = Change::Parts(vec![(0, PAGE)]); + assert_eq!(look(&all), whole, "nothing known of it yet: all of it differs"); + REMAP_COMPARE.with(|c| c.set(Some(true))); + let remap = |ranges: &[[u32; 3]]| { + map_pages(gpu, ranges, home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&res), "due at the next upload"); + assert_eq!(texture_upload::take_again(&known, 0, 0), Again::Nothing, "nothing sent with no comparison"); + let pages = texture_upload::take_recheck(&known, gpu); + assert_eq!(pages, all, "its pages under the mapping, to compare"); + look(&pages) + }; + assert_eq!(remap(&[[0, 1, 1]]), Change::None, "a page with the same bytes: nothing goes up"); + assert_eq!(remap(&[[0, 2, 1]]), whole, "other bytes go up"); + assert_eq!(remap(&[[2, 0, 1]]), whole, "unmapped: zeros"); + // a render target goes up as it is + map_pages(gpu + PAGE, &[[0, 1, 1]], home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&rt)); + assert_eq!(texture_upload::take_again(&rt_known, 0, 0), Again::Now(whole.clone()), "a render target: with no comparison"); + assert!(texture_upload::take_recheck(&rt_known, gpu + PAGE).is_empty()); + // and so does everything with the comparison off + REMAP_COMPARE.with(|c| c.set(Some(false))); + map_pages(gpu, &[[0, 0, 1]], home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&res)); + assert_eq!(texture_upload::take_again(&known, 0, 0), Again::Now(whole), "off: with no comparison"); + assert!(texture_upload::take_recheck(&known, gpu).is_empty()); + REMAP_COMPARE.with(|c| c.set(None)); + forget(res); + forget(rt); + drop_paged_views(cpu, gpu, pages); + } + } + /// A texture read through its pages finds its written pages through the GPU-view pages a /// write reaches: a write where a mapped page is kept, and one in the CPU view under a page /// the queue's page mappings never named; those that differ from what went up are sent. @@ -5252,6 +5411,8 @@ pub(super) mod tests { known: Default::default(), whole, again: texture_upload::Change::None, + recheck: Vec::new(), + written: false, target: false, pages: None, }; @@ -5360,6 +5521,8 @@ pub(super) mod tests { known: Default::default(), whole, again: texture_upload::Change::None, + recheck: Vec::new(), + written: false, target: false, pages: None, }; From 0b985d7e064e6719004d5042e7d4731e611c2481 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:39:24 +0100 Subject: [PATCH 068/175] D3D12.X: a texture made over a GPU-written one keeps the GPU's texels A texture the title places at the range of one its GPU work wrote, with the same description, shares that texture's video memory (vram::Pages tiles or the small-texture slot of the range): on the console it shows the memory, which holds the GPU's texels. Its first upload read the title's memory instead, which never got them, and wrote it over the shared video memory - the old texture's texels too. VIctory-Neo names this lead ("a placed texture view lies in the memory of a texture the host copied into: it is filled from title memory, which the copy never reached", victory-gpu texture.rs placed_in_host_written). Such a texture now starts GPU-written (no first upload, no CPU-write uploads, all levels given pages with XCL_TEXTURE_LEVEL_PAGES), under XCL_GPU_WRITE_INHERIT (default on; =0 uploads it from memory as before). Only an active old texture counts: its range's video memory is shared for certain. The risk: a title that gives the memory to new texels while the old texture still lives gets the GPU's old ones for the new texture. Each case is logged now and then (also with the switch off, "reads the memory") and counted in the upload line, so a run shows whether it happens at all. Tests: placed_title_textures_share_vram_and_preserve_pixels gains the case (RX 9070 XT). cargo test -p xcl --lib -- title_textures texture_upload: 53 passed, 0 failed. Not tested: the retail title. (cherry picked from commit 4407578c5af02f51f35857199662c593b3016764) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 84 +++++++++++++++++++-- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index df48fc7e08..177c56f0f7 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -640,7 +640,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, note_paged(va); } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); - let e = Entry { + let mut e = Entry { device: device as usize, va, src, @@ -658,8 +658,19 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, target: u32::from_le_bytes(desc[0x30..0x34].try_into().unwrap()) & 0x7 != 0, }; let (hot_src, hot_bytes) = (e.src, e.tex.size() as usize); + // (Some: made over a texture the GPU wrote; whether it keeps the GPU's texels) + let mut over_gpu_write = None; let to_unmap = { let mut t = TEXTURES.lock().unwrap(); + // a texture made over one the GPU wrote, at its range with its description, shares its + // video memory: it holds the GPU's texels, as the memory does on the console (`over_gpu_written`) + if let Some(call) = over_gpu_written(&t, res, &e) { + let keep = gpu_write_inherit(); + if keep { + (e.gpu_written, e.written_call, e.pending) = (true, call, false); + } + over_gpu_write = Some(keep); + } let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); @@ -669,12 +680,53 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, for r in &to_unmap { super::vram::unmap_superseded(r); } + if let Some(keep) = over_gpu_write { + let n = STAYED[2].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + let what = if keep { "keeps the GPU's texels instead of reading the memory (XCL_GPU_WRITE_INHERIT=0 reads it)" } else { "reads the memory (XCL_GPU_WRITE_INHERIT=1 keeps the GPU's texels)" }; + crate::xlog_info!("D3D12.X: a texture made at {va:#x} ({hot_bytes} bytes) over one the GPU wrote, with its description, {what} (#{n})"); + } + } + if over_gpu_write == Some(true) { + // (lazy levels: all of them get their pages, as for a GPU write) + if super::vram::level_pages() { + if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { + super::vram::map_levels(r, None); + } + } + } TEXTURES_GEN.fetch_add(1, Ordering::Release); // the data the title is about to write there is for the next submit mark_hot(hot_src, hot_bytes); Ok(()) } +/// `XCL_GPU_WRITE_INHERIT=0`: a texture made over one the GPU wrote (`over_gpu_written`) goes up +/// from the title's memory as any new texture, over the shared video memory. On (the default), +/// it starts as the GPU's: it holds the GPU's texels, as the memory does on the console, and the +/// CPU's writes there do not go up over them. If the title gives the memory to new texels while +/// the old texture still lives, those do not reach it either (count: the upload line). +fn gpu_write_inherit() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GPU_WRITE_INHERIT").map_or(true, |v| v.trim() != "0")) +} + +/// The written call of an active texture the GPU wrote that `e`, PC texture `res`, is made over: +/// both placed on the video memory of their range (`vram`: shared tiles or slot), the same +/// range, and the same PC description (the same texels where they are). None for any other. +unsafe fn over_gpu_written(t: &Table, res: *mut c_void, e: &Entry) -> Option { + if !e.placed { + return None; + } + let end = e.va + e.tex.size() as usize; + let desc = ID3D12Resource::from_raw_borrowed(&res)?.GetDesc(); + t.active_overlaps(e.va, end).into_iter().find_map(|(ova, ores, oend)| { + let o = t.by_res.get(&ores).filter(|o| ova == e.va && oend == end && o.placed && !o.unmapped && o.gpu_written && o.tex.mips == e.tex.mips)?; + let p = ores as *mut c_void; + (ID3D12Resource::from_raw_borrowed(&p)?.GetDesc() == desc).then_some(o.written_call) + }) +} + /// Where a texture at `va` is read from: the CPU view behind a GPU view (`kernelx::mirrors`) /// when nothing is mapped at `va` itself, else `va`. A physical page mapped at `va` counts /// before its first use too, while it is still reserved memory (`kernelx::physical_page_at`). @@ -875,8 +927,9 @@ fn gpu_write_stays() -> bool { *ON.get_or_init(|| std::env::var("XCL_GPU_WRITE_STAYS").map_or(true, |v| v.trim() != "0")) } -/// GPU writes kept over a page mapping and over a source change under them (`gpu_write_stays`) -static STAYED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// GPU writes kept over a page mapping and over a source change under them (`gpu_write_stays`), +/// and textures made over GPU-written ones (`over_gpu_written`) +static STAYED: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; /// `e`, written by the GPU, stays the GPU's over a change of what is under it (`k`: 0 a page /// mapping of call `call`, 1 its source): said now and then. @@ -2129,8 +2182,8 @@ fn upload_line_now() { let held = take(&REMAPS_COMPARED[1]); let compared = take(&REMAPS_COMPARED[0]) + held; crate::xlog_info!( - "title texture uploads in the last 1024 submits that uploaded: {} whole ({:.1} MB: new textures, sources changed, uncovered); {} for CPU-written pages ({:.1} MB); {} for pages a mapping changed under them ({:.1} MB); {} sent again behind another queue ({:.1} MB); textures remapped: {compared} compared, {held} of them held what they held (left out); GPU writes kept so far over mappings {}, over source changes {}", - whole.0, whole.1, written.0, written.1, remapped.0, remapped.1, again.0, again.1, STAYED[0].load(Ordering::Relaxed), STAYED[1].load(Ordering::Relaxed) + "title texture uploads in the last 1024 submits that uploaded: {} whole ({:.1} MB: new textures, sources changed, uncovered); {} for CPU-written pages ({:.1} MB); {} for pages a mapping changed under them ({:.1} MB); {} sent again behind another queue ({:.1} MB); textures remapped: {compared} compared, {held} of them held what they held (left out); GPU writes kept so far over mappings {}, over source changes {}; textures made over GPU-written ones {}", + whole.0, whole.1, written.0, written.1, remapped.0, remapped.1, again.0, again.1, STAYED[0].load(Ordering::Relaxed), STAYED[1].load(Ordering::Relaxed), STAYED[2].load(Ordering::Relaxed) ); } @@ -5065,6 +5118,27 @@ pub(super) mod tests { refresh(queue.as_raw()); assert_eq!(read_sub(&same_a, 0), subresources(base + 0x1000, &xg::Texture::new(&same_desc).unwrap())[0].data, "row 6: releasing newer placement reactivates older one"); drop(same_a); + // (a2) A texture made over one the GPU wrote, at its range with its description, holds + // the GPU's texels (the memory never got them; here: what went up before the write) + let gw_a = place_tex(base + 0x1000, &same_desc); + write_tiled(base + 0x1000, &same_desc, 0x4D); + refresh(queue.as_raw()); + let want_4d = subresources(base + 0x1000, &xg::Texture::new(&same_desc).unwrap()).swap_remove(0).data; + let list = 0x7E57_0000_D000usize; + note_gpu_write(list, gw_a.as_raw() as usize); + submitted(&[list as *mut c_void]); + list_reset(list); + write_tiled(base + 0x1000, &same_desc, 0x5E); + refresh(queue.as_raw()); + assert_eq!(read_sub(&gw_a, 0), want_4d, "the GPU's, not the memory's"); + let made = STAYED[2].load(Ordering::Relaxed); + let gw_b = place_tex(base + 0x1000, &same_desc); + refresh(queue.as_raw()); + assert!(TEXTURES.lock().unwrap().by_res.get(&(gw_b.as_raw() as usize)).is_some_and(|e| e.gpu_written && !e.pending), "the GPU's from the start"); + assert!(STAYED[2].load(Ordering::Relaxed) > made, "counted"); + assert_eq!(read_sub(&gw_b, 0), want_4d, "made over a GPU-written texture: the GPU's texels, not the memory's"); + drop(gw_b); + drop(gw_a); // (b) Partial / different-range overlap (row 5 + unmap dead tail + remap on release): let old_desc = console_desc(3, 512, 512, 1, 1, 28, 0x109); // 1 MiB From f78e50873157f71f67f77d646fb40f177b60f467 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:47:21 +0100 Subject: [PATCH 069/175] D3D12.X: recycle released reserved sampled textures by description and state Port of xcl-dev/xcl PR #2436 (cd1c1d8d, merged on main as 7d96cad2, by Saintwolf), adapted to amd-dev's vram.rs. Streamed sampled textures placed on shared 64 KiB video-memory pages call CreateReservedResource and GetResourceTiling for every placement (0.6-1.7 ms a texture on AMD drivers, #1268). The retail title places 300 to 950 textures every 2 s in its open world ("925 placed textures in 224 ms"). A bounded per-device pool (512 idle, FIFO eviction) keeps released reserved sampled textures keyed by exact D3D12_RESOURCE_DESC and the uniform state they were left in (title_textures::forget now returns it). When late_release has let the queues pass a texture's batch, vram::recycle_ready unmaps its tiles and parks it behind the tile-mapping queue's fence; a matching place_on_pages takes it with QueryInterface and its cached tile count instead of CreateReservedResource (and GetResourceTiling when its levels do not get pages one by one). Textures that got private data or a name are never reused (SetPrivateData, SetPrivateDataInterface and SetName are hooked for that in real.rs). Differences from the PR: amd-dev's vram::forget keeps its small-texture path and becomes forget_for_recycle; only a texture still mapped at its release is kept (one a superseding placement unmapped may still have that unmap waiting for the queues, unmap_placed); Pages::bind takes the physical pages here. XCL_RESERVED_POOL=0 turns it off; on by default as upstream. Tests: the PR's five tests (pool order and eviction, the mapping mark, GPU reuse and remap, private data excluded). cargo test -p xcl --lib -- d3d12x::vram d3d12x::title_textures d3d12x::texture_upload d3d12x::late_release d3d12x::real: 207 passed, 1 failed, 1 ignored (RX 9070 XT); the failure, real::release_tests::the_last_release_drops_ entries_before_the_object_goes, fails the same way on f33df5a7. (cherry picked from commit 3765d6119c7d98f686d22a6e4f68b4462570bf60) --- crates/xcl/src/hle/d3d12x/late_release.rs | 8 +- crates/xcl/src/hle/d3d12x/real.rs | 40 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 34 +- crates/xcl/src/hle/d3d12x/vram.rs | 632 +++++++++++++++++++- 4 files changed, 679 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index a37d72b75e..12a24d3c71 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -145,7 +145,7 @@ pub unsafe fn hold(res: usize, pinned: bool) { std::hint::spin_loop(); drain_known(false); } - if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { + if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) && !super::vram::pending_recycles() { return; } BUSY.found(Instant::now()); @@ -218,6 +218,7 @@ pub fn hold_unmap(res: ID3D12Resource) { /// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the /// upload ones. pub unsafe fn drain_known(seal_now: bool) { + super::vram::drain_recycled(); if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } @@ -264,9 +265,14 @@ pub unsafe fn drain_known(seal_now: bool) { super::sparse::forget_buffer(res); super::placements::gone(res); super::small_tex::gone(res); + // (a reserved sampled texture kept for a later placement of its kind: not released) + if super::vram::recycle_ready(res) { + continue; + } let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res as *mut c_void, 2)); f(res as *mut c_void); } + super::vram::drain_recycled(); } #[cfg(test)] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9c3f78ffb..2938f51235 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2179,6 +2179,32 @@ pub(super) fn note_title_address(res: usize, va: usize) { /// resources whose Map gave their unified-memory address (no PC mapping to undo) static UNMAPPABLE: Mutex>> = Mutex::new(None); +/// resources that got private data or a name (`SetPrivateData`, `SetPrivateDataInterface`, +/// `SetName`): not kept for reuse (`vram::park_recyclable`), so no payload or reference they hold +/// reaches a later texture +static PRIVATE_DATA: Mutex>> = Mutex::new(None); + +fn note_private_data(this: *mut c_void, hr: HRESULT) -> HRESULT { + if hr >= 0 { + PRIVATE_DATA.lock().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); + } + hr +} + +unsafe extern "system" fn res_set_private_data(this: *mut c_void, guid: *const GUID, size: u32, data: *const c_void) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *const GUID, u32, *const c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "SetPrivateData"))); + note_private_data(this, f(this, guid, size, data)) +} + +unsafe extern "system" fn res_set_private_data_interface(this: *mut c_void, guid: *const GUID, data: *const c_void) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *const GUID, *const c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "SetPrivateDataInterface"))); + note_private_data(this, f(this, guid, data)) +} + +unsafe extern "system" fn res_set_name(this: *mut c_void, name: *const u16) -> HRESULT { + let f: unsafe extern "system" fn(*mut c_void, *const u16) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "SetName"))); + note_private_data(this, f(this, name)) +} unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c_void) { if UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { @@ -2230,11 +2256,12 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { m.remove(&(this as usize)); } + let had_private_data = PRIVATE_DATA.lock().unwrap().as_mut().is_some_and(|s| s.remove(&(this as usize))); // (a held placed buffer still maps its tiles: unpinned by `late_release` when it lets it go) if !held { super::sparse::forget_buffer(this as usize); } - super::vram::forget(this as usize); + let recycle = super::vram::forget_for_recycle(this as usize, held); // (a held one is gone when `late_release` lets it go) if !held { super::placements::gone(this as usize); @@ -2244,8 +2271,12 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::barrier_groups::forget(this as usize); super::format_alias::forget(this as usize); super::ambient::forget_resource(this as usize); - super::title_textures::forget(this as usize); + let state = super::title_textures::forget(this as usize); super::lut3d::forget(this as usize); + // (a reserved sampled texture: kept for a placement of its description and last state) + if let (Some(info), Some(state), false) = (recycle, state, had_private_data) { + super::vram::park_recyclable(this as usize, info, state.0 as u32); + } let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); // a buffer may be over a heap of pages that are freed next; a texture, and a buffer of XCL's // in video memory (or over a GPU view's tiles), is not @@ -4138,6 +4169,9 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::CommandAllocator => v.extend_from_slice(&[("Release", alloc_release as usize), ("Reset", alloc_reset as usize)]), Kind::Resource => v.extend_from_slice(&[ ("Release", res_release as usize), + ("SetPrivateData", res_set_private_data as usize), + ("SetPrivateDataInterface", res_set_private_data_interface as usize), + ("SetName", res_set_name as usize), ("Map", res_map as usize), ("Unmap", res_unmap as usize), ("WriteToSubresource", res_write_to_subresource as usize), @@ -4615,7 +4649,7 @@ unsafe fn desc_of(res: *mut c_void) -> Option { ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()) } -unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESULT { +pub(super) unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESULT { if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { if let Some(d) = desc_of(*ppv) { RESERVED.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, d); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 177c56f0f7..9fab961022 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -479,17 +479,19 @@ impl Table { } /// Remove `res` on COM release, reactivating any shadowed older textures it uncovered (newest - /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap)`. - fn remove(&mut self, res: usize) -> (bool, isize, Vec) { + /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap, uniform_state)`: the + /// last one the state all its subresources were left in, when they share one. + fn remove(&mut self, res: usize) -> (bool, isize, Vec, Option) { if let Some(old) = self.shadowed.remove(&res) { self.shadowed_by_va.remove(&(old.va, res)); self.undisplace(res, &old); if self.shadowed.is_empty() { self.max_shadowed_size = 0; } - return (true, 0, Vec::new()); + return (true, 0, Vec::new(), (old.states.len() == 1).then(|| old.states[0])); } - let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new()) }; + let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new(), None) }; + let state = (old.states.len() == 1).then(|| old.states[0]); self.unlink_src(res, old.src, old.tex.size() as usize, !old.gpu_written); self.by_va.remove(&(old.va, res)); let mut pending_delta = if old.pending { -1 } else { 0 }; @@ -533,7 +535,7 @@ impl Table { if self.shadowed.is_empty() { self.max_shadowed_size = 0; } - (true, pending_delta, to_remap) + (true, pending_delta, to_remap, state) } fn get_mut(&mut self, res: usize) -> Option<&mut Entry> { @@ -1103,16 +1105,17 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { } } -/// The PC texture was released for good. -pub fn forget(res: usize) { +/// The PC texture was released for good. The state all its subresources were left in, when they +/// share one (`vram::park_recyclable`). +pub fn forget(res: usize) -> Option { STREAM_RECHECK.lock().unwrap().remove(&res); - let (removed, to_remap) = { + let (removed, to_remap, state) = { let mut t = TEXTURES.lock().unwrap(); - let (removed, delta, remap_ptrs) = t.remove(res); + let (removed, delta, remap_ptrs, state) = t.remove(res); adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); - (removed, unsafe { clone_resources(&remap_ptrs) }) + (removed, unsafe { clone_resources(&remap_ptrs) }, state) }; for r in &to_remap { unsafe { @@ -1126,6 +1129,7 @@ pub fn forget(res: usize) { if removed { TEXTURES_GEN.fetch_add(1, Ordering::Release); } + state } /// Whether a draw's descriptor tables might name a shadowed texture. @@ -4709,12 +4713,12 @@ pub(super) mod tests { assert_eq!((delta, unmap), (0, vec![1, 2, 20])); assert!(tbl.by_res.contains_key(&3) && tbl.by_res.contains_key(&4)); // Releasing 4 uncovers newest non-overlapping shadowed entries (1 and 20) and requests remap. - let (removed, delta, mut remap) = tbl.remove(4); + let (removed, delta, mut remap, _) = tbl.remove(4); remap.sort_unstable(); assert_eq!((removed, delta, remap), (true, 1, vec![1, 20])); assert!(tbl.by_res.contains_key(&1) && tbl.by_res.contains_key(&20) && tbl.shadowed.contains_key(&2)); // Releasing 20 uncovers 2; releasing middle of a 3-chain still uncovers oldest when top goes. - let (removed, _, remap) = tbl.remove(20); + let (removed, _, remap, _) = tbl.remove(20); assert_eq!((removed, remap), (true, vec![2])); assert!(tbl.by_res.contains_key(&2)); assert_eq!(tbl.insert(5, entry(0x10_8000, &tex_64k, true, true)).0, 1); @@ -4768,7 +4772,7 @@ pub(super) mod tests { assert_eq!(tbl.uncover(2, 1), Some((0, false))); assert!(tbl.shadowed.contains_key(&1) && !tbl.shadowed[&1].unmapped); assert!(tbl.displaced[&1].whole && tbl.shadowed[&1].pending, "1 still goes up at the next submit"); - let (removed, _, remap) = tbl.remove(2); + let (removed, _, remap, _) = tbl.remove(2); assert_eq!((removed, remap), (true, vec![])); assert!(tbl.by_res.contains_key(&1)); @@ -4806,7 +4810,7 @@ pub(super) mod tests { assert_eq!(dirty_tbl.coarse.get(&block_a), Some(&1)); assert_eq!(dirty_tbl.uncover(20, 9), Some((0, false))); assert_eq!((dirty_tbl.coarse.get(&block_a), dirty_tbl.coarse.get(&block_b)), (Some(&1), Some(&1)), "linked once each"); - assert_eq!(dirty_tbl.remove(21), (true, 0, vec![])); + assert_eq!(dirty_tbl.remove(21), (true, 0, vec![], Some(D3D12_RESOURCE_STATE_COMMON))); assert!(dirty_tbl.displaced.is_empty() && !dirty_tbl.coarse.contains_key(&block_a)); } @@ -4853,7 +4857,7 @@ pub(super) mod tests { assert!(COARSE_GEN.load(Ordering::Acquire) > gen, "the watched ranges are made again"); // released, a GPU-written texture takes nothing from another's count t.insert(4, entry(0x40_0000, a, &tex_16k, false)); - assert_eq!(t.remove(1), (true, 0, vec![])); + assert_eq!(t.remove(1), (true, 0, vec![], Some(D3D12_RESOURCE_STATE_COMMON))); assert_eq!(t.coarse, BTreeMap::from([(block(a), 1)])); // a displaced texture the GPU writes leaves its block, and takes nothing more once it is no diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 126745a2ae..b0e09c4f1c 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -131,18 +131,251 @@ pub(super) fn is_placed_texture(resource: usize) -> bool { } pub(super) fn forget(resource: usize) { + let _ = forget_for_recycle(resource, false); +} + +/// `forget` at the last release of `resource`: with `held` (`late_release` lets it go once the +/// queues are past it), what it takes to keep a reserved sampled texture of `Pages` for a later +/// placement of its description and state instead (`park_recyclable`, `recycle_ready`). +pub(super) fn forget_for_recycle(resource: usize, held: bool) -> Option { let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); - if placed { - if !super::vram_small::forget(resource) { - forget_pages(resource); + if !placed { + return None; + } + let info = if super::vram_small::forget(resource) { None } else { forget_pages(resource, held) }; + if let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { + ARENAS.lock().unwrap().release(id, std::time::Instant::now()); + } + super::placements::released(resource); + info +} + +/// Maximum idle reserved sampled textures kept per device for reuse (#1268). +/// Reserved resources hold no backing memory of their own (tiles are unmapped when parked). +const RESERVED_POOL_MAX: usize = 512; + +fn reserved_pool_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_RESERVED_POOL").ok().as_deref() != Some("0")) +} + +/// Exact description and uniform D3D12 resource state of a recyclable reserved sampled texture. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +struct ReservedKey { + dimension: i32, + alignment: u64, + width: u64, + height: u32, + depth_or_array: u16, + mip_levels: u16, + format: i32, + sample_count: u32, + sample_quality: u32, + flags: i32, + state: u32, +} + +impl ReservedKey { + fn from_desc(desc: &D3D12_RESOURCE_DESC, state: u32) -> Self { + Self { + dimension: desc.Dimension.0, + alignment: desc.Alignment, + width: desc.Width, + height: desc.Height, + depth_or_array: desc.DepthOrArraySize, + mip_levels: desc.MipLevels, + format: desc.Format.0, + sample_count: desc.SampleDesc.Count, + sample_quality: desc.SampleDesc.Quality, + flags: desc.Flags.0, + state, + } + } +} + +/// Bounded per-device pool of idle reserved sampled textures keyed by `(desc, state)`. +/// FIFO eviction caps the number of idle `ID3D12Resource` wrappers; evicted raw pointers are +/// returned to the caller so COM `Release` runs outside `PAGES.lock()`. +struct ReservedPool { + by_key: std::collections::HashMap>, + order: std::collections::VecDeque<(ReservedKey, usize, u64)>, + live_gen: std::collections::HashMap, + next_gen: u64, + cap: usize, +} + +impl ReservedPool { + fn new(cap: usize) -> Self { + Self { + by_key: std::collections::HashMap::new(), + order: std::collections::VecDeque::new(), + live_gen: std::collections::HashMap::new(), + next_gen: 0, + cap, + } + } + + fn compact_order(&mut self) { + if self.live_gen.is_empty() { + self.order.clear(); + return; + } + while let Some(&(_, raw, gen)) = self.order.front() { + if self.live_gen.get(&raw) == Some(&gen) { + break; + } + self.order.pop_front(); + } + if self.order.len() > self.live_gen.len().saturating_mul(2).max(16) { + self.order.retain(|&(_, raw, gen)| self.live_gen.get(&raw) == Some(&gen)); + } + } + + fn take(&mut self, key: &ReservedKey) -> Option<(usize, u32)> { + let bucket = self.by_key.get_mut(key)?; + let (raw, total, _gen) = bucket.pop()?; + if bucket.is_empty() { + self.by_key.remove(key); + } + self.live_gen.remove(&raw); + self.compact_order(); + Some((raw, total)) + } + + fn push(&mut self, key: ReservedKey, raw: usize, total: u32) -> Option { + if self.cap == 0 { + return Some(raw); + } + let mut evicted = None; + while self.live_gen.len() >= self.cap { + let Some((old_key, old_raw, old_gen)) = self.order.pop_front() else { break }; + if self.live_gen.get(&old_raw) != Some(&old_gen) { + continue; + } + self.live_gen.remove(&old_raw); + if let Some(bucket) = self.by_key.get_mut(&old_key) { + if let Some(pos) = bucket.iter().position(|&(r, _, g)| r == old_raw && g == old_gen) { + bucket.swap_remove(pos); + if bucket.is_empty() { + self.by_key.remove(&old_key); + } + } + } + evicted = Some(old_raw); + break; + } + let gen = self.next_gen; + self.next_gen = self.next_gen.wrapping_add(1); + self.live_gen.insert(raw, gen); + self.by_key.entry(key).or_default().push((raw, total, gen)); + self.order.push_back((key, raw, gen)); + self.compact_order(); + evicted + } +} + +/// Owns a retired reserved texture until the tile-mapping queue passes its last update mark. +struct PendingRecycle { + key: ReservedKey, + raw: usize, + total: u32, + mark: u64, +} + +fn promote_pending( + pool: &mut ReservedPool, + pending: &mut std::collections::VecDeque, + completed: u64, +) -> Vec { + let mut evicted = Vec::new(); + while pending.front().is_some_and(|item| item.mark <= completed) { + let item = pending.pop_front().unwrap(); + if let Some(old) = pool.push(item.key, item.raw, item.total) { + evicted.push(old); } - if let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { - ARENAS.lock().unwrap().release(id, std::time::Instant::now()); + } + evicted +} + +/// Metadata for a released reserved sampled texture awaiting GPU completion in `late_release`. +#[derive(Clone, Copy)] +pub(super) struct RecycleInfo { + dev_key: usize, + key: ReservedKey, + total: u32, + was_mapped: bool, +} + +static PARKING: Mutex>> = Mutex::new(None); +static PENDING_RECYCLES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub(super) fn pending_recycles() -> bool { + PENDING_RECYCLES.load(std::sync::atomic::Ordering::Acquire) != 0 +} + +/// Promotes retired textures whose tile-mapping fence mark has completed into `ReservedPool`. +/// COM `Release` of any evicted pool entries runs outside `PAGES.lock()`. +pub(super) unsafe fn drain_recycled() { + if !pending_recycles() { + return; + } + let mut evicted = Vec::new(); + { + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + let before = pages.pending_recycles.len(); + evicted.extend(promote_pending( + &mut pages.reserved_pool, + &mut pages.pending_recycles, + pages.fence.GetCompletedValue(), + )); + PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release); } - super::placements::released(resource); + } + for old in evicted { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(old as *mut c_void, 2)); + f(old as *mut c_void); } } +/// `resource`, released with `info` (`forget_for_recycle`), was last in `final_state`: it is kept +/// for a placement with its description in that state once `late_release` lets it go. +pub(super) fn park_recyclable(resource: usize, mut info: RecycleInfo, final_state: u32) { + info.key.state = final_state; + PARKING.lock().unwrap().get_or_insert_with(std::collections::HashMap::new).insert(resource, info); +} + +/// Called by `late_release` once every live GPU queue is past the batch containing `resource`. +/// Returns `true` when `resource` was retained for later reuse after its tile-mapping queue mark +/// completes (so `late_release` must not call `Release` on it). +pub(super) unsafe fn recycle_ready(resource: usize) -> bool { + let Some(info) = PARKING.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) else { + return false; + }; + if !reserved_pool_enabled() { + return false; + } + { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&info.dev_key) else { + return false; + }; + if info.was_mapped { + if let Some(res) = ID3D12Resource::from_raw_borrowed(&(resource as *mut c_void)) { + pages.unmap(res, info.total); + } + } + pages.pending_recycles.push_back(PendingRecycle { + key: info.key, + raw: resource, + total: info.total, + mark: pages.value, + }); + PENDING_RECYCLES.fetch_add(1, std::sync::atomic::Ordering::Release); + } + true +} + /// Whether a console texture with these D3D12_RESOURCE_FLAGS is the GPU's (render target, /// depth buffer, UAV). pub fn gpu_owned(flags: u32) -> bool { @@ -240,6 +473,8 @@ struct Target { levels: Option, /// placed as GPU-owned: its pages are keyed by the physical page under them (`page_key`) gpu_owned: bool, + /// a reserved sampled texture kept for reuse once released (`ReservedPool`) by this key + recycle: Option, } /// The tiles of a texture whose levels get video memory when an upload first has texels for @@ -884,6 +1119,10 @@ struct Pages { waited: std::collections::HashMap, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// idle reserved sampled textures kept for reuse by `(desc, state)` (#1268) + reserved_pool: ReservedPool, + /// retired reserved textures held until the tile-mapping queue passes their unmap fence mark + pending_recycles: std::collections::VecDeque, /// reusable scratch buffers for `map()` scratch_heaps: Vec, scratch_flags: Vec, @@ -938,6 +1177,8 @@ impl Pages { targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), reservable_cache: std::collections::HashMap::new(), + reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), + pending_recycles: std::collections::VecDeque::new(), scratch_heaps: Vec::new(), scratch_flags: Vec::new(), scratch_offsets: Vec::new(), @@ -1512,10 +1753,18 @@ unsafe fn place_on_pages( } }; let dev_key = dev.as_raw() as usize; + let recycle_key = (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()).then(|| ReservedKey::from_desc(&tiled, state)); + let mut pooled = None; let is_reservable = { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; - *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)) + let ok = *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)); + if ok { + if let Some(key) = recycle_key { + pooled = pages.reserved_pool.take(&key); + } + } + ok }; if !is_reservable { log("no tiled support for its format or sample count"); @@ -1523,11 +1772,37 @@ unsafe fn place_on_pages( } // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize. - let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); - if hr < 0 || (*ppv).is_null() { - log(&format!("{hr:#x}")); - return None; + // A released one of the same description and state is taken again instead (`ReservedPool`). + let mut cached_total = None; + if let Some((pooled_raw, total)) = pooled { + type QiFn = unsafe extern "system" fn(*mut c_void, *const windows_sys::core::GUID, *mut *mut c_void) -> HRESULT; + type RelFn = unsafe extern "system" fn(*mut c_void) -> u32; + let qi: QiFn = std::mem::transmute(super::real::orig_fn(pooled_raw as *mut c_void, 0)); + let rel: RelFn = std::mem::transmute(super::real::orig_fn(pooled_raw as *mut c_void, 2)); + let hr = qi(pooled_raw as *mut c_void, riid, ppv); + rel(pooled_raw as *mut c_void); + if hr >= 0 && !(*ppv).is_null() { + super::real::note_reserved(hr, ppv); + cached_total = Some(total); + static REUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = REUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() && n >= 16 { + crate::xlog_info!("D3D12.X: reserved texture pool: {n} reused (skipped CreateReservedResource)"); + } + } else { + *ppv = std::ptr::null_mut(); + } } + let hr = if cached_total.is_some() { + 0 + } else { + let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); + if hr < 0 || (*ppv).is_null() { + log(&format!("{hr:#x}")); + return None; + } + hr + }; let raw = *ppv; let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; @@ -1535,6 +1810,9 @@ unsafe fn place_on_pages( let (levels, n) = level_tiling(dev, res, desc.MipLevels as u32); total = n; levels.filter(|_| total > 0 && owned_pages(va, console_bytes, total as usize).is_some()) + } else if let Some(n) = cached_total { + total = n; + None } else { dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); None @@ -1546,10 +1824,10 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used: Vec::new(), used_extra: Vec::new(), levels, gpu_owned: require_aligned }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used: Vec::new(), used_extra: Vec::new(), levels, gpu_owned: require_aligned, recycle: recycle_key }); true } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total, &phys) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, levels: None, gpu_owned: require_aligned }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, levels: None, gpu_owned: require_aligned, recycle: recycle_key }); true } else { false @@ -1681,21 +1959,26 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { } /// A resource released: its pages are no longer its. -fn forget_pages(resource: usize) { +fn forget_pages(resource: usize, held: bool) -> Option { let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); - for pages in g.values_mut().flatten() { + for (&dev_key, slot) in g.iter_mut() { + let Some(pages) = slot.as_mut() else { continue }; let Some(t) = pages.targets.remove(&resource) else { continue }; if let Some(l) = &t.levels { LEVEL_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_sub(t.total as u64, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); } + // (only one still mapped is kept: one a superseding placement unmapped may have its unmap + // still waiting for the queues, `unmap_placed`) + let keep = (held && t.mapped && reserved_pool_enabled()).then_some(t.recycle).flatten().map(|key| RecycleInfo { dev_key, key, total: t.total, was_mapped: t.mapped }); if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); } - return; + return keep; } + None } /// Reclaimed heaps waiting for `unmap_mark` (if any) and every live queue's fence mark on one device. @@ -3426,4 +3709,321 @@ mod tests { pool.drain_cooling_before(t_stall, Some(t0 + std::time::Duration::from_millis(2500))); assert_eq!(pool.free_total, 2); } + + #[test] + fn reserved_pool_reuses_matching_key_isolates_state_and_evicts_fifo() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 9, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_BC1_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let k_common = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_COMMON.0 as u32); + let k_srv = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 as u32); + let mut desc2 = desc; + desc2.Width = 512; + let k_512 = ReservedKey::from_desc(&desc2, D3D12_RESOURCE_STATE_COMMON.0 as u32); + + let mut pool = ReservedPool::new(2); + assert_eq!(pool.push(k_common, 0x1000, 1), None); + assert_eq!(pool.push(k_srv, 0x2000, 1), None); + // State mismatch does not cross-hit. + assert_eq!(pool.take(&k_512), None); + // Third push evicts oldest (0x1000) FIFO. + assert_eq!(pool.push(k_512, 0x3000, 4), Some(0x1000)); + assert_eq!(pool.take(&k_common), None); + assert_eq!(pool.take(&k_srv), Some((0x2000, 1))); + assert_eq!(pool.take(&k_512), Some((0x3000, 4))); + assert_eq!(pool.live_gen.len(), 0); + assert_eq!(pool.order.len(), 0); + + // Zero-cap pool immediately returns pushed objects for release. + let mut disabled = ReservedPool::new(0); + assert_eq!(disabled.push(k_common, 0x4000, 1), Some(0x4000)); + } + + #[test] + fn recycled_texture_stays_owned_until_its_mapping_mark_completes() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_BC1_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let key = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_COMMON.0 as u32); + let mut pool = ReservedPool::new(1); + let mut pending = std::collections::VecDeque::from([PendingRecycle { key, raw: 0x1000, total: 1, mark: 2 }]); + assert!(promote_pending(&mut pool, &mut pending, 1).is_empty()); + assert_eq!(pool.take(&key), None, "the pending resource cannot be reused before its mark"); + assert_eq!(pool.push(key, 0x2000, 1), None); + assert_eq!(pool.push(key, 0x3000, 1), Some(0x2000)); + assert_eq!(pending.len(), 1, "pool pressure cannot evict the pending resource"); + assert_eq!(promote_pending(&mut pool, &mut pending, 2), vec![0x3000]); + assert!(pending.is_empty()); + assert_eq!(pool.take(&key), Some((0x1000, 1))); + } + + #[test] + fn reserved_pool_repark_tombstones_stale_order_and_preserves_fifo() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 9, + Format: DXGI_FORMAT_BC1_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let k_a = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_COMMON.0 as u32); + let k_b = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 as u32); + let mut desc_c = desc; + desc_c.Width = 512; + let k_c = ReservedKey::from_desc(&desc_c, D3D12_RESOURCE_STATE_COMMON.0 as u32); + + // Repeated take -> repark below cap must not accumulate unbounded stale order entries, + // even when an older entry stays parked at the front of the queue. + let mut pool = ReservedPool::new(4); + assert_eq!(pool.push(k_a, 0x1000, 1), None); + assert_eq!(pool.push(k_b, 0x2000, 1), None); + for _ in 0..100 { + assert_eq!(pool.take(&k_b), Some((0x2000, 1))); + assert_eq!(pool.push(k_b, 0x2000, 1), None); + } + assert_eq!(pool.live_gen.len(), 2); + assert!(pool.order.len() <= 16, "stale order entries accumulated: {}", pool.order.len()); + + // At cap, a reparked pointer must be ordered by its current parking time, not its original one. + let mut cap2 = ReservedPool::new(2); + assert_eq!(cap2.push(k_a, 0x1000, 1), None); // gen 0 + assert_eq!(cap2.push(k_b, 0x2000, 1), None); // gen 1 + assert_eq!(cap2.take(&k_a), Some((0x1000, 1))); // tombstones gen 0 + assert_eq!(cap2.push(k_a, 0x1000, 1), None); // gen 2 (newer than 0x2000) + // Third entry at cap=2 must evict 0x2000 (gen 1), NOT reparked 0x1000 (gen 2). + assert_eq!(cap2.push(k_c, 0x3000, 4), Some(0x2000)); + assert_eq!(cap2.take(&k_b), None); + assert_eq!(cap2.take(&k_a), Some((0x1000, 1))); + assert_eq!(cap2.take(&k_c), Some((0x3000, 4))); + assert_eq!(cap2.live_gen.len(), 0); + assert_eq!(cap2.order.len(), 0); + + // Non-front stale entry at cap: push A, B, C; take+repark B so stale B(1) remains + // behind A(0); pushing D evicts A(0), then pushing E must skip stale B(1) and evict C(2). + let mut cap3 = ReservedPool::new(3); + assert_eq!(cap3.push(k_a, 0x1000, 1), None); + assert_eq!(cap3.push(k_b, 0x2000, 1), None); + assert_eq!(cap3.push(k_c, 0x3000, 4), None); + assert_eq!(cap3.take(&k_b), Some((0x2000, 1))); + assert_eq!(cap3.push(k_b, 0x2000, 1), None); + assert_eq!(cap3.push(k_a, 0x4000, 1), Some(0x1000)); + assert_eq!(cap3.push(k_a, 0x5000, 1), Some(0x3000)); + assert_eq!(cap3.take(&k_b), Some((0x2000, 1))); + } + + #[test] + fn reserved_resource_recycle_unmaps_reuses_and_remaps_on_gpu() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 9, + Format: DXGI_FORMAT_BC1_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let res = r.unwrap(); + let raw = res.into_raw() as usize; + let raw_ptr = raw as *mut c_void; + let borrowed = ID3D12Resource::from_raw_borrowed(&raw_ptr).unwrap(); + let mut total = 0u32; + dev.GetResourceTiling(borrowed, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + assert!(total >= 1); + + let key = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_COMMON.0 as u32); + let (used1, extra1) = pages.bind(&dev, borrowed, 0x2000_0000, Some(total as u64 * PAGE as u64), total, &[]).expect("initial bind"); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + pages.queue.Wait(&gate, 1).unwrap(); + pages.unmap(borrowed, total); + pages.release_tiles(used1, extra1, std::time::Instant::now(), false); + let mark = pages.value; + pages.pending_recycles.push_back(PendingRecycle { key, raw, total, mark }); + let before_completion = pages.fence.GetCompletedValue(); + let early = promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, before_completion); + let early_hit = pages.reserved_pool.take(&key); + gate.Signal(1).unwrap(); + let _ = pages.fence.SetEventOnCompletion(mark, windows::Win32::Foundation::HANDLE::default()); + assert!(before_completion < mark, "the mapping queue was held behind the gate"); + assert!(early.is_empty() && early_hit.is_none(), "a pending unmap must not publish the texture"); + assert_eq!(pages.pending_recycles.len(), 1); + assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty()); + assert!(pages.pending_recycles.is_empty()); + + // Mismatched state does not reuse it. + let wrong_state = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 as u32); + assert_eq!(pages.reserved_pool.take(&wrong_state), None); + + // Matching desc + state pops the exact same resource and rebinds cleanly to a new VA. + let (reused_raw, reused_total) = pages.reserved_pool.take(&key).expect("recycle hit"); + assert_eq!(reused_raw, raw); + assert_eq!(reused_total, total); + let reused_ptr = reused_raw as *mut c_void; + let reused = ID3D12Resource::from_raw_borrowed(&reused_ptr).unwrap(); + let (used2, extra2) = pages.bind(&dev, reused, 0x2010_0000, Some(total as u64 * PAGE as u64), reused_total, &[]).expect("rebind after recycle"); + pages.unmap(reused, reused_total); + pages.release_tiles(used2, extra2, std::time::Instant::now(), false); + // Wait for unmap on the tile-mapping queue before dropping the resource and heaps. + let _ = pages.fence.SetEventOnCompletion(pages.value, windows::Win32::Foundation::HANDLE::default()); + drop(ID3D12Resource::from_raw(reused_raw as *mut c_void)); + } + } + + #[test] + fn reserved_resource_with_private_data_is_excluded_from_recycle() { + use crate::hle::d3d12x::{late_release, real, title_textures}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + real::adopt(dev.as_raw(), real::Kind::Device); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 9, + Format: DXGI_FORMAT_BC1_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let desc_bytes: [u8; 0x38] = std::mem::transmute(desc); + let backing = vec![0u8; 256 * 1024]; + let va = ((backing.as_ptr() as usize) + PAGE - 1) & !(PAGE - 1); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + + let place = |slot_va: usize| -> Option<*mut c_void> { + let mut ppv: *mut c_void = std::ptr::null_mut(); + let hr = place_on_pages( + &dev, + dev.as_raw(), + slot_va, + &desc, + D3D12_RESOURCE_STATE_COMMON.0 as u32, + std::ptr::null(), + Some(64 * 1024), + false, + false, + riid, + &mut ppv, + )?; + assert!(hr >= 0 && !ppv.is_null()); + let _ = title_textures::register(dev.as_raw(), ppv, slot_va, &desc_bytes, D3D12_RESOURCE_STATE_COMMON); + Some(ppv) + }; + + let Some(raw_a) = place(va) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let custom_guid = windows::core::GUID::from_u128(0x11223344_5566_7788_99aa_bbccddeeff01); + let iface_guid = windows::core::GUID::from_u128(0x11223344_5566_7788_99aa_bbccddeeff02); + let payload: u32 = 0xDEAD_BEEF; + { + let a = ID3D12Resource::from_raw_borrowed(&raw_a).unwrap(); + a.SetPrivateData(&custom_guid, 4, Some(&payload as *const u32 as *const c_void)).unwrap(); + let mut got = 0u32; + let mut sz = 4u32; + a.GetPrivateData(&custom_guid, &mut sz, Some(&mut got as *mut u32 as *mut c_void)).unwrap(); + assert_eq!(got, payload); + } + // Release A through its adopted vtable; private data excludes it from the recycle pool. + drop(ID3D12Resource::from_raw(raw_a)); + late_release::drain_known(true); + + // Matching texture B must behave like a fresh resource (no stale private data). + let raw_b = place(va).expect("place B"); + { + let b = ID3D12Resource::from_raw_borrowed(&raw_b).unwrap(); + let mut got = 0u32; + let mut sz = 4u32; + assert!( + b.GetPrivateData(&custom_guid, &mut sz, Some(&mut got as *mut u32 as *mut c_void)).is_err(), + "private data leaked from released texture A into fresh texture B" + ); + // Also verify SetPrivateDataInterface excludes B from reuse. + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + b.SetPrivateDataInterface(&iface_guid, &fence).unwrap(); + drop(fence); + } + drop(ID3D12Resource::from_raw(raw_b)); + late_release::drain_known(true); + + // Matching texture C must have no leaked interface data; untagged C then recycles into D. + let raw_c = place(va).expect("place C"); + { + let c = ID3D12Resource::from_raw_borrowed(&raw_c).unwrap(); + let mut ptr: *mut c_void = std::ptr::null_mut(); + let mut sz = std::mem::size_of::<*mut c_void>() as u32; + assert!( + c.GetPrivateData(&iface_guid, &mut sz, Some(&mut ptr as *mut *mut c_void as *mut c_void)).is_err(), + "SetPrivateDataInterface leaked from released texture B into fresh texture C" + ); + } + drop(ID3D12Resource::from_raw(raw_c)); + late_release::drain_known(true); + + // C may still be held by the mapping queue after its title-side Release. + let start = std::time::Instant::now(); + let pending_mark = loop { + late_release::drain_known(true); + let g = PAGES.lock().unwrap(); + let pages = g.get(&(dev.as_raw() as usize)).and_then(Option::as_ref).unwrap(); + if pages.reserved_pool.live_gen.contains_key(&(raw_c as usize)) { + break None; + } + if let Some(item) = pages.pending_recycles.iter().find(|p| p.raw == raw_c as usize) { + break Some((pages.fence.clone(), item.mark)); + } + assert!(start.elapsed() < std::time::Duration::from_secs(5), "C did not reach the recycle queue"); + drop(g); + std::thread::yield_now(); + }; + if let Some((fence, mark)) = pending_mark { + let _ = fence.SetEventOnCompletion(mark, windows::Win32::Foundation::HANDLE::default()); + drain_recycled(); + } + + let raw_d = place(va).expect("place D"); + assert_eq!(raw_d, raw_c, "untagged texture C should still recycle into D"); + drop(ID3D12Resource::from_raw(raw_d)); + late_release::drain_known(true); + } + } } From 27f5f621db74e6c08a341b992036b29f959e5929 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:27:44 +0100 Subject: [PATCH 070/175] D3D12.X: split the ExecuteCommandLists hook into steps a thread can run No behaviour change. The hook's body becomes the steps it already ran in this order: what a title's submit notes first (`note_title_submit`), the put-off dispatches recorded (`record_deferred_of`), the refresh, the title lists mapped to their PC lists and segments (`pc_lists_of`), and the submission with its per-chunk after-work (`execute_mapped`). The queue's Signal / SignalX / Wait bodies become `queue_signal_now` and `queue_wait_now` (SignalX had a copy of Signal's). This prepares an ordered submit thread (VIctory-Neo's `VICTORY_ASYNC_SUBMIT`, crates/victory-gpu/src/queue/behind.rs): the title's thread keeps the steps that must see the lists as submitted, the thread runs the rest in order. (cherry picked from commit 4831996f13a2437dc969398fd2b8dbf0a302ed7d) --- crates/xcl/src/hle/d3d12x/real.rs | 122 +++++++++++++++++++----------- 1 file changed, 76 insertions(+), 46 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2938f51235..3a0ea06878 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -10360,8 +10360,6 @@ const QUEUE_FIRST: usize = 14; /// A title's call of queue slot `slot` (arguments as integers; Signal / Wait / SignalX / /// PresentX / GetTimestampFrequency / GetClockCalibration / GetDesc all fit). unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize) -> usize { - const PC_SIGNAL: usize = 14; - const PC_WAIT: usize = 15; const PC_TIMESTAMP_FREQUENCY: usize = 16; const PC_CLOCK_CALIBRATION: usize = 17; const PC_GET_DESC: usize = 18; @@ -10378,22 +10376,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a match older { // Signal / Wait take a fence: anything else is not one of them 14 | 15 if is_fence(a1) => { - if older == 14 { - super::list_x::break_cycles_before_title_signal(this as usize, a1, a2 as u64); - // (work that waits for it may use memory committed since it was submitted) - super::sparse::send_pending(); - } - let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(if older == 14 { PC_SIGNAL } else { PC_WAIT })); - let hr = f(this, a1, a2); - if hr >= 0 { - if older == 14 { - super::fence_x::note_queue_signal(a1, a2 as u64); - super::list_x::note_title_queue_signal(this as usize, a1, a2 as u64); - } else { - super::fence_x::note_queue_wait(a1, a2 as u64); - super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); - } - } + let hr = if older == 14 { queue_signal_now(this, a1, a2 as u64) } else { queue_wait_now(this, a1, a2 as u64) }; hr as u32 as usize } 16 => { @@ -10529,14 +10512,33 @@ unsafe fn q_copy_page_mappings(count: u32, batches: usize, pool: usize, pool_pag /// nothing left Fortnite's render fences pending: its render thread waited, textures were /// never released, and the garbage collector ended the game after 10 s.) unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, value: u64, _flags: u32) -> HRESULT { + queue_signal_now(this, fence as usize, value) +} + +/// A Signal of `fence` (one of the title's) with `value` on `queue`, with what XCL notes around +/// it (Signal and SignalX). +pub(super) unsafe fn queue_signal_now(queue: *mut c_void, fence: usize, value: u64) -> HRESULT { const PC_SIGNAL: usize = 14; - super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); + super::list_x::break_cycles_before_title_signal(queue as usize, fence, value); + // (work that waits for it may use memory committed since it was submitted) super::sparse::send_pending(); - let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, PC_SIGNAL)); - let hr = f(this, fence, value); + let f: unsafe extern "system" fn(*mut c_void, usize, u64) -> HRESULT = std::mem::transmute(orig_fn(queue, PC_SIGNAL)); + let hr = f(queue, fence, value); if hr >= 0 { - super::fence_x::note_queue_signal(fence as usize, value); - super::list_x::note_title_queue_signal(this as usize, fence as usize, value); + super::fence_x::note_queue_signal(fence, value); + super::list_x::note_title_queue_signal(queue as usize, fence, value); + } + hr +} + +/// A Wait of `queue` for `fence` (one of the title's) to reach `value`, with what XCL notes. +pub(super) unsafe fn queue_wait_now(queue: *mut c_void, fence: usize, value: u64) -> HRESULT { + const PC_WAIT: usize = 15; + let f: unsafe extern "system" fn(*mut c_void, usize, u64) -> HRESULT = std::mem::transmute(orig_fn(queue, PC_WAIT)); + let hr = f(queue, fence, value); + if hr >= 0 { + super::fence_x::note_queue_wait(fence, value); + super::list_x::note_title_queue_wait(queue as usize, fence, value); } hr } @@ -10640,44 +10642,73 @@ unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT } unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) { - type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); - let f: F = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12CommandQueue", "ExecuteCommandLists"))); if n == 0 || lists.is_null() { - f(this, n, lists); + pc_execute_command_lists(this)(this, n, lists); stop_if_device_removed(); return; } - super::gpu_awake::note_activity(); - super::capture::submit(this, std::slice::from_raw_parts(lists, n as usize)); + let lists = std::slice::from_raw_parts(lists, n as usize); + note_title_submit(this, lists); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's // own work in the submission. Where that takes long, it is not the title's time // (`pso_async::title_held`) let _in_pc = super::pso_async::pc_call(); // (not while a stop for a driver error is being handled: `watch`) super::watch::wait_while_held(); - // the dispatches title lists put off to the submit (their pipelines were being built) are - // recorded first, as `kickoff_x` does: the GPU-view tiles they ask for are mapped by this - // submit's refresh, and their waits for the builds are not the submit's cost (the put-off line) - for &l in std::slice::from_raw_parts(lists, n as usize) { - if super::console_list::pc_list(l).is_none() { - super::list_x::record_deferred(l); - } - } + record_deferred_of(lists); // textures in title memory the CPU wrote since: uploaded again first let submit_t0 = std::time::Instant::now(); - super::title_textures::refresh_for(this, std::slice::from_raw_parts(lists, n as usize)); + super::title_textures::refresh_for(this, lists); let t_lists = std::time::Instant::now(); super::submit_cost::call(t_lists - submit_t0); - // console-shaped lists run as the PC lists they were translated into (split title lists expand - // into all of their recorded PC segments in exact chronological order) - let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); - for &l in std::slice::from_raw_parts(lists, n as usize) { + let mapped = pc_lists_of(lists); + execute_mapped(this, &mapped, t_lists); + super::submit_cost::done(submit_t0); +} + +type ExecuteFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + +/// The PC's own ExecuteCommandLists of `queue`. +unsafe fn pc_execute_command_lists(queue: *mut c_void) -> ExecuteFn { + std::mem::transmute(orig_fn(queue, pc_slot!("ID3D12CommandQueue", "ExecuteCommandLists"))) +} + +/// What a title's submit of `lists` to `queue` notes before anything else. +pub(super) unsafe fn note_title_submit(queue: *mut c_void, lists: &[*mut c_void]) { + super::gpu_awake::note_activity(); + super::capture::submit(queue, lists); +} + +/// The dispatches title lists put off to the submit (their pipelines were being built) are +/// recorded first, as `kickoff_x` does: the GPU-view tiles they ask for are mapped by the +/// submit's refresh, and their waits for the builds are not the submit's cost (the put-off line). +pub(super) unsafe fn record_deferred_of(lists: &[*mut c_void]) { + for &l in lists { + if super::console_list::pc_list(l).is_none() { + super::list_x::record_deferred(l); + } + } +} + +/// The PC lists the title's `lists` run as: console-shaped lists the PC lists they were +/// translated into, split title lists all of their recorded PC segments in exact chronological +/// order. +pub(super) unsafe fn pc_lists_of(lists: &[*mut c_void]) -> Vec<*mut c_void> { + let mut mapped: Vec<*mut c_void> = Vec::with_capacity(lists.len()); + for &l in lists { if let Some(pc) = super::console_list::pc_list(l) { mapped.push(pc); } else if !super::title_list::push_segments(l, &mut mapped) { mapped.push(l); } } + mapped +} + +/// A title's submit after its refresh: the PC lists `mapped` go to `queue` with what XCL does +/// around them (`t_lists`: when the refresh ended). +pub(super) unsafe fn execute_mapped(this: *mut c_void, mapped: &[*mut c_void], t_lists: std::time::Instant) { + let f = pc_execute_command_lists(this); // Flush and wait for any tile mappings / recycled-tile zero-fills queued concurrently while // `record_deferred` built/waited on PSOs so the title's submit never races `UpdateTileMappings`. // Skip for XCL's own internal submits (`own_work`) which may already hold `PAGES` or `STATE`. @@ -10687,11 +10718,11 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::vram::wait_pending_mappings(q); } } - super::list_x::note_queue_for_lists(this as usize, &mapped); + super::list_x::note_queue_for_lists(this as usize, mapped); super::gpu_profile::note_queue(this); let t_exec = std::time::Instant::now(); super::submit_cost::lists(t_exec - t_lists); - super::list_x::execute_with_waits_on(this, &mapped, |chunk| { + super::list_x::execute_with_waits_on(this, mapped, |chunk| { // a list still on the GPU from its previous submit: that one first (the PC does not take // a list again before then) let t = std::time::Instant::now(); @@ -10718,12 +10749,11 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis let t_end = std::time::Instant::now(); super::submit_cost::exec(t_end - t_exec); // the next uploads into textures kept in step start from the states these lists leave - super::title_textures::submitted(&mapped); - super::present::note_execute(this, &mapped); + super::title_textures::submitted(mapped); + super::present::note_execute(this, mapped); stop_if_device_removed(); gpu_sync_after_submit(this); super::submit_cost::end(t_end.elapsed()); - super::submit_cost::done(submit_t0); } /// `XCL_GPU_SYNC=` (diagnostic, off unless set): a title's submit returns only once its queue From db556c26dbca288d160db56842223c082d5af30d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:31:09 +0100 Subject: [PATCH 071/175] D3D12.X: tell the title's queue calls from XCL's own by their caller No behaviour change. XCL signals, waits and submits on the title's queues itself (alloc_pool's and late_release's marks, uploads, presents, copy-scratch and progress fences), through the same vtable the title calls, so `queue_dispatch` could not tell whose call it was. The queue's ExecuteCommandLists and its console slots from #14 now go through `guard::make_split`: a call from a game image reaches the title entry (`q_execute_command_lists_title`, `queue_dispatch(.., title: true, ..)`), any other the entry it reached before. Both do what the hook did. An ordered submit thread needs this: the title's Signal / Wait / submits go into its line behind the title's earlier submits, while XCL's own signals must go to the queue at once (alloc_pool signals one fence a queue from the submit and from KickoffX; one of them queued behind the other would set the fence back). (cherry picked from commit c3bfe77a062ee6101691aae1201014381730e43e) --- crates/xcl/src/hle/d3d12x/real.rs | 55 ++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3a0ea06878..fe33190f06 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1204,7 +1204,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { Kind::Fence => vec![(12, super::fence_x::completed_value_address as usize)], // the title's calls from #14 on: Signal / Wait / … / SignalX / PresentX at the slots of // its runtime's layout (`queue_dispatch`) - Kind::CommandQueue => QUEUE_SLOTS.iter().enumerate().map(|(k, &f)| (QUEUE_FIRST + k, f as usize)).collect(), + Kind::CommandQueue => queue_entries().iter().enumerate().map(|(k, &f)| (QUEUE_FIRST + k, f)).collect(), Kind::DmaList => { use super::list_x as l; vec![(9, l::dma_close_x as usize), (10, l::reset_x as usize), (11, l::copy_buffer_region_x as usize), (12, l::copy_texture_region_x as usize), (13, l::copy_resource_x as usize)] @@ -4165,7 +4165,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("Close", cl_close as usize), ("Reset", cl_reset as usize), ]), - Kind::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", q_execute_command_lists as usize)]), + Kind::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", execute_entry())]), Kind::CommandAllocator => v.extend_from_slice(&[("Release", alloc_release as usize), ("Reset", alloc_reset as usize)]), Kind::Resource => v.extend_from_slice(&[ ("Release", res_release as usize), @@ -10357,9 +10357,10 @@ fn is_fence(p: usize) -> bool { /// first queue slot `queue_dispatch` handles const QUEUE_FIRST: usize = 14; -/// A title's call of queue slot `slot` (arguments as integers; Signal / Wait / SignalX / -/// PresentX / GetTimestampFrequency / GetClockCalibration / GetDesc all fit). -unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize) -> usize { +/// A call of queue slot `slot` (arguments as integers; Signal / Wait / SignalX / PresentX / +/// GetTimestampFrequency / GetClockCalibration / GetDesc all fit). `title`: made by the title's +/// code (`queue_entries`), not by XCL's own. +unsafe fn queue_dispatch(slot: usize, title: bool, this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize) -> usize { const PC_TIMESTAMP_FREQUENCY: usize = 16; const PC_CLOCK_CALIBRATION: usize = 17; const PC_GET_DESC: usize = 18; @@ -10415,7 +10416,11 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a 33 if shifted => { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| crate::xlog_info!("D3D12.X: queue #35 ExecuteCommandListsX ({} lists, value {a3:#x}, flags {a4:#x})", a1)); - q_execute_command_lists(this, a1 as u32, a2 as *const *mut c_void); + if title { + q_execute_command_lists_title(this, a1 as u32, a2 as *const *mut c_void); + } else { + q_execute_command_lists(this, a1 as u32, a2 as *const *mut c_void); + } 0 } _ => { @@ -10443,10 +10448,18 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a macro_rules! queue_slots { ($($slot:literal),*) => { - /// the title's entry for each queue slot from `QUEUE_FIRST` + /// the entry for each queue slot from `QUEUE_FIRST` of calls from XCL's own code (and the + /// runtime's) static QUEUE_SLOTS: &[unsafe extern "system" fn(*mut c_void, usize, usize, usize, usize) -> usize] = &[$({ unsafe extern "system" fn f(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize) -> usize { - queue_dispatch($slot, this, a1, a2, a3, a4) + queue_dispatch($slot, false, this, a1, a2, a3, a4) + } + f + }),*]; + /// the same of calls from the title's code + static QUEUE_TITLE_SLOTS: &[unsafe extern "system" fn(*mut c_void, usize, usize, usize, usize) -> usize] = &[$({ + unsafe extern "system" fn f(this: *mut c_void, a1: usize, a2: usize, a3: usize, a4: usize) -> usize { + queue_dispatch($slot, true, this, a1, a2, a3, a4) } f }),*]; @@ -10454,6 +10467,26 @@ macro_rules! queue_slots { } queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35); +/// The queue's vtable entry for each slot from `QUEUE_FIRST`. XCL signals, waits and submits on +/// the title's queues itself (its marks of how far the GPU got, uploads, presents), through the +/// same vtable: a call from a game image is the title's (`guard::make_split`), any other XCL's +/// own. (Made once.) +fn queue_entries() -> &'static [usize] { + static E: OnceLock> = OnceLock::new(); + E.get_or_init(|| QUEUE_TITLE_SLOTS.iter().zip(QUEUE_SLOTS).map(|(&t, &x)| super::guard::make_split(t as usize, x as usize)).collect()) +} + +/// The queue's ExecuteCommandLists entry, split as `queue_entries` are. +fn execute_entry() -> usize { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| super::guard::make_split(q_execute_command_lists_title as usize, q_execute_command_lists as usize)) +} + +/// ExecuteCommandLists (and #35 ExecuteCommandListsX) called by the title's code. +unsafe extern "system" fn q_execute_command_lists_title(this: *mut c_void, n: u32, lists: *const *mut c_void) { + q_execute_command_lists(this, n, lists); +} + /// The calls of the queue's page-mapping method recorded so far and what they did, summed, and /// when their line was logged last. static PAGE_MAPPINGS: Mutex<(u64, crate::hle::kernelx::mirrors::Mapped, Option)> = @@ -11759,14 +11792,14 @@ mod queue_tests { QUEUE_OLDER.store(false, Ordering::Release); unsafe { let mut out = [0xAAAA_AAAAu32; 4]; - let r = queue_dispatch(18, this, out.as_mut_ptr() as usize, 0, 0, 0); + let r = queue_dispatch(18, false, this, out.as_mut_ptr() as usize, 0, 0, 0); assert_eq!(r, out.as_ptr() as usize); assert_eq!(out, [1, 2, 0xAAAA_AAAA, 0xAAAA_AAAA], "only the first 8 bytes"); FENCES.write().unwrap().push(fence); - queue_dispatch(14, this, fence, 1, 0, 0); + queue_dispatch(14, false, this, fence, 1, 0, 0); assert!(QUEUE_OLDER.load(Ordering::Acquire) && !QUEUE_SHIFTED.load(Ordering::Acquire)); let mut out = [0xAAAA_AAAAu32; 4]; - queue_dispatch(18, this, out.as_mut_ptr() as usize, 0, 0, 0); + queue_dispatch(18, false, this, out.as_mut_ptr() as usize, 0, 0, 0); assert_eq!(out, [1, 2, 3, 4], "older layout: the whole description"); } } From b54c6d9b35a594236e95fda77918a0dc6c3ca155 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:48:01 +0100 Subject: [PATCH 072/175] D3D12.X: XCL_ASYNC_SUBMIT=1 makes the title's submits on a thread of XCL's Off unless set. A retail title's world (amd-dev, RX 9070 XT) had its submitting thread inside ExecuteCommandLists for ~1.75 s of every 2 s: ~100 submits a second at 8.8-11 ms each, the driver's own call 0.02 ms. The title does nothing with what that work does; it only has to be done before the lists run, in order. The idea is VIctory-Neo's VICTORY_ASYNC_SUBMIT (https://github.com/KyleS98/VIctory-Neo, crates/victory-gpu/src/queue/ behind.rs, GPL-3.0-or-later). Neo keeps fences itself and holds a queue's work at its waits; here fences and queue waits are the PC's, so the line (`submit_thread`) keeps nothing but the order: one line for all the title's queues, done by one thread. - The title's ExecuteCommandLists / ExecuteCommandListsX note the submit, record their put-off dispatches and take the PC lists and segments the lists are now on the title's thread, then go into the line holding a reference to each list and the queue; the thread runs the refresh and `execute_mapped` as the hook did. - The title's Signal / SignalX / Wait go into the line behind them (at once when it is empty): no fence is reached before the work in front of it was submitted, and the thread never waits for a title's thread. - PresentX (and the fallback present), CopyPageMappingsBatchX, the queue's UpdateTileMappings / CopyTileMappings (now hooked for this), KickoffX, a Reset of a list in the line that found no stand-in, and the last Release of an allocator with recordings in the line drain it first. XCL's own calls on the title's queues never go into it. - A PC list in the line counts as in flight: the title's Reset records on a stand-in, and the segments it moves to the spares keep their recording state until submitted (`when_submitted`). The allocator a queued recording is on is not free (`alloc_pool::queued`): a Reset of the title's allocator puts it aside, and it gets the queue's mark when the submit is made. - late_release seals a batch only once the line made what it held when the batch's newest release came: its fence values go behind them. Needs XCL_ALLOC_SWAP on and XCL_CONSOLE_LISTS off (else a warning and the title's threads submit). XCL_ASYNC_SUBMIT_DEPTH (64) bounds the line. One entry at a time here; batching the refresh comes next. Tests: the line's order, drains and room; queued lists' deferred work; allocators held by queued recordings; late_release's gate; and a GPU test in a process of its own: two title submits of one list, reset in between while the first is in the line, and a Signal behind them that is not reached before the thread made them. (cherry picked from commit 00b7caac59b73d5cc217e419a2667ac8485f1af2) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 97 ++- crates/xcl/src/hle/d3d12x/late_release.rs | 43 +- crates/xcl/src/hle/d3d12x/list_x.rs | 2 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/present.rs | 2 + crates/xcl/src/hle/d3d12x/real.rs | 76 +- crates/xcl/src/hle/d3d12x/submit_cost.rs | 16 +- crates/xcl/src/hle/d3d12x/submit_thread.rs | 761 +++++++++++++++++++++ crates/xcl/src/hle/d3d12x/title_list.rs | 14 +- 9 files changed, 992 insertions(+), 20 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/submit_thread.rs diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 1a074ded1b..59c5e2f9f6 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -28,6 +28,9 @@ struct Backing { users: HashSet, /// queue → (fence, value after the last submit of one of them) marks: HashMap, + /// submits of recordings on it in the submit thread's line, not made yet (`queued`): they have + /// no marks yet + queued: u32, } impl Backing { @@ -37,7 +40,7 @@ impl Backing { } unsafe fn free(&self) -> bool { - self.users.is_empty() && self.idle() + self.users.is_empty() && self.queued == 0 && self.idle() } } @@ -142,6 +145,10 @@ pub(super) fn park_list(list: usize) { /// Reset `list` on the title's allocator `alloc`, committing its new recording association /// only after native Reset succeeds. No pool lock is held across the driver call. pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { + // (a recording the submit thread has not submitted yet is lost to a Reset: it is submitted first) + if super::submit_thread::queued(list) { + super::submit_thread::drain(super::submit_thread::Drain::ListReset); + } let backing = current(alloc); let hr = reset(backing); if hr < 0 || !enabled() || alloc == 0 { @@ -302,6 +309,10 @@ unsafe fn wait_for_previous_submits_within(lists: &[*mut c_void], limit: std::ti /// submitted again before that; `title_list` records the title's next recording elsewhere). /// (`fence_completed`: XCL's own fence, without the title's hook, STATE held) pub fn in_flight(list: usize) -> bool { + // (in a submit the submit thread has not made yet: it will be) + if super::submit_thread::queued(list) { + return true; + } let g = STATE.lock().unwrap(); g.as_ref().and_then(|s| s.last_submit.get(&list)).is_some_and(|l| unsafe { super::real::fence_completed(&l.fence) } < l.value) } @@ -379,10 +390,53 @@ pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { let g = STATE.lock().unwrap(); let Some(s) = g.as_ref() else { return false }; let mine = s.cur.get(&alloc).into_iter().chain(s.aside.get(&alloc).into_iter().flatten()).chain([&alloc]); - let busy = mine.filter_map(|b| s.backings.get(b)).any(|b| !b.idle()); + let busy = mine.filter_map(|b| s.backings.get(b)).any(|b| b.queued > 0 || !b.idle()); busy } +/// The PC lists `lists` are in a submit put in the submit thread's line: the PC allocators their +/// recordings are on are not free until `unqueued` (a Reset of the title's allocator puts one +/// aside, as one the GPU still runs). Returns those allocators, for `unqueued`. +pub(super) fn queued(lists: &[*mut c_void]) -> Vec { + if !enabled() { + return Vec::new(); + } + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + let on: Vec = lists.iter().filter_map(|&l| s.of_list.get(&(l as usize)).copied()).collect(); + for &b in &on { + s.backings.entry(b).or_default().queued += 1; + } + on +} + +/// Whether a recording on a PC allocator of the title's allocator `alloc` is in a submit the +/// submit thread has not made yet. +pub(super) fn has_queued(alloc: usize) -> bool { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + let mine = s.cur.get(&alloc).into_iter().chain(s.aside.get(&alloc).into_iter().flatten()).chain([&alloc]); + let queued = mine.filter_map(|b| s.backings.get(b)).any(|b| b.queued > 0); + queued +} + +/// The submit `queued` returned `backings` for was made on `queue`. They get the queue's mark +/// after it: `executed` marks the allocator a list records on when it is submitted, and the title +/// may have reset the list (it records elsewhere) while the submit was in the line. +pub(super) fn unqueued(queue: *mut c_void, backings: &[usize]) { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + let mark = s.fences.get(&(queue as usize)).cloned(); + for b in backings { + if let Some(x) = s.backings.get_mut(b) { + x.queued = x.queued.saturating_sub(1); + if let Some(m) = &mark { + x.marks.insert(queue as usize, m.clone()); + } + } + } +} + /// Like `forget`, but when `alloc` (or any of its put-aside backings) still has unfinished GPU /// fence marks, defers running `cleanup` (and resetting/dropping any XCL-created spare PC /// allocators) until all those fences complete (`release_finished`). Returns `true` if deferred, @@ -731,6 +785,45 @@ mod tests { ids[0] = 0; } + /// `XCL_ASYNC_SUBMIT`: a recording in a submit the submit thread has not made yet holds the + /// allocator it is on, also once its list is parked (the title reset it and records elsewhere): + /// a Reset of the title's allocator puts that one aside instead of resetting it. Once made, it + /// holds it no more. + #[test] + fn a_submit_in_the_line_holds_the_allocator_its_recording_is_on() { + let mut ids = Box::new([0u8; 2]); + let alloc = ids.as_mut_ptr() as usize; + let list = alloc + 1; + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let on = queued(&[list as *mut c_void]); + assert_eq!(on, vec![alloc]); + park_list(list); + let free = || unsafe { STATE.lock().unwrap().as_ref().unwrap().backings[&alloc].free() }; + assert!(!free(), "the submit is not made yet"); + assert!(unsafe { allocator_in_flight(alloc) }); + unqueued(std::ptr::null_mut(), &on); + assert!(free()); + ids[0] = 0; + + let (alloc, spare) = (0x1000usize, 0x2000usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.backings.insert(alloc, Backing { queued: 1, ..Default::default() }); + s.aside.insert(alloc, vec![spare]); + s.backings.insert(spare, Backing::default()); + let mut calls = Vec::new(); + let hr = unsafe { + title_reset_in(&mut s, alloc as *mut c_void, |raw| { + calls.push(raw as usize); + 0 + }) + }; + assert_eq!(hr, Some(0)); + assert_eq!(calls, [spare], "the allocator with a submit in the line is not reset"); + assert_eq!(s.cur.get(&alloc), Some(&spare)); + assert_eq!(s.aside.get(&alloc), Some(&vec![alloc])); + } + #[test] fn a_spare_whose_reset_fails_stays_available_for_retry() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 12a24d3c71..27b8b47f34 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -47,6 +47,9 @@ struct Held { /// queue → its fence here and the last value signalled on it fences: HashMap, open: Vec, + /// how many entries the submit thread's line had taken in when the newest of `open` came + /// (`XCL_ASYNC_SUBMIT`): what the title submitted before its release may not be submitted yet + open_seq: u64, sealed: VecDeque, last_seal: Option, } @@ -59,10 +62,23 @@ impl Held { self.open.is_empty() && self.sealed.is_empty() } + /// `dead` is held from now on. + fn hold(&mut self, dead: Dead) { + self.open.push(dead); + self.open_seq = super::submit_thread::pushed(); + } + /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`, /// and take out the batches every queue is past: what to release now. unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { - if !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) { + self.drain_after(queues, seal_now, super::submit_thread::done()) + } + + /// `drain`, with the submit thread's line done up to `line_done`: the open batch is closed only + /// once the line made the submits it held when the batch's newest came (its fence values are + /// signalled behind them). + unsafe fn drain_after(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool, line_done: u64) -> Vec { + if !self.open.is_empty() && line_done >= self.open_seq && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) { let mut marks = Vec::with_capacity(queues.len()); let mut ok = true; for q in queues { @@ -136,7 +152,7 @@ static BUSY: Busy = Busy(Mutex::new(None)); /// `Release` finds it unpinned, as before. Otherwise the thread here lets it go – the driver takes /// ~100 us to end a texture, and a title ends thousands of them when it changes places. pub unsafe fn hold(res: usize, pinned: bool) { - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Resource(res)); + HELD.lock().unwrap().get_or_insert_with(Held::default).hold(Dead::Resource(res)); let start = Instant::now(); let busy = !pinned || BUSY.is(start); if !busy { @@ -186,7 +202,7 @@ pub fn hold_pipeline(p: usize) { if !enabled() { return super::pso_async::release(p); } - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Pipeline(p)); + HELD.lock().unwrap().get_or_insert_with(Held::default).hold(Dead::Pipeline(p)); start_thread(); } @@ -199,7 +215,7 @@ pub fn hold_heap(heap: ID3D12Heap) { if !enabled() { return drop(heap); } - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Heap(heap.into_raw() as usize)); + HELD.lock().unwrap().get_or_insert_with(Held::default).hold(Dead::Heap(heap.into_raw() as usize)); start_thread(); } @@ -211,7 +227,7 @@ pub fn hold_unmap(res: ID3D12Resource) { unsafe { super::placements::unmap_if_superseded(&res) }; return drop(res); } - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Unmap(res.into_raw() as usize)); + HELD.lock().unwrap().get_or_insert_with(Held::default).hold(Dead::Unmap(res.into_raw() as usize)); start_thread(); } @@ -350,6 +366,23 @@ mod tests { assert!(held.is_empty()); } + /// `XCL_ASYNC_SUBMIT`: a release the title made with submits of its in the submit thread's line + /// is not sealed before the line made them (its fence values would be signalled in front of + /// them), and is once it has – the next one waits for the line as it was then. + #[test] + fn a_batch_is_sealed_behind_the_submits_in_the_line_at_its_release() { + let mut held = Held::default(); + held.open.push(Dead::Resource(0x1000)); + held.open_seq = 5; + assert!(unsafe { held.drain_after(&[], true, 4) }.is_empty(), "the line has not made its 5th submit"); + assert!(!held.is_empty()); + assert_eq!(unsafe { held.drain_after(&[], true, 5) }, vec![Dead::Resource(0x1000)]); + held.open.push(Dead::Pipeline(0x2000)); + held.open_seq = 9; + assert!(unsafe { held.drain_after(&[], true, 8) }.is_empty()); + assert_eq!(unsafe { held.drain_after(&[], true, 12) }, vec![Dead::Pipeline(0x2000)]); + } + /// A pipeline state XCL lets go goes into a batch (a list in flight may bind it), and the /// thread here releases it once the queues are past – through its COM Release. (That a batch /// waits for a busy queue is `a_held_resource_goes_when_the_queue_is_past_its_batch`.) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index dee65b213b..3cefb413fb 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3988,6 +3988,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return; } + // (it submits at once: behind the title's submits the submit thread has not made yet) + super::submit_thread::drain(super::submit_thread::Drain::Kickoff); let dev_raw = device_of(this).map_or(0, |d| d.as_raw() as usize); let (alloc, queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, waits, sparse_writes) = { let mut g = recording(this as usize).lock().unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 91cb0d988c..dfcd3d9e34 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -55,6 +55,7 @@ mod targets; mod watch; pub mod title_list; mod submit_cost; +mod submit_thread; mod texture_upload; pub mod title_textures; mod uma_driver; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 92264f4d8f..3a36305824 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -473,6 +473,8 @@ pub fn on_queue_console_method(_info: &StubInfo, _caller: usize) { } BOUNDARIES.fetch_add(1, Ordering::Relaxed); LAST_BOUNDARY_MS.store(now_ms(), Ordering::Relaxed); + // (the frame's copy goes behind the title's submits: `XCL_ASYNC_SUBMIT`) + super::submit_thread::drain(super::submit_thread::Drain::Present); let _cost = super::look_stats::deep().then(|| crate::hle::api_cost::time(crate::hle::api_cost::Call::Present)); unsafe { present_now(Duration::from_millis(4), None) }; } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fe33190f06..ac22c442ea 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4165,7 +4165,10 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("Close", cl_close as usize), ("Reset", cl_reset as usize), ]), - Kind::CommandQueue => v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", execute_entry())]), + Kind::CommandQueue => { + let [update, copy] = tile_mapping_entries(); + v.extend_from_slice(&[("Release", q_release as usize), ("ExecuteCommandLists", execute_entry()), ("UpdateTileMappings", update), ("CopyTileMappings", copy)]) + } Kind::CommandAllocator => v.extend_from_slice(&[("Release", alloc_release as usize), ("Reset", alloc_reset as usize)]), Kind::Resource => v.extend_from_slice(&[ ("Release", res_release as usize), @@ -10219,6 +10222,10 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); if add_ref(this) == 2 { let a = this as usize; + // (the submit thread's line may hold recordings on it: the marks below are theirs once made) + if super::alloc_pool::has_queued(a) { + super::submit_thread::drain(super::submit_thread::Drain::Release); + } let deferred = super::alloc_pool::release_when_done( a, Box::new(move || { @@ -10377,7 +10384,13 @@ unsafe fn queue_dispatch(slot: usize, title: bool, this: *mut c_void, a1: usize, match older { // Signal / Wait take a fence: anything else is not one of them 14 | 15 if is_fence(a1) => { - let hr = if older == 14 { queue_signal_now(this, a1, a2 as u64) } else { queue_wait_now(this, a1, a2 as u64) }; + // (`XCL_ASYNC_SUBMIT=1`: the title's go behind its submits the thread has not made yet) + let hr = match (older == 14, title && super::submit_thread::on()) { + (true, true) => super::submit_thread::signal(this, a1, a2 as u64), + (false, true) => super::submit_thread::wait(this, a1, a2 as u64), + (true, false) => queue_signal_now(this, a1, a2 as u64), + (false, false) => queue_wait_now(this, a1, a2 as u64), + }; hr as u32 as usize } 16 => { @@ -10407,9 +10420,22 @@ unsafe fn queue_dispatch(slot: usize, title: bool, this: *mut c_void, a1: usize, let f: unsafe extern "system" fn(*mut c_void, usize) -> usize = std::mem::transmute(pc(PC_GET_DESC)); f(this, a1) } + 23 if title && super::submit_thread::on() => super::submit_thread::signal(this, a1, a2 as u64) as u32 as usize, 23 => q_signal_x(this, a1 as *mut c_void, a2 as u64, a3 as u32) as u32 as usize, - 29 if crate::hle::kernelx::mirrors::page_mappings() => q_copy_page_mappings(a1 as u32, a2, a3, a4 as u32) as u32 as usize, - 30 => super::present::present_x(this, a1 as u32, a2 as *const u8, a3 as *const u8) as u32 as usize, + 29 if crate::hle::kernelx::mirrors::page_mappings() => { + // (the title's submits made before read the pages as they were mapped then) + if title { + super::submit_thread::drain(super::submit_thread::Drain::PageMappings); + } + q_copy_page_mappings(a1 as u32, a2, a3, a4 as u32) as u32 as usize + } + 30 => { + // (the frame's copy goes behind the title's submits) + if title { + super::submit_thread::drain(super::submit_thread::Drain::Present); + } + super::present::present_x(this, a1 as u32, a2 as *const u8, a3 as *const u8) as u32 as usize + } // the newer layout's #35: ExecuteCommandListsX(count, lists, a value, flags) – a retail // game submits all its command lists this way (flags 3; 0 for the one it recorded at // start); as a stub nothing the title recorded ran on the GPU but its first two frames @@ -10482,11 +10508,51 @@ fn execute_entry() -> usize { *E.get_or_init(|| super::guard::make_split(q_execute_command_lists_title as usize, q_execute_command_lists as usize)) } -/// ExecuteCommandLists (and #35 ExecuteCommandListsX) called by the title's code. +/// ExecuteCommandLists (and #35 ExecuteCommandListsX) called by the title's code: into the submit +/// thread's line with `XCL_ASYNC_SUBMIT=1`. unsafe extern "system" fn q_execute_command_lists_title(this: *mut c_void, n: u32, lists: *const *mut c_void) { + if n != 0 && !lists.is_null() && super::submit_thread::on() && !super::submit_thread::is_ours() { + super::submit_thread::execute(this, std::slice::from_raw_parts(lists, n as usize)); + return; + } q_execute_command_lists(this, n, lists); } +/// The queue's UpdateTileMappings (#8) and CopyTileMappings (#9), split as `queue_entries` are: the +/// title's go behind its submits (`XCL_ASYNC_SUBMIT=1`), which the mappings must not reach. +fn tile_mapping_entries() -> [usize; 2] { + static E: OnceLock<[usize; 2]> = OnceLock::new(); + *E.get_or_init(|| { + [ + super::guard::make_split(q_update_tile_mappings_title as usize, q_update_tile_mappings as usize), + super::guard::make_split(q_copy_tile_mappings_title as usize, q_copy_tile_mappings as usize), + ] + }) +} + +type UpdateTileMappingsFn = unsafe extern "system" fn(*mut c_void, usize, u32, usize, usize, usize, u32, usize, usize, usize, u32); +type CopyTileMappingsFn = unsafe extern "system" fn(*mut c_void, usize, usize, usize, usize, usize, u32); + +unsafe extern "system" fn q_update_tile_mappings(this: *mut c_void, res: usize, regions: u32, coords: usize, sizes: usize, heap: usize, ranges: u32, flags: usize, offsets: usize, counts: usize, f: u32) { + let pc: UpdateTileMappingsFn = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12CommandQueue", "UpdateTileMappings"))); + pc(this, res, regions, coords, sizes, heap, ranges, flags, offsets, counts, f); +} + +unsafe extern "system" fn q_update_tile_mappings_title(this: *mut c_void, res: usize, regions: u32, coords: usize, sizes: usize, heap: usize, ranges: u32, flags: usize, offsets: usize, counts: usize, f: u32) { + super::submit_thread::drain(super::submit_thread::Drain::TileMappings); + q_update_tile_mappings(this, res, regions, coords, sizes, heap, ranges, flags, offsets, counts, f); +} + +unsafe extern "system" fn q_copy_tile_mappings(this: *mut c_void, dst: usize, dst_at: usize, src: usize, src_at: usize, size: usize, f: u32) { + let pc: CopyTileMappingsFn = std::mem::transmute(orig_fn(this, pc_slot!("ID3D12CommandQueue", "CopyTileMappings"))); + pc(this, dst, dst_at, src, src_at, size, f); +} + +unsafe extern "system" fn q_copy_tile_mappings_title(this: *mut c_void, dst: usize, dst_at: usize, src: usize, src_at: usize, size: usize, f: u32) { + super::submit_thread::drain(super::submit_thread::Drain::TileMappings); + q_copy_tile_mappings(this, dst, dst_at, src, src_at, size, f); +} + /// The calls of the queue's page-mapping method recorded so far and what they did, summed, and /// when their line was logged last. static PAGE_MAPPINGS: Mutex<(u64, crate::hle::kernelx::mirrors::Mapped, Option)> = diff --git a/crates/xcl/src/hle/d3d12x/submit_cost.rs b/crates/xcl/src/hle/d3d12x/submit_cost.rs index f0da57f19a..a1c63533bc 100644 --- a/crates/xcl/src/hle/d3d12x/submit_cost.rs +++ b/crates/xcl/src/hle/d3d12x/submit_cost.rs @@ -130,13 +130,23 @@ pub(super) fn textures_uploaded(textures: usize, bytes: usize, took: Duration) { /// A whole submit (from the hook's entry) is done. pub(super) fn done(t0: Instant) { - add(TOTAL, t0.elapsed()); - // `XCL_LOOK_STATS=2`: the title's submits for `api_cost` (and the thread that makes them), - // not XCL's own ones inside a submit or a present: those are in that one's time + note_title_call(t0); + tally(t0); +} + +/// `XCL_LOOK_STATS=2`: the title's submit took its thread from `t0` to now – for `api_cost` (and +/// the thread that makes them), not XCL's own ones inside a submit or a present: those are in that +/// one's time. +pub(super) fn note_title_call(t0: Instant) { if super::look_stats::deep() && !super::title_textures::is_own_work() && !super::present::presenting() { crate::hle::api_cost::note_submitter(); crate::hle::api_cost::add(crate::hle::api_cost::Call::Submit, t0.elapsed()); } +} + +/// A whole submit, made from `t0` on, is done: into the averages (the 1024-submit lines). +pub(super) fn tally(t0: Instant) { + add(TOTAL, t0.elapsed()); let n = SUM[N].fetch_add(1, Ordering::Relaxed) + 1; if n % 1024 != 0 { return; diff --git a/crates/xcl/src/hle/d3d12x/submit_thread.rs b/crates/xcl/src/hle/d3d12x/submit_thread.rs new file mode 100644 index 0000000000..439e4018e5 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/submit_thread.rs @@ -0,0 +1,761 @@ +//! `XCL_ASYNC_SUBMIT=1` (off unless set): the title's ExecuteCommandLists hand its lists to a +//! thread of XCL's and return; that thread does what the submit did on the title's thread – the +//! refresh of the textures in title memory, the waits for tile mappings, the PC submission and +//! what XCL does after it – in the order of the title's calls. +//! +//! Measured in a retail title's world (amd-dev, RX 9070 XT): its submitting thread spent 1.75 s +//! of every 2 s inside ExecuteCommandLists, ~100 submits a second at 8.8–11 ms each, of which the +//! driver's own call was 0.02 ms. The title does nothing with what that work does: it only has to +//! be done before the lists run, in order. +//! +//! The idea is VIctory-Neo's `VICTORY_ASYNC_SUBMIT` (KyleS98/VIctory-Neo, +//! , `crates/victory-gpu/src/queue/behind.rs`, itself after +//! fxceless/victory-fork f85101b6; GPL-3.0-or-later, as XCL). Neo keeps the fences itself and holds +//! a queue's work at its waits; here fences and queue waits are the PC's, so the line keeps nothing +//! but the order: one line for all the title's queues, in the order of its calls. +//! +//! - ExecuteCommandLists: the title's thread notes the submit (`capture`), records the dispatches +//! it put off (they must be in the lists before the title may Reset them) and takes the PC lists +//! and segments its lists are now; the line holds a reference to each title list and the queue. +//! - The title's Signal and Wait on a queue go in behind what the line holds (at once when it is +//! empty): a fence is not reached before the work in front of it was submitted. A title's thread +//! that waits for one waits for this thread, which never waits for the title's. +//! - What has to see the title's earlier submits made drains the line first (`drain`). +//! - A PC list in the line counts as in flight (`alloc_pool::in_flight`): the title's Reset records +//! on another PC list, the allocator its recording is on is put aside at a Reset of the title's +//! allocator, and its segments keep what they recorded until they are submitted +//! (`when_submitted`). +//! - A last Release held by `late_release` waits for the line too: its batch is sealed once the +//! line has done what was in it at the release (`pushed`, `done`). + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex, MutexGuard}; +use std::time::Instant; + +use crate::util::HRESULT; + +const S_OK: HRESULT = 0; + +/// A line of work done by one thread in the order it was put in. +pub(super) struct Line { + state: Mutex>, + /// something was put in + work: Condvar, + /// something was done + moved: Condvar, + /// `State::pushed` and `State::done`, read without the lock + pushed: AtomicU64, + done: AtomicU64, +} + +struct State { + items: VecDeque, + /// entries put in so far, and those done (in order: the n-th put in is done once `done >= n`) + pushed: u64, + done: u64, +} + +impl Line { + pub(super) const fn new() -> Self { + Line { + state: Mutex::new(State { items: VecDeque::new(), pushed: 0, done: 0 }), + work: Condvar::new(), + moved: Condvar::new(), + pushed: AtomicU64::new(0), + done: AtomicU64::new(0), + } + } + + fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn put(&self, mut s: MutexGuard<'_, State>, t: T) { + s.items.push_back(t); + s.pushed += 1; + self.pushed.store(s.pushed, Ordering::Release); + drop(s); + self.work.notify_one(); + } + + /// Puts `t` at the end: how many were in the line or being done before it. + pub(super) fn push(&self, t: T) -> u64 { + let s = self.lock(); + let before = s.pushed - s.done; + self.put(s, t); + before + } + + /// Puts `t` at the end if anything is in the line or being done; else gives it back, to be done + /// at once by the caller (nothing is before it). + pub(super) fn push_unless_idle(&self, t: T) -> Option { + let s = self.lock(); + if s.pushed == s.done { + return Some(t); + } + self.put(s, t); + None + } + + /// Waits for something in the line and takes the first `pick(items)` entries (at least one). + pub(super) fn take(&self, pick: impl FnOnce(&VecDeque) -> usize) -> Vec { + let mut s = self.lock(); + while s.items.is_empty() { + s = self.work.wait(s).unwrap_or_else(|e| e.into_inner()); + } + let n = pick(&s.items).clamp(1, s.items.len()); + s.items.drain(..n).collect() + } + + /// An entry taken was done. + pub(super) fn finished(&self) { + let mut s = self.lock(); + s.done += 1; + self.done.store(s.done, Ordering::Release); + drop(s); + self.moved.notify_all(); + } + + /// Waits until everything put in before this call was done. Whether anything was left. + pub(super) fn drain(&self) -> bool { + let mut s = self.lock(); + let ticket = s.pushed; + if s.done >= ticket { + return false; + } + while s.done < ticket { + s = self.moved.wait(s).unwrap_or_else(|e| e.into_inner()); + } + true + } + + /// Waits while more than `most` are in the line or being done. Whether it waited. + pub(super) fn room(&self, most: u64) -> bool { + let mut s = self.lock(); + if s.pushed - s.done <= most { + return false; + } + while s.pushed - s.done > most { + s = self.moved.wait(s).unwrap_or_else(|e| e.into_inner()); + } + true + } + + /// Entries put in so far (the last one's number). + pub(super) fn pushed(&self) -> u64 { + self.pushed.load(Ordering::Acquire) + } + + /// Entries done so far. + pub(super) fn done(&self) -> u64 { + self.done.load(Ordering::Acquire) + } +} + +/// The thread runs (`XCL_ASYNC_SUBMIT=1`). +static RUNNING: AtomicBool = AtomicBool::new(false); + +thread_local! { + /// This is the thread that does what is in the line. + static OURS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether the calling thread is the one that does what is in the line. +pub(super) fn is_ours() -> bool { + OURS.with(|o| o.get()) +} + +/// A PC list's submits in the line, and what waits for the last of them to be made. +#[derive(Default)] +struct Queued { + count: u32, + then: Vec>, +} + +/// PC list → its submits in the line (absent: none) +static QUEUED: Mutex>> = Mutex::new(None); + +fn queued_map() -> MutexGuard<'static, Option>> { + QUEUED.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether the PC list `list` is in a submit of the title's the line has not made yet. +pub(super) fn queued(list: usize) -> bool { + RUNNING.load(Ordering::Acquire) && queued_map().as_ref().is_some_and(|m| m.get(&list).is_some_and(|q| q.count > 0)) +} + +/// The PC lists `lists` are in a submit put in the line. +fn note_queued(lists: &[usize]) { + let mut g = queued_map(); + let m = g.get_or_insert_with(HashMap::new); + for &l in lists { + m.entry(l).or_default().count += 1; + } +} + +/// The submit of the PC lists `lists` was made. What waited for the last one of a list's +/// (`when_submitted`) runs first, while the list still counts as in the line: another recording +/// must not take it before that. +fn note_unqueued(lists: &[usize]) { + let first: Vec> = { + let mut g = queued_map(); + let Some(m) = g.as_mut() else { return }; + let mut first = Vec::new(); + for l in lists { + if let Some(q) = m.get_mut(l).filter(|q| q.count == 1) { + first.append(&mut q.then); + } + } + first + }; + for f in first { + f(); + } + // (what was put behind it meanwhile runs once it is gone) + let late: Vec> = { + let mut g = queued_map(); + let Some(m) = g.as_mut() else { return }; + let mut late = Vec::new(); + for l in lists { + if let Some(q) = m.get_mut(l) { + q.count = q.count.saturating_sub(1); + if q.count == 0 { + late.extend(m.remove(l).into_iter().flat_map(|q| q.then)); + } + } + } + late + }; + for f in late { + f(); + } +} + +/// `f` once the PC list `list` is in no submit of the line any more: at once if it is in none. (The +/// title's Reset of a split list: its segments keep what they recorded until they are submitted.) +pub(super) fn when_submitted(list: usize, f: impl FnOnce() + Send + 'static) { + { + let mut g = queued_map(); + if let Some(q) = g.as_mut().and_then(|m| m.get_mut(&list)).filter(|q| q.count > 0) { + q.then.push(Box::new(f)); + return; + } + } + f(); +} + +/// Why a title's call drains the line. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Drain { + /// PresentX: the frame's copy goes behind its work + Present, + /// CopyPageMappingsBatchX: a submit in the line reads the pages through the mappings it was made with + PageMappings, + /// the queue's UpdateTileMappings / CopyTileMappings + TileMappings, + /// KickoffX submits on the list's queue at once + Kickoff, + /// a Reset of a PC list still in the line (no other to record on) + ListReset, + /// the last Release of an allocator with recordings in the line + Release, +} + +/// The title's line, seen from what XCL does around it: entries put in so far and done so far (0 +/// while the thread does not run). +pub(super) fn pushed() -> u64 { + LINE.pushed() +} + +pub(super) fn done() -> u64 { + LINE.done() +} + +/// Before something that has to see the title's submits so far made: they are. Not on the thread +/// of the line (it is inside one of them), and at once while there is no thread. +pub(super) fn drain(why: Drain) { + if !RUNNING.load(Ordering::Acquire) || is_ours() { + return; + } + let t = Instant::now(); + if LINE.drain() { + stats::drained(why, t.elapsed()); + } +} + +/// What the title's queues put in the line. +enum Op { + /// a submit: the title's lists (the line holds a reference to each), the PC lists they run as, + /// and the PC allocators their recordings are on (`alloc_pool::queued`) + Execute { lists: Vec, mapped: Vec, backings: Vec }, + Signal { fence: usize, value: u64 }, + Wait { fence: usize, value: u64 }, + /// (tests: something the thread does in its turn) + #[cfg(test)] + Test(Box), +} + +/// An entry of the line: the queue (the line holds a reference to it) and what is done on it. +struct Entry { + queue: usize, + op: Op, +} + +static LINE: Line = Line::new(); + +/// Whether the title's submits are made by the thread of the line (`XCL_ASYNC_SUBMIT=1`; started +/// at the first call). It needs the allocators' stand-ins (`alloc_pool`, `XCL_ALLOC_SWAP`) and the +/// title's own list objects (not `XCL_CONSOLE_LISTS`). +pub(super) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_ASYNC_SUBMIT").is_ok_and(|v| v.trim() == "1") { + return false; + } + if !super::alloc_pool::enabled() || super::console_list::enabled() { + crate::xlog_warn!("D3D12.X: XCL_ASYNC_SUBMIT=1 needs XCL_ALLOC_SWAP on and XCL_CONSOLE_LISTS off – the title's threads make their submits"); + return false; + } + let worker = || { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL}; + // (as Neo's: the title's frames wait for this thread) + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) }; + OURS.with(|o| o.set(true)); + serve() + }; + match std::thread::Builder::new().name("xcl-submit".into()).spawn(worker) { + Ok(_) => { + RUNNING.store(true, Ordering::Release); + crate::xlog_info!("D3D12.X: the title's submits are made by a thread of XCL's, in the order of its calls (XCL_ASYNC_SUBMIT=1; at most {} in its line)", depth()); + true + } + Err(e) => { + crate::xlog_warn!("D3D12.X: XCL_ASYNC_SUBMIT=1: no thread for the title's submits ({e}) – its threads make them"); + false + } + } + }) +} + +/// How many entries the line may hold when a submit returns (`XCL_ASYNC_SUBMIT_DEPTH`, 64: two +/// frames of a retail title's world and more). +fn depth() -> u64 { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_ASYNC_SUBMIT_DEPTH").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64).max(1)) +} + +unsafe fn add_ref(p: usize) { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(p as *const *const usize)).add(1)); + f(p as *mut c_void); +} + +/// (through the object's own vtable: the last one ends it as the title's would) +unsafe fn release(p: usize) { + let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(p as *const *const usize)).add(2)); + f(p as *mut c_void); +} + +/// The title's ExecuteCommandLists of `lists` (n > 0) on `queue`: into the line. +pub(super) unsafe fn execute(queue: *mut c_void, lists: &[*mut c_void]) { + let t0 = Instant::now(); + super::real::note_title_submit(queue, lists); + { + let _in_pc = super::pso_async::pc_call(); + super::real::record_deferred_of(lists); + } + let mapped = super::real::pc_lists_of(lists); + // (the title may release a list it submitted, and its queue: they stay until they were used) + for &l in lists { + add_ref(l as usize); + } + add_ref(queue as usize); + let pcs: Vec = mapped.iter().map(|&p| p as usize).collect(); + note_queued(&pcs); + let backings = super::alloc_pool::queued(&mapped); + let lists = lists.iter().map(|&l| l as usize).collect(); + let before = LINE.push(Entry { queue: queue as usize, op: Op::Execute { lists, mapped: pcs, backings } }); + stats::pushed(before); + if before >= depth() { + let t = Instant::now(); + LINE.room(depth() - 1); + stats::room(t.elapsed()); + } + stats::title_submit(t0.elapsed()); + super::submit_cost::note_title_call(t0); +} + +/// The title's Signal of `fence` (one of its own) with `value` on `queue`: behind what the line +/// holds, at once when it is empty. S_OK when it goes in the line (a console's does not fail). +pub(super) unsafe fn signal(queue: *mut c_void, fence: usize, value: u64) -> HRESULT { + put(queue, Op::Signal { fence, value }) +} + +/// The title's Wait of `queue` for `fence` to reach `value`: as `signal`. +pub(super) unsafe fn wait(queue: *mut c_void, fence: usize, value: u64) -> HRESULT { + put(queue, Op::Wait { fence, value }) +} + +unsafe fn put(queue: *mut c_void, op: Op) -> HRESULT { + add_ref(queue as usize); + match LINE.push_unless_idle(Entry { queue: queue as usize, op }) { + None => S_OK, + Some(e) => { + release(e.queue); + run_fence_op(queue, e.op) + } + } +} + +unsafe fn run_fence_op(queue: *mut c_void, op: Op) -> HRESULT { + match op { + Op::Signal { fence, value } => super::real::queue_signal_now(queue, fence, value), + Op::Wait { fence, value } => super::real::queue_wait_now(queue, fence, value), + _ => S_OK, + } +} + +/// The thread: does what is in the line for as long as the process runs. A panic ends the run +/// (an entry not done would hold the title's fences, and its threads waiting for them, for good). +fn serve() -> ! { + loop { + let batch = LINE.take(|_| 1); + for e in batch { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { run(e) })).is_err() { + let msg = "the thread that makes the title's submits (XCL_ASYNC_SUBMIT=1) panicked – the title is stopped".to_string(); + crate::xlog_error!("D3D12.X: {msg}"); + crate::report::write_final(Some(msg)); + crate::log::flush(); + unsafe { windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), 1) }; + } + LINE.finished(); + } + } +} + +/// One entry, as the title's thread would have done it. +unsafe fn run(e: Entry) { + let t = Instant::now(); + let queue = e.queue as *mut c_void; + match e.op { + #[cfg(test)] + Op::Test(f) => return f(), + Op::Execute { lists, mapped, backings } => { + let title: Vec<*mut c_void> = lists.iter().map(|&l| l as *mut c_void).collect(); + let pcs: Vec<*mut c_void> = mapped.iter().map(|&l| l as *mut c_void).collect(); + let _in_pc = super::pso_async::pc_call(); + // (not while a stop for a driver error is being handled: `watch`) + super::watch::wait_while_held(); + let submit_t0 = Instant::now(); + super::title_textures::refresh_for(queue, &title); + let t_lists = Instant::now(); + super::submit_cost::call(t_lists - submit_t0); + super::real::execute_mapped(queue, &pcs, t_lists); + super::submit_cost::tally(submit_t0); + note_unqueued(&mapped); + super::alloc_pool::unqueued(queue, &backings); + for l in lists { + release(l); + } + } + op => { + if run_fence_op(queue, op) < 0 { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: XCL_ASYNC_SUBMIT: a Signal / Wait of the title's on queue {queue:p} failed"); + } + super::real::stop_if_device_removed(); + } + } + } + release(e.queue); + stats::ran(t.elapsed()); +} + +/// Diagnostics of the line (`stats::line`). +mod stats { + use super::Drain; + use std::time::Duration; + + pub(super) fn drained(_why: Drain, _d: Duration) {} + pub(super) fn pushed(_before: u64) {} + pub(super) fn room(_d: Duration) {} + pub(super) fn title_submit(_d: Duration) {} + pub(super) fn ran(_d: Duration) {} +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::time::Duration; + + /// Entries are taken in the order they were put in, as many as asked for; a drain is over at + /// once while nothing is left. + #[test] + fn the_line_keeps_the_order_of_its_entries() { + let line: Line = Line::new(); + assert!(!line.drain()); + assert_eq!(line.push(1), 0); + assert_eq!(line.push(2), 1); + assert_eq!(line.push(3), 2); + assert_eq!(line.take(|items| items.iter().take_while(|&&i| i < 3).count()), [1, 2]); + assert_eq!(line.take(|_| 0), [3], "at least one"); + assert_eq!((line.pushed(), line.done()), (3, 0)); + for _ in 0..3 { + line.finished(); + } + assert_eq!(line.done(), 3); + assert!(!line.drain()); + } + + /// Something put in while the line is idle is done at once by the caller; while an entry is in + /// the line or being done, it goes in behind it. + #[test] + fn a_signal_goes_behind_what_the_line_holds() { + let line: Line<&str> = Line::new(); + assert_eq!(line.push_unless_idle("signal"), Some("signal"), "nothing before it"); + line.push("submit"); + assert_eq!(line.push_unless_idle("signal"), None); + assert_eq!(line.take(|_| 1), ["submit"]); + // the submit is being done: behind it still + assert_eq!(line.push_unless_idle("wait"), None); + line.finished(); + assert_eq!(line.take(|_| 2), ["signal", "wait"]); + line.finished(); + line.finished(); + assert_eq!(line.push_unless_idle("signal"), Some("signal")); + } + + /// With the thread: a title's thread that waits for a fence a queued signal sets is not held by + /// the thread, a drain comes back when everything put in before it was done (not what came in + /// after), and room is made at the depth asked for. + #[test] + fn a_drain_waits_for_what_was_put_in_before_it() { + let line: &'static Line<(u32, Arc<(Mutex, Condvar)>)> = Box::leak(Box::new(Line::new())); + let log: &'static Mutex> = Box::leak(Box::new(Mutex::new(Vec::new()))); + std::thread::spawn(move || loop { + for (n, gate) in line.take(|_| 1) { + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + log.lock().unwrap().push(n); + line.finished(); + } + }); + let open = || Arc::new((Mutex::new(true), Condvar::new())); + let shut = Arc::new((Mutex::new(false), Condvar::new())); + line.push((1, shut.clone())); + line.push((2, open())); + // the "fence" of entry 2: the title's thread waits for it while the thread is held by 1 + let opener = { + let shut = shut.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + *shut.0.lock().unwrap() = true; + shut.1.notify_all(); + }) + }; + assert!(line.room(1), "two in the line, one asked for"); + assert!(line.done() >= 1); + // (2 may be done already) + line.drain(); + assert_eq!(*log.lock().unwrap(), [1, 2]); + opener.join().unwrap(); + // what is put in after a drain began is not waited for by it + let late = Arc::new((Mutex::new(false), Condvar::new())); + line.push((3, late.clone())); + let t = std::thread::spawn(move || line.drain()); + std::thread::sleep(Duration::from_millis(10)); + assert!(!t.is_finished(), "3 was put in before the drain"); + *late.0.lock().unwrap() = true; + late.1.notify_all(); + assert!(t.join().unwrap()); + assert_eq!(*log.lock().unwrap(), [1, 2, 3]); + assert!(!line.room(0)); + } + + /// What waits for a PC list's submits runs once the last of them was made, while the list still + /// counts as in the line; at once for a list in none. + #[test] + fn what_waits_for_a_list_runs_when_its_last_submit_is_made() { + // (lists of this test only: the map is the process's) + let (a, b) = (0x7e57_0001usize, 0x7e57_0002usize); + let ran: Arc>> = Default::default(); + let note = |what: &'static str, list: usize| { + let ran = ran.clone(); + move || { + let still = queued_map().as_ref().is_some_and(|m| m.get(&list).is_some_and(|q| q.count > 0)); + ran.lock().unwrap().push((what, still)); + } + }; + when_submitted(a, note("not queued", a)); + assert_eq!(*ran.lock().unwrap(), [("not queued", false)]); + note_queued(&[a, b]); + note_queued(&[a]); + when_submitted(a, note("after a", a)); + when_submitted(b, note("after b", b)); + note_unqueued(&[a, b]); + assert_eq!(ran.lock().unwrap()[1..], [("after b", true)], "a has another submit in the line"); + note_unqueued(&[a]); + assert_eq!(ran.lock().unwrap()[2..], [("after a", true)]); + assert!(queued_map().as_ref().is_some_and(|m| !m.contains_key(&a) && !m.contains_key(&b))); + when_submitted(b, note("b again", b)); + assert_eq!(ran.lock().unwrap().len(), 4); + } + + /// A call of slot `slot` of `this`'s vtable with three integer arguments, from code that is + /// registered as a title's image (`title_image`): the queue's split entries take it for the + /// title's. + #[inline(never)] + unsafe fn as_title(slot: usize, this: *mut c_void, a1: usize, a2: usize, a3: usize) -> usize { + let f: unsafe extern "system" fn(*mut c_void, usize, usize, usize) -> usize = std::mem::transmute(*(*(this as *const *const usize)).add(slot)); + // (the call's return address stays inside this function) + std::hint::black_box(f(this, a1, a2, a3)) + } + + /// `as_title` registered as an image of the title's. + fn title_image() -> usize { + use windows_sys::Win32::System::Diagnostics::Debug::RtlLookupFunctionEntry; + let mut image = 0; + let entry = unsafe { RtlLookupFunctionEntry(as_title as usize as u64, &mut image, std::ptr::null_mut()).as_ref() }.expect("unwind entry of as_title"); + let base = (image + u64::from(entry.BeginAddress)) as usize; + crate::modules::register_mapped(Arc::new(crate::modules::MappedModule { + name: "submit-thread-title".into(), + path: Default::default(), + base, + size: (entry.EndAddress - entry.BeginAddress) as usize, + entry_rva: 0, + is_dll: false, + exports: Default::default(), + tls_callbacks: Default::default(), + no_thread_calls: Default::default(), + initialized: Default::default(), + stack_reserve: 0, + })); + base + } + + /// With `XCL_ASYNC_SUBMIT=1` (in a process of its own): the title's submits go into the line + /// and return; a list it resets at once records on another PC list while its submit is still in + /// the line, and both recordings run; its Signal behind them is not reached before the thread + /// has made them; and the thread makes them all while the title's thread waits for the fence. + #[test] + fn gpu_title_submits_made_by_the_thread_keep_their_order_and_recordings() { + const CHILD: &str = "XCL_TEST_SUBMIT_THREAD_CHILD"; + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::submit_thread::tests::gpu_title_submits_made_by_the_thread_keep_their_order_and_recordings", "--nocapture", "--test-threads=1"]) + .env(CHILD, "1") + .env("XCL_ASYNC_SUBMIT", "1") + .output() + .unwrap(); + let out = String::from_utf8_lossy(&output.stdout); + assert!(output.status.success() && out.contains("1 passed"), "{out}\n{}", String::from_utf8_lossy(&output.stderr)); + return; + } + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + assert!(on(), "XCL_ASYNC_SUBMIT=1 starts the thread"); + let image = title_image(); + unsafe { + let raw = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw).unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let buffer = |heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 512, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r).unwrap(); + r.unwrap() + }; + let upload = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let readback = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + for k in 0..512 { + *(p as *mut u8).add(k) = if k < 256 { 0xA1 } else { 0x5C }; + } + upload.Unmap(0, None); + // the title's list, as the title gets it (`device_x::create_list`) + let mut w = std::ptr::null_mut(); + let hr = super::super::device_x::create_command_list_pc(raw, 0, ty.0 as u32, alloc.as_raw() as usize, 0, &ID3D12GraphicsCommandList::IID as *const _ as *const _, &mut w); + assert!(hr >= 0 && !w.is_null()); + let list = ID3D12GraphicsCommandList::from_raw_borrowed(&w).unwrap(); + let primary = super::super::title_list::backing(w).unwrap(); + let q = queue.as_raw(); + + // the thread is held by an entry before the title's + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let held = gate.clone(); + LINE.push(Entry { + queue: 0, + op: Op::Test(Box::new(move || { + let mut open = held.0.lock().unwrap(); + while !*open { + open = held.1.wait(open).unwrap(); + } + })), + }); + list.CopyBufferRegion(&readback, 0, &upload, 0, 256); + list.Close().unwrap(); + let one = [w]; + as_title(10, q, 1, one.as_ptr() as usize, 0); + assert!(queued(primary as usize), "the submit is in the line"); + assert!(super::super::alloc_pool::in_flight(primary as usize)); + // recording again at once: on another PC list, the first recording stays as it was + let reset: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(*(*(w as *const *const usize)).add(10)); + assert!(reset(w, alloc.as_raw() as usize, 0) >= 0); + assert_ne!(super::super::title_list::backing(w), None); + let mut now = Vec::new(); + assert!(super::super::title_list::push_segments(w, &mut now)); + assert_ne!(now[0], primary, "the new recording is on a stand-in"); + list.CopyBufferRegion(&readback, 256, &upload, 256, 256); + list.Close().unwrap(); + as_title(10, q, 1, one.as_ptr() as usize, 0); + // the Signal goes behind the submits (slot #14: the older layout's Signal) + assert_eq!(as_title(14, q, fence.as_raw() as usize, 1, 0) as u32, 0); + assert_eq!(fence.GetCompletedValue(), 0, "not signalled before the submits are made"); + let pushed = LINE.pushed(); + assert!(pushed - LINE.done() >= 4, "held, two submits and the signal are in the line"); + + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + // the title's thread waits for its fence: the thread makes what is in front of it + let ran = crate::gpu::fence::wait(&fence, 1, dev, None, 10_000).is_ok(); + drain(Drain::Present); + assert!(ran, "the fence is reached"); + assert!(LINE.done() >= pushed); + assert!(dev.GetDeviceRemovedReason().is_ok()); + assert!(!queued(primary as usize) && !queued(now[0] as usize)); + let mut r = std::ptr::null_mut(); + readback.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 512 }), Some(&mut r)).unwrap(); + let bytes = std::slice::from_raw_parts(r as *const u8, 512).to_vec(); + readback.Unmap(0, None); + assert!(bytes[..256].iter().all(|&b| b == 0xA1), "the first recording ran"); + assert!(bytes[256..].iter().all(|&b| b == 0x5C), "the second recording ran"); + // the title lets its list go: the line gave its references back + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(w as *const *const usize)).add(2)); + assert_eq!(release(w), 0); + } + crate::modules::unregister_mapped(image); + } +} diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 6065ff937e..1efc2b3a51 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -195,11 +195,15 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: m.insert(active, this as usize); drop(wg); for seg in moved { - super::bind::reset(seg as *mut c_void, 0, 0); - super::list_x::clear_segment_state(seg); - // a spare records again only after its next Reset: it does not hold its - // allocator meanwhile - super::alloc_pool::park_list(seg); + // (a segment in a submit the submit thread has not made yet keeps what it recorded + // until then: its waits, signals and copies back are made with it) + super::submit_thread::when_submitted(seg, move || { + super::bind::reset(seg as *mut c_void, 0, 0); + super::list_x::clear_segment_state(seg); + // a spare records again only after its next Reset: it does not hold its + // allocator meanwhile + super::alloc_pool::park_list(seg); + }); } // nor does the previous recording a stand-in now replaces: it is not reset here either if stand_in.is_some() { From 9f9a9bce122e5584edf739fd2d0579f28aa0099d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:51:33 +0100 Subject: [PATCH 073/175] D3D12.X: the submit thread refreshes once for a batch of submits With XCL_ASYNC_SUBMIT=1 the thread takes what the line holds up to the first submit to another queue than the first one's (signals and waits of any queue go along, at most XCL_ASYNC_SUBMIT_BATCH = 64 entries) and runs `title_textures::refresh_for` once, with all their lists, before them; then each entry goes as before, in order. A batch of one submit refreshes as the title's thread did. The refresh is mostly a fixed cost a call: in a retail title's world 6.4-8.9 ms of each 8.8-11 ms submit (look 1.4-1.6, sparse lock 1.9-2.7, textures 1.0-2.5, scan 0.5, upload 0.3-0.55, ~1 ms rest), ~28 submits a frame. Its uploads go on the batch's queue and it makes that queue wait for XCL's own uploads, as a refresh for each of its submits would have; a submit to another queue gets a refresh of its own, so no texture uploaded on one queue is read on another without a wait. The batch's refresh sees the CPU's writes up to when it runs, which is after the title made all of the batch's submits: a title writes what submitted work reads only after a fence behind that work, which the thread reaches only after it made it. The first submit's time in the 1024-submit averages has the batch's refresh in it, so the averages stay the time the thread spent a submit. Neo's line takes submissions behind one another along likewise (`take_along`, VICTORY_JOIN_PARTS); here only the refresh is shared. (cherry picked from commit 01dc7204e35a9d941eedf3b0270caf4164c9e959) --- crates/xcl/src/hle/d3d12x/submit_thread.rs | 129 ++++++++++++++++++--- 1 file changed, 115 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/submit_thread.rs b/crates/xcl/src/hle/d3d12x/submit_thread.rs index 439e4018e5..3ca36ec3d9 100644 --- a/crates/xcl/src/hle/d3d12x/submit_thread.rs +++ b/crates/xcl/src/hle/d3d12x/submit_thread.rs @@ -416,26 +416,103 @@ unsafe fn run_fence_op(queue: *mut c_void, op: Op) -> HRESULT { } } -/// The thread: does what is in the line for as long as the process runs. A panic ends the run -/// (an entry not done would hold the title's fences, and its threads waiting for them, for good). +/// How many entries the thread takes at once (`XCL_ASYNC_SUBMIT_BATCH`, 64; 1: a refresh for +/// each submit, as on the title's thread). +fn batch_most() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_ASYNC_SUBMIT_BATCH").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64).max(1)) +} + +/// How many of the first `items` (at most `most`) go in one batch: up to the first submit to +/// another queue than the batch's first submit. Signals and waits of any queue go along. The +/// refresh before the batch uploads on that queue what all its submits read, and makes it wait for +/// XCL's own uploads – as a refresh for each of them would have on the same queue; a submit to +/// another queue gets its own (a texture uploaded on one queue is not waited for on another). +fn batch_len(items: &VecDeque, most: usize) -> usize { + let mut queue = None; + let mut n = 0; + for e in items.iter().take(most) { + if matches!(e.op, Op::Execute { .. }) { + match queue { + None => queue = Some(e.queue), + Some(q) if q != e.queue => break, + Some(_) => {} + } + } + n += 1; + } + n +} + +/// The thread: does what is in the line for as long as the process runs, a batch at a time. A +/// panic ends the run (an entry not done would hold the title's fences, and its threads waiting +/// for them, for good). fn serve() -> ! { loop { - let batch = LINE.take(|_| 1); + let batch = LINE.take(|items| batch_len(items, batch_most())); + let submits = batch.iter().filter(|e| matches!(e.op, Op::Execute { .. })).count(); + stats::batch(submits); + // (one submit: its own refresh, as on the title's thread) + let batched = submits > 1; + let mut began = if batched { guarded(|| unsafe { refresh_batch(&batch) }) } else { None }; for e in batch { - if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { run(e) })).is_err() { - let msg = "the thread that makes the title's submits (XCL_ASYNC_SUBMIT=1) panicked – the title is stopped".to_string(); - crate::xlog_error!("D3D12.X: {msg}"); - crate::report::write_final(Some(msg)); - crate::log::flush(); - unsafe { windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), 1) }; - } + let refresh = match &e.op { + Op::Execute { .. } if !batched => Refresh::Own, + // (the first submit's time has the batch's refresh in it) + Op::Execute { .. } => Refresh::Done(began.take()), + _ => Refresh::Done(None), + }; + guarded(|| unsafe { run(e, refresh) }); LINE.finished(); } } } +fn guarded(f: impl FnOnce() -> R) -> R { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) { + Ok(r) => r, + Err(_) => { + let msg = "the thread that makes the title's submits (XCL_ASYNC_SUBMIT=1) panicked – the title is stopped".to_string(); + crate::xlog_error!("D3D12.X: {msg}"); + crate::report::write_final(Some(msg)); + crate::log::flush(); + unsafe { windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), 1) }; + std::process::abort() + } + } +} + +/// One refresh for the submits of `batch` (all to one queue, `batch_len`), before the first of +/// them: when it began. +unsafe fn refresh_batch(batch: &[Entry]) -> Option { + let queue = batch.iter().find(|e| matches!(e.op, Op::Execute { .. }))?.queue as *mut c_void; + let lists: Vec<*mut c_void> = batch + .iter() + .filter_map(|e| match &e.op { + Op::Execute { lists, .. } => Some(lists), + _ => None, + }) + .flatten() + .map(|&l| l as *mut c_void) + .collect(); + let _in_pc = super::pso_async::pc_call(); + super::watch::wait_while_held(); + let t0 = Instant::now(); + super::title_textures::refresh_for(queue, &lists); + super::submit_cost::call(t0.elapsed()); + Some(t0) +} + +/// Whether a submit's refresh is to be done with it, or was done before its batch. +#[derive(Clone, Copy)] +enum Refresh { + Own, + /// (the time it began for the batch's first submit) + Done(Option), +} + /// One entry, as the title's thread would have done it. -unsafe fn run(e: Entry) { +unsafe fn run(e: Entry, refresh: Refresh) { let t = Instant::now(); let queue = e.queue as *mut c_void; match e.op { @@ -447,10 +524,16 @@ unsafe fn run(e: Entry) { let _in_pc = super::pso_async::pc_call(); // (not while a stop for a driver error is being handled: `watch`) super::watch::wait_while_held(); - let submit_t0 = Instant::now(); - super::title_textures::refresh_for(queue, &title); + let submit_t0 = match refresh { + Refresh::Own => { + let t0 = Instant::now(); + super::title_textures::refresh_for(queue, &title); + super::submit_cost::call(t0.elapsed()); + t0 + } + Refresh::Done(began) => began.unwrap_or_else(Instant::now), + }; let t_lists = Instant::now(); - super::submit_cost::call(t_lists - submit_t0); super::real::execute_mapped(queue, &pcs, t_lists); super::submit_cost::tally(submit_t0); note_unqueued(&mapped); @@ -483,6 +566,7 @@ mod stats { pub(super) fn room(_d: Duration) {} pub(super) fn title_submit(_d: Duration) {} pub(super) fn ran(_d: Duration) {} + pub(super) fn batch(_submits: usize) {} } #[cfg(test)] @@ -606,6 +690,23 @@ mod tests { assert_eq!(ran.lock().unwrap().len(), 4); } + /// A batch goes up to the first submit to another queue than its first submit's; the signals + /// and waits in between (of any queue) go along, and it holds at most as many as asked for. + #[test] + fn a_batch_holds_the_submits_to_one_queue_and_what_is_between_them() { + let submit = |queue| Entry { queue, op: Op::Execute { lists: Vec::new(), mapped: Vec::new(), backings: Vec::new() } }; + let signal = |queue| Entry { queue, op: Op::Signal { fence: 0, value: 1 } }; + let wait = |queue| Entry { queue, op: Op::Wait { fence: 0, value: 1 } }; + let items: VecDeque = [submit(1), signal(2), submit(1), wait(1), submit(2), submit(1)].into(); + assert_eq!(batch_len(&items, 64), 4); + assert_eq!(batch_len(&items, 2), 2); + let items: VecDeque = [signal(1), wait(2), submit(3), submit(3), signal(3)].into(); + assert_eq!(batch_len(&items, 64), 5); + let items: VecDeque = [signal(1), wait(2)].into(); + assert_eq!(batch_len(&items, 64), 2); + assert_eq!(batch_len(&VecDeque::new(), 64), 0); + } + /// A call of slot `slot` of `this`'s vtable with three integer arguments, from code that is /// registered as a title's image (`title_image`): the queue's split entries take it for the /// title's. From 077047a31603b98f5d20fbd56d4bf87e6a06ff21 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:53:31 +0100 Subject: [PATCH 074/175] D3D12.X: count what the submit thread does in the 1024-submit lines With XCL_ASYNC_SUBMIT=1, after each 1024-submit average line: the title's submits into the line and their time on its thread, the thread's own time, the batches and submits a batch (and the largest), how many entries were in the line at a submit (and the most), the signals / waits put behind submits and those done at once, the title's waits for room, and the drains by what drained the line (presents, page mappings, tile mappings, KickoffX, list resets, allocator releases) with their time. The title's waits for the line (drains, room) are also a call of their own in the 2-s lines (`api_cost`: "waits for the submit thread"), next to its ExecuteCommandLists, which there count the title's thread's time only. The GPU test now checks its two submits went in one batch. (cherry picked from commit c44e7b9b647eca2d4e2ab1200a4789935cb6fb1a) --- crates/xcl/src/hle/api_cost.rs | 5 +- crates/xcl/src/hle/d3d12x/submit_cost.rs | 4 + crates/xcl/src/hle/d3d12x/submit_thread.rs | 146 +++++++++++++++++++-- 3 files changed, 146 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/api_cost.rs b/crates/xcl/src/hle/api_cost.rs index 8178e3b93e..4421b048ce 100644 --- a/crates/xcl/src/hle/api_cost.rs +++ b/crates/xcl/src/hle/api_cost.rs @@ -29,9 +29,11 @@ pub enum Call { FenceWait, /// copies back landed for the title's look at a fence (`sparse::settle_readbacks_within`) FenceSettle, + /// a wait for the submit thread's line (`XCL_ASYNC_SUBMIT`): a drain, or room in it + SubmitWait, } -pub const CALLS: [(Call, &str); 12] = [ +pub const CALLS: [(Call, &str); 13] = [ (Call::PlacedTexture, "placed textures"), (Call::PlacedBuffer, "placed buffers"), (Call::PhysicalPages, "physical page calls"), @@ -44,6 +46,7 @@ pub const CALLS: [(Call, &str); 12] = [ (Call::WaitFrameEvent, "WaitFrameEventX"), (Call::FenceWait, "blocking fence waits"), (Call::FenceSettle, "copies back settled at fence looks"), + (Call::SubmitWait, "waits for the submit thread"), ]; /// calls, microseconds diff --git a/crates/xcl/src/hle/d3d12x/submit_cost.rs b/crates/xcl/src/hle/d3d12x/submit_cost.rs index a1c63533bc..761c9206d9 100644 --- a/crates/xcl/src/hle/d3d12x/submit_cost.rs +++ b/crates/xcl/src/hle/d3d12x/submit_cost.rs @@ -200,6 +200,10 @@ pub(super) fn tally(t0: Instant) { outside_part(&ms) ); } + // (`XCL_ASYNC_SUBMIT`: how the submit thread made these) + if let Some(line) = super::submit_thread::line() { + crate::xlog_info!("{line}"); + } *g = Some(Last { sum: now, parts, tex, at: Instant::now() }); } diff --git a/crates/xcl/src/hle/d3d12x/submit_thread.rs b/crates/xcl/src/hle/d3d12x/submit_thread.rs index 3ca36ec3d9..e380240f5a 100644 --- a/crates/xcl/src/hle/d3d12x/submit_thread.rs +++ b/crates/xcl/src/hle/d3d12x/submit_thread.rs @@ -399,7 +399,9 @@ pub(super) unsafe fn wait(queue: *mut c_void, fence: usize, value: u64) -> HRESU unsafe fn put(queue: *mut c_void, op: Op) -> HRESULT { add_ref(queue as usize); - match LINE.push_unless_idle(Entry { queue: queue as usize, op }) { + let left = LINE.push_unless_idle(Entry { queue: queue as usize, op }); + stats::fence_op(left.is_none()); + match left { None => S_OK, Some(e) => { release(e.queue); @@ -454,7 +456,9 @@ fn serve() -> ! { stats::batch(submits); // (one submit: its own refresh, as on the title's thread) let batched = submits > 1; + let t = Instant::now(); let mut began = if batched { guarded(|| unsafe { refresh_batch(&batch) }) } else { None }; + stats::ran(t.elapsed()); for e in batch { let refresh = match &e.op { Op::Execute { .. } if !batched => Refresh::Own, @@ -503,6 +507,11 @@ unsafe fn refresh_batch(batch: &[Entry]) -> Option { Some(t0) } +/// The line's part of the 1024-submit lines (`submit_cost`): None while nothing went through it. +pub(super) fn line() -> Option { + stats::line() +} + /// Whether a submit's refresh is to be done with it, or was done before its batch. #[derive(Clone, Copy)] enum Refresh { @@ -556,17 +565,125 @@ unsafe fn run(e: Entry, refresh: Refresh) { stats::ran(t.elapsed()); } -/// Diagnostics of the line (`stats::line`). +/// Diagnostics of the line, for the 1024-submit lines (`line`). mod stats { use super::Drain; + use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; use std::time::Duration; - pub(super) fn drained(_why: Drain, _d: Duration) {} - pub(super) fn pushed(_before: u64) {} - pub(super) fn room(_d: Duration) {} - pub(super) fn title_submit(_d: Duration) {} - pub(super) fn ran(_d: Duration) {} - pub(super) fn batch(_submits: usize) {} + /// Since the last line: the title's submits into the line and their time on its thread (µs); + /// the thread's time (µs, the batches' refreshes in it); batches with a submit and their + /// submits, the largest; the entries in the line when a submit came (summed) and the most; + /// signals and waits put behind submits and those done at once; the title's waits for room in + /// the line (count, µs); then a count and µs for each `Drain`. + static S: [AtomicU64; 12 + 2 * DRAINS] = [const { AtomicU64::new(0) }; 12 + 2 * DRAINS]; + const TITLE_N: usize = 0; + const TITLE_US: usize = 1; + const BUSY_US: usize = 2; + const BATCHES: usize = 3; + const BATCH_SUBMITS: usize = 4; + const BATCH_MOST: usize = 5; + const DEPTH: usize = 6; + const DEPTH_MOST: usize = 7; + const BEHIND: usize = 8; + const AT_ONCE: usize = 9; + const ROOM_N: usize = 10; + const ROOM_US: usize = 11; + const DRAIN: usize = 12; + const DRAINS: usize = 6; + const NAMES: [(Drain, &str); DRAINS] = [ + (Drain::Present, "presents"), + (Drain::PageMappings, "page mappings"), + (Drain::TileMappings, "tile mappings"), + (Drain::Kickoff, "KickoffX"), + (Drain::ListReset, "list resets"), + (Drain::Release, "allocator releases"), + ]; + + fn us(d: Duration) -> u64 { + d.as_micros() as u64 + } + + pub(super) fn drained(why: Drain, d: Duration) { + let k = NAMES.iter().position(|n| n.0 == why).unwrap_or(0); + S[DRAIN + 2 * k].fetch_add(1, Relaxed); + S[DRAIN + 2 * k + 1].fetch_add(us(d), Relaxed); + crate::hle::api_cost::add(crate::hle::api_cost::Call::SubmitWait, d); + } + + pub(super) fn pushed(before: u64) { + S[DEPTH].fetch_add(before, Relaxed); + S[DEPTH_MOST].fetch_max(before + 1, Relaxed); + } + + pub(super) fn room(d: Duration) { + S[ROOM_N].fetch_add(1, Relaxed); + S[ROOM_US].fetch_add(us(d), Relaxed); + crate::hle::api_cost::add(crate::hle::api_cost::Call::SubmitWait, d); + } + + pub(super) fn title_submit(d: Duration) { + S[TITLE_N].fetch_add(1, Relaxed); + S[TITLE_US].fetch_add(us(d), Relaxed); + } + + pub(super) fn ran(d: Duration) { + S[BUSY_US].fetch_add(us(d), Relaxed); + } + + pub(super) fn batch(submits: usize) { + if submits > 0 { + S[BATCHES].fetch_add(1, Relaxed); + S[BATCH_SUBMITS].fetch_add(submits as u64, Relaxed); + S[BATCH_MOST].fetch_max(submits as u64, Relaxed); + } + } + + pub(super) fn fence_op(behind: bool) { + S[if behind { BEHIND } else { AT_ONCE }].fetch_add(1, Relaxed); + } + + /// The line's part of the 1024-submit lines, from what was counted since the last (None while + /// nothing went through the line). + pub(super) fn line() -> Option { + let s: Vec = S.iter().map(|a| a.swap(0, Relaxed)).collect(); + Some(format(&s)).filter(|_| s[TITLE_N] > 0 || s[BATCHES] > 0) + } + + pub(super) fn format(s: &[u64]) -> String { + let per = |a: usize, n: usize| s[a] as f64 / s[n].max(1) as f64; + let drains: Vec = NAMES + .iter() + .enumerate() + .filter(|(k, _)| s[DRAIN + 2 * k] > 0) + .map(|(k, n)| format!("{} at {} in {:.1} ms", s[DRAIN + 2 * k], n.1, s[DRAIN + 2 * k + 1] as f64 / 1000.0)) + .collect(); + format!( + "submit thread (XCL_ASYNC_SUBMIT): {} submits into its line at {:.2} ms each on the title's thread, {:.1} ms on its own; {} batches, {:.1} submits a batch (at most {}); {:.1} in the line at a submit (at most {}); {} signals / waits behind submits, {} at once; the title's threads waited {:.1} ms for room ({}x) and drained it {}", + s[TITLE_N], + per(TITLE_US, TITLE_N) / 1000.0, + s[BUSY_US] as f64 / 1000.0, + s[BATCHES], + per(BATCH_SUBMITS, BATCHES), + s[BATCH_MOST], + per(DEPTH, TITLE_N), + s[DEPTH_MOST], + s[BEHIND], + s[AT_ONCE], + s[ROOM_US] as f64 / 1000.0, + s[ROOM_N], + if drains.is_empty() { "at nothing".to_string() } else { drains.join(", ") } + ) + } + + #[cfg(test)] + pub(super) fn sample() -> Vec { + let mut s = vec![0u64; S.len()]; + (s[TITLE_N], s[TITLE_US], s[BUSY_US], s[BATCHES], s[BATCH_SUBMITS], s[BATCH_MOST]) = (4, 2000, 30_500, 2, 4, 3); + (s[DEPTH], s[DEPTH_MOST], s[BEHIND], s[AT_ONCE], s[ROOM_N], s[ROOM_US]) = (6, 4, 3, 1, 0, 0); + (s[DRAIN], s[DRAIN + 1], s[DRAIN + 10], s[DRAIN + 11]) = (2, 12_300, 1, 400); + s + } } #[cfg(test)] @@ -707,6 +824,16 @@ mod tests { assert_eq!(batch_len(&VecDeque::new(), 64), 0); } + /// The line's part of the 1024-submit lines: the title's time a submit, the thread's, the + /// batches, the depth, and only the drains that happened. + #[test] + fn the_counters_line_reads_as_averages() { + assert_eq!( + stats::format(&stats::sample()), + "submit thread (XCL_ASYNC_SUBMIT): 4 submits into its line at 0.50 ms each on the title's thread, 30.5 ms on its own; 2 batches, 2.0 submits a batch (at most 3); 1.5 in the line at a submit (at most 4); 3 signals / waits behind submits, 1 at once; the title's threads waited 0.0 ms for room (0x) and drained it 2 at presents in 12.3 ms, 1 at allocator releases in 0.4 ms" + ); + } + /// A call of slot `slot` of `this`'s vtable with three integer arguments, from code that is /// registered as a title's image (`title_image`): the queue's split entries take it for the /// title's. @@ -847,6 +974,9 @@ mod tests { assert!(LINE.done() >= pushed); assert!(dev.GetDeviceRemovedReason().is_ok()); assert!(!queued(primary as usize) && !queued(now[0] as usize)); + // (the two submits and the signal went in one batch, behind the held entry) + let counted = line().unwrap(); + assert!(counted.contains("2 submits into its line") && counted.contains("1 batches, 2.0 submits a batch") && counted.contains("1 signals / waits behind submits"), "{counted}"); let mut r = std::ptr::null_mut(); readback.Map(0, Some(&D3D12_RANGE { Begin: 0, End: 512 }), Some(&mut r)).unwrap(); let bytes = std::slice::from_raw_parts(r as *const u8, 512).to_vec(); From 09536b891abac280b564ff42efd4019921deafe9 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:36:47 +0100 Subject: [PATCH 075/175] D3D12.X: a CPU read waits for its copy back with the sparse lock released A title's Map with a read range on memory in a sparse window (`sparse::readback_now`) held `sparse::STATE` from the scan of its range through the copy on the sparse queue, the CPU wait for that queue and the landing. In a retail title's world on an RX 9070 XT (amd-dev 82d5eea8, XCL_LOOK_STATS=2) the "CPU reads" holder kept the lock 3.6-6.3 ms a submit; each submit waited 0.4-1.6 ms behind it in before_execute, its after stage 0.3-0.9 ms and its ranges 0.1-0.3 ms more (the sparse lock split line). The sparse queue is a direct queue: its copy waits for the GPU to get to it. Now (XCL_CPU_READ_UNLOCKED, on unless set to 0, and only with a readback queue) the read goes in two holds of the lock: - `cpu_read_begin`: tile clears and mappings, the copies back done land, then the copy is recorded and submitted with the hash each 64-byte chunk was last sent with, and `State::reading` follows the range; - the fence is waited for with the lock released (`wait_fence`, 5 s at most; past that nothing lands, before the buffer was copied anyway), and the hashes of the copied chunks are made there; - `cpu_read_land`: a chunk takes the copy only if its tile has the same video and CPU memory (`pool`, `gen`), its sent hash is the one of then, the CPU did not write it (as `land_page`), and nothing landed there that the hashes cannot show: copies back and immediates of later submissions (`spoil_if_newer`, by `RbJob::seq`) and decommitted pages (`decommit_range`), which `Reading::spoiled` keeps. `CPU_READ` keeps the readback list and buffer to one read at a time (taken before `STATE`). The CPU's unsent writes in the range are no longer scanned and sent before the copy: a chunk the CPU wrote does not take the copy back and goes up with the next look, so that only copied back what the CPU had. A whole chunk the copy holds as it was sent is left alone. The old path stays as `readback_locked` (XCL_CPU_READ_UNLOCKED=0, or no readback queue). The idea is that of open upstream PR #1385 (MacieGx, "waits for the sparse queue do not hold the sparse state's lock"), made again on amd-dev, whose copies back land asynchronously and by hash. XCL_LOOK_STATS=2 adds a "CPU reads" part to the sparse lock split line: reads a submit, KB each, ms with and without the lock each. Test: cpu_read_waits_unlocked_and_keeps_what_changed_meanwhile (the state's lock is free while the copy waits behind a fence; a CPU-written chunk, a page decommitted and committed again, and a later copy back's zeros keep their bytes; the rest takes the GPU's, with its hash). Without the decommit or the landing spoil it fails. (cherry picked from commit 601b841ae204b061669a3d70ad49c3d347ee07d3) --- crates/xcl/src/hle/d3d12x/sparse.rs | 545 +++++++++++++++++++++++++++- 1 file changed, 533 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index f866cbca39..69e11cb8f9 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -879,6 +879,41 @@ struct State { diag: ViewDiag, /// `XCL_VIEW_POISON`: the tile the windows' tiles without video memory show (`poison_windows`) poison: Option, + /// a CPU read whose copy back is waited for with the lock released (`readback_now`) + reading: Option, +} + +/// A CPU read's copy back on the GPU (`State::reading`; one at a time, `CPU_READ`): the range it +/// copied, its place among the copies back of the submissions (`ReadbackQueue::job_seq` when it +/// was recorded), and the parts of the range that changed since in a way the chunks' hashes do not +/// show (`spoil`): what copies back and immediates of later submissions landed there (they may +/// hold what the CPU had before, so the hashes stay), and pages decommitted (committed again they +/// hold zeros, and so may the hashes). Its copy does not land there. +struct Reading { + at: usize, + end: usize, + seq: u64, + spoiled: Vec<(usize, usize)>, +} + +impl State { + /// `[a, a + n)` changed while a CPU read's copy back is on the GPU (`Reading`). + fn spoil(&mut self, a: usize, n: usize) { + if let Some(r) = self.reading.as_mut() { + let (lo, hi) = (a.max(r.at), a.saturating_add(n).min(r.end)); + if lo < hi { + r.spoiled.push((lo, hi)); + } + } + } + + /// A copy back or an immediate of the submissions' (`seq`, `RbJob::seq`) landed in `[a, a + n)`: + /// one recorded after the CPU read's copy holds the newer bytes. + fn spoil_if_newer(&mut self, seq: u64, a: usize, n: usize) { + if self.reading.as_ref().is_some_and(|r| seq > r.seq) { + self.spoil(a, n); + } + } } /// The one 64 KiB of video memory the tiles of the windows without video memory of their own are @@ -1384,6 +1419,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - counts: MirrorCounts::default(), diag: ViewDiag { keep: view_switches().keep, stats: view_switches().stats, ..Default::default() }, poison: None, + reading: None, }) } @@ -2269,6 +2305,7 @@ impl State { ReadyJob::Imm(job) => { for &(va, value, bytes, gen) in &job.writes { self.store_imm(va, value, bytes, gen); + self.spoil_if_newer(job.seq, va, (bytes & 0x7f) as usize); } RB_PENDING.fetch_sub(1, Ordering::Release); } @@ -2276,6 +2313,7 @@ impl State { let copies = std::mem::take(&mut job.copies); for &(dst, off, len, gen) in &copies { self.copy_back(job.ptr, dst, off, len, gen); + self.spoil_if_newer(job.seq, dst, len); } TILE_WORK[3].fetch_add(copies.iter().map(|c| c.2 as u64).sum(), Ordering::Relaxed); RB_PENDING.fetch_sub(1, Ordering::Release); @@ -3192,9 +3230,8 @@ impl State { } /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with -/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending -/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then -/// copies the range back from VRAM into CPU memory. +/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): what the GPU wrote +/// there is copied back into CPU memory, where the CPU did not write since (`readback_now_with`). pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; @@ -3204,13 +3241,238 @@ pub unsafe fn readback_now(va: usize, len: usize) { wait_and_check_ready(&rb, Drain::TitleDone, 2000, None); } } - let excess = { - let mut g = lock_state(); - let _held = holding(Holder::CpuRead); - let Some(s) = g.as_mut() else { return }; - if s.window_index(va).is_none() { - return; + readback_now_with(&STATE, va, len); +} + +/// `XCL_CPU_READ_UNLOCKED=0`: a CPU read (`readback_now`) holds the state's lock while the GPU +/// makes its copy back, as before. Otherwise (with a readback queue) the copy is waited for with +/// the lock released (`cpu_read_begin`, `cpu_read_land`). A retail title's world on an RX 9070 XT: +/// its threads held the lock 3.6–6.3 ms a submit for CPU reads, and each submit waited 0.4–1.6 ms +/// behind them for its own use of it, its after stage 0.3–0.9 ms more. +fn cpu_read_unlocked() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_CPU_READ_UNLOCKED").map_or(true, |v| v.trim() != "0")) +} + +/// One CPU read's copy back at a time (`cpu_read_unlocked`): the state's readback list and +/// buffer are the read's from the copy's recording until it landed, and the copy is waited for +/// with `STATE` released. Taken before `STATE`, never under it. +static CPU_READ: Mutex<()> = Mutex::new(()); + +/// `XCL_LOOK_STATS=2`: the CPU reads (`readback_now`) since the last sparse lock split line: +/// [reads, bytes asked for, µs with the state's lock held, µs waiting for the copy with it +/// released, copies made, 64-byte chunks landed] +static CPU_READS: super::look_stats::Sums<6> = super::look_stats::Sums::new(); + +/// The CPU reads part of the sparse lock split line (`CPU_READS`' sums over `submits`). +fn cpu_reads_line(x: &[u64; 6], submits: u64) -> String { + let n = submits.max(1) as f64; + let reads = x[0].max(1) as f64; + format!( + "CPU reads: {:.2} a submit, {:.0} KB each, {:.3} ms each with the lock held and {:.3} ms waiting for the copy without it, {:.1} chunks landed each, {:.1} copies each", + x[0] as f64 / n, + x[1] as f64 / reads / 1024.0, + x[2] as f64 / reads / 1e3, + x[3] as f64 / reads / 1e3, + x[5] as f64 / reads, + x[4] as f64 / reads + ) +} + +/// Wait until `fence` reaches `value`, 5 s at most (true: it did; a removed device counts). Not +/// for a holder of `STATE`. +unsafe fn wait_fence(fence: &ID3D12Fence, value: u64) -> bool { + thread_local! { + /// this thread's event for its waits (one given up on stays registered with the fence: + /// it is never closed, and a wait looks at the fence again when it is set) + static EVENT: HANDLE = unsafe { windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap_or_default() }; + } + let event = EVENT.with(|e| *e); + let t0 = std::time::Instant::now(); + loop { + let at = super::real::fence_completed(fence); + if at >= value { + return true; + } + let left = 5000u64.saturating_sub(t0.elapsed().as_millis() as u64); + if left == 0 { + crate::xlog_warn!("sparse: the queue has not reached fence value {value} after 5 s (at {at}): a CPU read's copy back is left out"); + return false; + } + if !event.is_invalid() && fence.SetEventOnCompletion(value, event).is_ok() { + windows::Win32::System::Threading::WaitForSingleObject(event, left as u32); + } else { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } +} + +/// What `cpu_read_begin` did. +enum CpuReadStep { + /// the read is done (with the lock held: `readback_locked`); the copy-back jobs to drop + Done(Vec), + /// the copy before this one is still on the GPU (given up on): wait for the fence, then again + Busy(ID3D12Fence, u64), + /// nothing to copy before this address; the copy-back jobs to drop + Skip(usize, Vec), + Copy(CpuReadCopy), +} + +/// A piece of a CPU read's copy (`cpu_read_begin`): `[va, va + len)` of one tile, at `off` in the +/// readback buffer, the tile's video memory and CPU memory when it was recorded +/// (`TileEntry::pool`, `gen`), the hash each 64-byte chunk there was last sent with, and (made +/// with the lock released once the copy is done, `hash_copied`) the hash of each whole chunk the +/// copy holds (0 for a chunk only partly read). +struct CpuReadPart { + va: usize, + off: usize, + len: usize, + pool: (u32, u32), + gen: u32, + sent: Vec, + copied: Vec, +} + +/// A CPU read's copy submitted on the state's queue (`cpu_read_begin`), to land once the fence +/// reaches `value` (`cpu_read_land`). +struct CpuReadCopy { + fence: ID3D12Fence, + value: u64, + /// where the rest of the read begins + next: usize, + /// the readback buffer (`ptr` is its mapping), kept while the copy is read + _buf: ID3D12Resource, + ptr: *const u8, + parts: Vec, + /// copy-back jobs to drop outside the lock + excess: Vec, +} + +impl CpuReadCopy { + /// `CpuReadPart::copied`, made with the lock released: the hashes `cpu_read_land` gives the + /// chunks it lands. + unsafe fn hash_copied(&mut self) { + for part in &mut self.parts { + part.copied.clear(); + let end = part.va + part.len; + let mut c = part.va & !(CHUNK - 1); + while c < end { + let whole = c >= part.va && c + CHUNK <= end; + part.copied.push(if whole { chunk_hash(std::slice::from_raw_parts(self.ptr.add(part.off + (c - part.va)), CHUNK)) } else { 0 }); + c += CHUNK; + } + } + } +} + +/// The hashes the 64-byte chunks of `[a, a + n)` (in the tile at `t`, `e`) were last sent with: +/// `ZERO_HASH` for a page with none (all zero, or a hole). +fn sent_hashes(e: &TileEntry, t: usize, a: usize, n: usize) -> Vec { + let mut out = Vec::with_capacity(n / CHUNK + 2); + let mut c = a & !(CHUNK - 1); + while c < a + n { + let idx = (c - t) / PAGE; + out.push(e.sent[idx].as_deref().map_or(ZERO_HASH, |s| s[(c - t) % PAGE / CHUNK])); + c += CHUNK; + } + out +} + +/// Whether `[lo, hi)` meets one of `runs` (sorted by start). +fn meets(runs: &[(usize, usize)], lo: usize, hi: usize) -> bool { + runs.iter().take_while(|r| r.0 < hi).any(|r| r.1 > lo) +} + +/// `readback_now` on the state in `state_lock` (the global one, or a test's). +unsafe fn readback_now_with(state_lock: &Mutex>, va: usize, len: usize) { + let is_global = std::ptr::eq(state_lock, &STATE); + let lock = || if is_global { lock_state() } else { state_lock.lock().unwrap() }; + let deep = is_global && super::look_stats::deep(); + let stamp = || deep.then(std::time::Instant::now); + let since = |t: Option| t.map_or(0, |t| t.elapsed().as_micros() as u64); + let unlocked = cpu_read_unlocked(); + let _one = unlocked.then(|| CPU_READ.lock().unwrap_or_else(|e| e.into_inner())); + let end = va.saturating_add(len); + let mut at = va; + // [µs with the lock, µs waiting without it, copies, chunks landed] + let mut x = [0u64; 4]; + while at < end { + let t = stamp(); + let step = { + let mut g = lock(); + let _held = is_global.then(|| holding(Holder::CpuRead)); + let Some(s) = g.as_mut() else { break }; + if s.window_index(at).is_none() { + break; + } + if unlocked && s.rbq.is_some() { + s.cpu_read_begin(at, end) + } else { + CpuReadStep::Done(s.readback_locked(at, end - at)) + } + }; + x[0] += since(t); + match step { + CpuReadStep::Done(excess) => { + drop(excess); + break; + } + CpuReadStep::Busy(fence, value) => { + let t = stamp(); + let there = wait_fence(&fence, value); + x[1] += since(t); + if !there { + break; + } + } + CpuReadStep::Skip(next, excess) => { + drop(excess); + at = next; + } + CpuReadStep::Copy(mut copy) => { + drop(std::mem::take(&mut copy.excess)); + let t = stamp(); + let there = wait_fence(©.fence, copy.value); + if there { + copy.hash_copied(); + } + x[1] += since(t); + let t = stamp(); + let (excess, landed) = { + let mut g = lock(); + let _held = is_global.then(|| holding(Holder::CpuRead)); + match g.as_mut() { + Some(s) => s.cpu_read_land(©, there), + None => (Vec::new(), 0), + } + }; + x[0] += since(t); + drop(excess); + x[2] += 1; + x[3] += landed; + if !there { + break; + } + at = copy.next; + } } + } + if deep { + CPU_READS.add(0, 1); + CPU_READS.add(1, len as u64); + for (k, v) in x.into_iter().enumerate() { + CPU_READS.add(2 + k, v); + } + } +} + +impl State { + /// A CPU read of `[va, va + len)` with the lock held all the way (`XCL_CPU_READ_UNLOCKED=0`, or + /// no readback queue): pending tile clears and unsubmitted CPU-changed chunks go first, then + /// the range is copied back from VRAM into CPU memory, the GPU waited for. The excess copy-back + /// jobs to drop outside the lock. + unsafe fn readback_locked(&mut self, va: usize, len: usize) -> Vec { + let s = self; let zeroed = zero_runs(std::mem::take(&mut s.to_zero)); if !zeroed.is_empty() { for &(a, n) in &zeroed { @@ -3243,8 +3505,148 @@ pub unsafe fn readback_now(va: usize, len: usize) { s.upload_dirty(&dirty_runs); } s.readback_ranges(&[(va, len)]) - }; - drop(excess); + } + + /// The first half of a CPU read of `[at, end)` whose copy back is waited for with the lock + /// released (`readback_now_with`): pending tile clears and mappings go first and the copies + /// back done land (they are older than this one), then a copy of as much of the range as the + /// readback buffer holds is submitted on the state's queue, with the hashes its chunks were + /// last sent with. `reading` follows what lands in the range until `cpu_read_land`. + /// + /// Unlike `readback_locked`, the CPU's writes there that are not sent yet are not scanned and + /// sent first: a chunk the CPU wrote since it was sent does not take the copy back + /// (`cpu_read_land`, as `land_page`) and goes up with the next look anyway, so sending it here + /// only had the GPU copy back what the CPU has. + unsafe fn cpu_read_begin(&mut self, at: usize, end: usize) -> CpuReadStep { + // (a copy given up on is still in the readback list and buffer) + if self.rb_last_fence != 0 && super::real::fence_completed(&self.fence) < self.rb_last_fence { + return CpuReadStep::Busy(self.fence.clone(), self.rb_last_fence); + } + let zeroed = zero_runs(std::mem::take(&mut self.to_zero)); + if !zeroed.is_empty() { + for &(a, n) in &zeroed { + self.clear_sent_range(a, n); + } + self.upload_zeros(&zeroed); + } + self.flush_pending(); + let excess = self.land_finished_readbacks(); + let Some((buf, p)) = self.readback_buf() else { return CpuReadStep::Skip(end, excess) }; + let piece_end = end.min(at.saturating_add(READBACK_STAGING)); + let mut parts: Vec = Vec::new(); + let mut used = 0usize; + let mut cur = at; + while cur < piece_end { + let tile = cur & !(TILE - 1); + let Some(wi) = self.window_index(cur) else { + cur = end; + break; + }; + let b = self.windows[wi].0; + let n = (piece_end - cur).min(tile + TILE - cur).min(b + crate::gpu::uma::WINDOW - cur); + // (a tile with no video memory has nothing to copy back, as in `readback_ranges`) + let Some(e) = self.mapped.get(&tile).filter(|e| e.pool != LAZY) else { + cur += n; + continue; + }; + let (pool, gen, sent) = (e.pool, e.gen, sent_hashes(e, tile, cur, n)); + if parts.is_empty() { + let _ = self.rb_alloc.Reset(); + let _ = self.rb_list.Reset(&self.rb_alloc, None); + } + self.rb_list.CopyBufferRegion(&buf, used as u64, &self.windows[wi].1, (cur - b) as u64, n as u64); + parts.push(CpuReadPart { va: cur, off: used, len: n, pool, gen, sent, copied: Vec::new() }); + used += n; + cur += n; + } + if parts.is_empty() { + return CpuReadStep::Skip(cur, excess); + } + let list = self.rb_list.Close().ok().and_then(|_| self.rb_list.cast::().ok()); + let Some(list) = list else { return CpuReadStep::Skip(end, excess) }; + super::title_textures::own_work(|| self.queue.ExecuteCommandLists(&[Some(list)])); + self.signal(); + self.rb_last_fence = self.value; + let seq = self.readbacks.lock().unwrap().job_seq; + self.reading = Some(Reading { at, end: cur, seq, spoiled: Vec::new() }); + CpuReadStep::Copy(CpuReadCopy { fence: self.fence.clone(), value: self.value, next: cur, _buf: buf, ptr: p, parts, excess }) + } + + /// The second half of a CPU read (`cpu_read_begin`), its copy done (`there`; else it lands + /// nowhere): the copies back done meanwhile land first, then the copy lands in each chunk of + /// its range that is as the copy found it: the tile has the same video and CPU memory, the + /// chunk the hash it had then and the CPU did not write it since (`land_page`), and nothing + /// landed there that the hashes do not show (`Reading::spoiled`). (A copy back of a submission + /// before the read that lands meanwhile keeps what it changed, as one that landed after the + /// read did when the read held the lock.) The excess copy-back jobs to drop outside the lock, + /// and the chunks landed. + unsafe fn cpu_read_land(&mut self, copy: &CpuReadCopy, there: bool) -> (Vec, u64) { + let excess = self.land_finished_readbacks(); + let reading = self.reading.take(); + // (a state made again while the copy was waited for: not its memory) + let Some(reading) = reading.filter(|_| there && self.fence.as_raw() == copy.fence.as_raw()) else { return (excess, 0) }; + let mut spoiled = reading.spoiled; + spoiled.sort_unstable(); + spoiled.dedup_by(|b, a| { + if b.0 > a.1 { + return false; + } + a.1 = a.1.max(b.1); + true + }); + let deep = super::look_stats::deep(); + let mut landed = 0u64; + for part in ©.parts { + let t = part.va & !(TILE - 1); + let Some(entry) = self.mapped.get_mut(&t).filter(|e| e.pool == part.pool && e.gen == part.gen) else { continue }; + let here = entry.cpu(t); + let end = part.va + part.len; + let mut c = part.va & !(CHUNK - 1); + let mut i = 0; + // (the page of the chunks landed last, and their bytes: noted once a page) + let mut page: Option<(usize, usize)> = None; + while c < end { + let (lo, hi) = (c.max(part.va), (c + CHUNK).min(end)); + let idx = (c - t) / PAGE; + let k = (c - t) % PAGE / CHUNK; + let sent = entry.sent[idx].as_deref().map_or(ZERO_HASH, |s| s[k]); + let whole = lo == c && hi == c + CHUNK; + let copied = part.copied.get(i).copied(); + // (a whole chunk the copy holds as it was sent: the CPU has it, or wrote it since) + let same = whole && copied == Some(sent); + if entry.holes & (1u16 << idx) == 0 && part.sent.get(i) == Some(&sent) && !same && !meets(&spoiled, lo, hi) { + let cpu = (here + (c - t)) as *mut u8; + if chunk_hash(std::slice::from_raw_parts(cpu, CHUNK)) == sent { + std::ptr::copy_nonoverlapping(copy.ptr.add(part.off + (lo - part.va)), cpu.add(lo - c), hi - lo); + let h = match copied { + Some(h) if whole => h, + _ => chunk_hash(std::slice::from_raw_parts(cpu, CHUNK)), + }; + entry.sent[idx].get_or_insert_with(|| Box::new(ZERO_HASHES))[k] = h; + landed += 1; + let pg = here + (c - t) - (c - t) % PAGE; + match page.as_mut() { + Some((p, n)) if *p == pg => *n += hi - lo, + _ => { + if let Some((p, n)) = page.replace((pg, hi - lo)) { + crate::hle::kernelx::pagelog::note("GPU copy back landed", p, 0, n); + } + if deep && self.own_pages.len() < OWN_PAGES_MAX { + self.own_pages.push(pg); + } + } + } + } + } + c += CHUNK; + i += 1; + } + if let Some((p, n)) = page { + crate::hle::kernelx::pagelog::note("GPU copy back landed", p, 0, n); + } + } + (excess, landed) + } } /// Submits waiting for the state's lock. A thread that takes it again and again – a title mapping @@ -3509,6 +3911,8 @@ impl State { /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps /// them and frees their pool tiles) unsafe fn decommit_range(&mut self, a: usize, n: usize) { + // (committed again, these pages hold zeros: a CPU read's copy back of them is old) + self.spoil(a, n); let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); let end = a.saturating_add(n); // tiles over a CPU view go as a whole (their holes are the CPU view's pages, not these) @@ -5139,7 +5543,7 @@ impl State { LOCK_SPLIT.add(LS_UNMAP_TILES, work(2)); if LOCK_SPLIT.add(LS_SUBMITS, 1) >= 1024 { let x = LOCK_SPLIT.take(); - crate::xlog_info!("D3D12.X: {}; {}", lock_split_line(&x), holders_line(&HELD.take(), x[LS_SUBMITS])); + crate::xlog_info!("D3D12.X: {}; {}; {}", lock_split_line(&x), holders_line(&HELD.take(), x[LS_SUBMITS]), cpu_reads_line(&CPU_READS.take(), x[LS_SUBMITS])); } } let zero_runs = zero_runs(std::mem::take(&mut s.to_zero)); @@ -5869,6 +6273,7 @@ mod tests { counts: MirrorCounts::default(), diag: ViewDiag::default(), poison: None, + reading: None, }; s.commit_range(base, TILE); assert!(s.mapped.contains_key(&base)); @@ -6202,6 +6607,7 @@ mod tests { counts: MirrorCounts::default(), diag: ViewDiag::default(), poison: None, + reading: None, }; let (first, reused) = s.take_tile().expect("a tile from a new pool"); @@ -6441,6 +6847,7 @@ mod tests { counts: MirrorCounts::default(), diag: ViewDiag::default(), poison: None, + reading: None, }; // Mirrors `place_buffer`: map both tiles probing real OS page commitment. @@ -6608,6 +7015,7 @@ mod tests { counts: MirrorCounts::default(), diag: ViewDiag::default(), poison: None, + reading: None, }; s.commit_range(base, TILE); @@ -9119,4 +9527,117 @@ mod tests { assert_eq!(iso.rb.lock().unwrap().submitting, 0); } } + + /// `len` bytes of `byte` put into the window's video memory at `va`, not into its CPU memory: + /// what the GPU wrote there. + unsafe fn gpu_fill(s: &mut State, va: usize, len: usize, byte: u8) { + let mut d = buffer_desc(len as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut up: Option = None; + s.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up).expect("upload buffer"); + let up = up.expect("upload buffer"); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("Map"); + std::ptr::write_bytes(p as *mut u8, byte, len); + up.Unmap(0, None); + let (base, window) = (s.windows[0].0, s.windows[0].1.clone()); + let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&window, (va - base) as u64, &up, 0, len as u64); + list.Close().expect("Close"); + s.flush_pending(); + s.queue.ExecuteCommandLists(&[Some(list.cast().expect("list"))]); + s.signal(); + s.wait_for(s.value); + } + + #[test] + fn meets_finds_overlaps_with_sorted_runs() { + let runs = [(0x100, 0x140), (0x800, 0x900)]; + assert!(!meets(&runs, 0x140, 0x180), "ends are exclusive"); + assert!(meets(&runs, 0x13F, 0x141)); + assert!(meets(&runs, 0x8C0, 0x900)); + assert!(!meets(&runs, 0x900, 0x940)); + assert!(!meets(&[], 0, usize::MAX)); + } + + /// A CPU read (`readback_now_with`) waits for its copy back with the state's lock released, and + /// what changed in its range meanwhile keeps its bytes: a chunk the CPU wrote, a page + /// decommitted and committed again (zeros), and what a later submission's copy back landed + /// (here the zeros the CPU had: the hashes cannot tell it from an untouched chunk). The rest + /// gets what the GPU wrote, with its hashes. Before, the read held the lock until its copy was + /// done (a retail title: 3.6–6.3 ms a submit, the submits waiting behind it). + #[test] + fn cpu_read_waits_unlocked_and_keeps_what_changed_meanwhile() { + use windows_sys::Win32::System::Memory::PAGE_READWRITE; + if !cpu_read_unlocked() { + return crate::gpu::recomp::runner::skip_test("XCL_CPU_READ_UNLOCKED=0"); + } + unsafe { + let iso = IsolatedAsyncState::new(); + let base = iso.base; + let blocker: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let _unblock = SignalOnDrop(blocker.clone(), 1); + { + let mut g = iso.state.lock().unwrap(); + let s = g.as_mut().unwrap(); + gpu_fill(s, base, 4 * PAGE, 0x5A); + // (the state's queue held until the test lets it go: the read's copy waits behind it) + s.queue.Wait(&blocker, 1).expect("Wait"); + } + let state = Arc::clone(&iso.state); + let reader = std::thread::spawn(move || readback_now_with(&state, base, 4 * PAGE)); + let t0 = std::time::Instant::now(); + while iso.state.lock().unwrap().as_ref().is_some_and(|s| s.reading.is_none()) { + assert!(t0.elapsed() < std::time::Duration::from_secs(10), "the read's copy was never submitted"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + for _ in 0..5 { + assert!(iso.state.try_lock().is_ok(), "the state's lock is free while the read waits for its copy"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + // the CPU writes a chunk + std::ptr::write_bytes((base + 0x100) as *mut u8, 0x77, CHUNK); + // a page is decommitted and committed again + let p2 = base + 2 * PAGE; + assert!(VirtualFree(p2 as *mut c_void, PAGE, MEM_DECOMMIT) != 0); + iso.state.lock().unwrap().as_mut().unwrap().decommit_range(p2, PAGE); + assert!(!VirtualAlloc(p2 as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + iso.state.lock().unwrap().as_mut().unwrap().commit_range(p2, PAGE); + // a later submission's copy back lands + let at = base + 3 * PAGE + 0x800; + let done: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("fence"); + let mut job = take_or_alloc_rb_job(&iso.dev, &iso.rb, 256, D3D12_COMMAND_LIST_TYPE_DIRECT).expect("readback job"); + std::ptr::write_bytes(job.ptr, 0, 256); + job.copies.clear(); + job.copies.push((at, 0, 256, iso.gen)); + (job.rb_v, job.done_v, job.fences) = (1, 1, Some((done.clone(), done))); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } + RB_PENDING.fetch_add(1, Ordering::Release); + drop(iso.state.lock().unwrap().as_mut().unwrap().land_finished_readbacks()); + assert!(iso.rb.lock().unwrap().rb_jobs.is_empty(), "the later copy back landed"); + blocker.Signal(1).expect("Signal"); + reader.join().unwrap(); + + let bytes = |a: usize, n: usize| std::slice::from_raw_parts(a as *const u8, n).to_vec(); + let all = |a: usize, n: usize, b: u8| bytes(a, n).iter().all(|&x| x == b); + assert!(all(base, 0x100, 0x5A) && all(base + 0x140, PAGE - 0x140, 0x5A), "the GPU's bytes landed around the CPU's chunk"); + assert!(all(base + 0x100, CHUNK, 0x77), "the chunk the CPU wrote while the copy was made keeps its bytes"); + assert!(all(base + PAGE, PAGE, 0x5A)); + assert!(all(p2, PAGE, 0), "the page committed again keeps its zeros"); + assert!(all(base + 3 * PAGE, 0x800, 0x5A) && all(at + 256, PAGE - 0x900, 0x5A)); + assert!(all(at, 256, 0), "what the later copy back landed stays"); + assert!(all(base + 4 * PAGE, PAGE, 0), "nothing lands past the read"); + let g = iso.state.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(s.reading.is_none()); + let sent = s.mapped[&base].sent[1].as_deref().expect("hashes of a landed page"); + assert_eq!(sent[0], chunk_hash(&[0x5A; CHUNK]), "a landed chunk has the hash of its bytes: the next look sends nothing"); + } + } } From 707123ad7db65a984f0c069623719bc35c5f2cf5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:42:01 +0100 Subject: [PATCH 076/175] D3D12.X: mapped ranges asked again at the same generation need no lock `title_textures::cached_watch_ranges` makes the watched ranges again whenever any part of its key moved (the textures' 16 MiB blocks, the graphics reservations, the shown pages, the mapped tiles), and each time it asked `sparse::mapped_ranges`, which takes `sparse::STATE`. In a retail title's world (RX 9070 XT, XCL_LOOK_STATS=2) a submit's "ranges" stage was 0.11-0.31 ms, 0.08-0.29 ms of it waiting for that lock ("the submit's other waits for it: ... ranges"). The tiles' runs (`State::runs`, `src_runs`) change only under the lock, and every change moves `MAPPED_GEN` (which is in the key already). So the last answer is kept with the generation it was made at (`RANGES`) and given again without the lock while the generation stands; `init` moves it when it puts a new state in. This is the "already up to date" check made lock-free, as VIctory-Neo does for its refreshes (55eb862, its write journal's epochs); here there is one generation for all the ranges. XCL_LOOK_STATS=2: the sparse lock split line counts the answers made under the lock and those that were not. Test: mapped_ranges_made_at_this_generation_need_no_lock (answered while another thread holds the lock; once the generation moved, it waits for the lock and makes them again). (cherry picked from commit 0383b3fe8a6a2595031fb89d702d0ce3e3f898ad) --- crates/xcl/src/hle/d3d12x/sparse.rs | 79 +++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 69e11cb8f9..3b462a4917 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1507,7 +1507,12 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { // (the queue first: `queue()` never answers with one older than the state's) let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); let old_rb = READBACKS.lock().unwrap().replace(Arc::clone(&s.readbacks)); - let old = STATE.lock().unwrap().replace(s); + let old = { + let mut g = STATE.lock().unwrap(); + // (the ranges made of the state before are not this one's: `RANGES`) + MAPPED_GEN.fetch_add(1, Ordering::Release); + g.replace(s) + }; drop(old); drop(old_rb); drop(old_queue); @@ -5030,6 +5035,12 @@ impl State { /// tiles of GPU views show (never the views' own addresses): where a CPU write has to reach the /// GPU. A tile with no page committed is not among them (`State::runs`). pub fn mapped_ranges() -> Vec<(usize, usize)> { + if let Some((gen, r)) = RANGES.lock().unwrap().as_ref() { + if *gen == MAPPED_GEN.load(Ordering::Acquire) { + RANGES_TAKEN.add(1, 1); + return r.clone(); + } + } let t0 = super::look_stats::deep().then(std::time::Instant::now); let g = lock_for_submit(); let _held = holding(Holder::Ranges); @@ -5037,9 +5048,24 @@ pub fn mapped_ranges() -> Vec<(usize, usize)> { HELD.add(HELD_RANGES_WAIT, t0.elapsed().as_micros() as u64); } let Some(s) = g.as_ref() else { return Vec::new() }; - s.watched_ranges() + let out = s.watched_ranges(); + // (read with the lock held: the runs change, and it goes up, only under it) + *RANGES.lock().unwrap() = Some((MAPPED_GEN.load(Ordering::Acquire), out.clone())); + RANGES_TAKEN.add(0, 1); + out } +/// The last `mapped_ranges` and the `MAPPED_GEN` they were made at: asked again with no tile +/// mapped, unmapped or made writable since, they are answered without `STATE`. The watched ranges +/// are made again whenever any part of their key changed (`title_textures::watch_key`: the +/// textures' blocks, the reservations, the shown pages too), and the lock may be held then by a +/// placed buffer, a commit, a CPU read or another queue's submit (a retail title's world: a submit +/// waited 0.1–0.3 ms for it there). Taken alone or under `STATE`, never around it. +static RANGES: Mutex)>> = Mutex::new(None); +/// `mapped_ranges` [made under the lock, answered from `RANGES`] (`XCL_LOOK_STATS=2`, with the +/// sparse lock split line) +static RANGES_TAKEN: super::look_stats::Sums<2> = super::look_stats::Sums::new(); + /// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line static WATCH: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; /// [lock wait, chunk scan, upload] in µs, runs uploaded @@ -5543,7 +5569,13 @@ impl State { LOCK_SPLIT.add(LS_UNMAP_TILES, work(2)); if LOCK_SPLIT.add(LS_SUBMITS, 1) >= 1024 { let x = LOCK_SPLIT.take(); - crate::xlog_info!("D3D12.X: {}; {}; {}", lock_split_line(&x), holders_line(&HELD.take(), x[LS_SUBMITS]), cpu_reads_line(&CPU_READS.take(), x[LS_SUBMITS])); + let [made, kept] = RANGES_TAKEN.take(); + crate::xlog_info!( + "D3D12.X: {}; {}; {}; mapped ranges asked for {made} times under the lock, {kept} times not", + lock_split_line(&x), + holders_line(&HELD.take(), x[LS_SUBMITS]), + cpu_reads_line(&CPU_READS.take(), x[LS_SUBMITS]) + ); } } let zero_runs = zero_runs(std::mem::take(&mut s.to_zero)); @@ -9551,6 +9583,47 @@ mod tests { s.wait_for(s.value); } + /// `mapped_ranges` asked again with no tile mapped or unmapped since answers without the state's + /// lock; once `MAPPED_GEN` moved it takes the lock again. + #[test] + fn mapped_ranges_made_at_this_generation_need_no_lock() { + let fake = vec![(0x7000_0000usize, 0x7001_0000usize)]; + // (other tests move the generation too: tried a few times) + let mut answered = false; + for _ in 0..20 { + let g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let gen = MAPPED_GEN.load(Ordering::Acquire); + *RANGES.lock().unwrap() = Some((gen, fake.clone())); + let (tx, rx) = std::sync::mpsc::channel(); + let asker = std::thread::spawn(move || { + let _ = tx.send(mapped_ranges()); + }); + let got = rx.recv_timeout(std::time::Duration::from_millis(500)); + let moved = MAPPED_GEN.load(Ordering::Acquire) != gen; + drop(g); + asker.join().unwrap(); + if moved { + continue; + } + assert_eq!(got.expect("answered with the state's lock held elsewhere"), fake); + answered = true; + break; + } + assert!(answered, "the generation never stood still"); + // a tile mapped or unmapped since: made again, under the lock + let g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + MAPPED_GEN.fetch_add(1, Ordering::Release); + let (tx, rx) = std::sync::mpsc::channel(); + let asker = std::thread::spawn(move || { + let _ = tx.send(mapped_ranges()); + }); + assert!(rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), "a stale answer without the lock"); + drop(g); + let again = rx.recv_timeout(std::time::Duration::from_secs(10)).expect("answered once the lock was free"); + asker.join().unwrap(); + assert_ne!(again, fake); + } + #[test] fn meets_finds_overlaps_with_sorted_runs() { let runs = [(0x100, 0x140), (0x800, 0x900)]; From 2a630fd218458925f7fd9f74560a15ac604a9c49 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:49:03 +0100 Subject: [PATCH 077/175] D3D12.X: XCL_LOOK_STATS=2 splits a look's other time and the GPU-view tiles Two parts of a submit's time with no line of their own yet, measured in a retail title's world (RX 9070 XT, amd-dev 82d5eea8): - the look for CPU writes took 1.5-1.9 ms, of which its write-watch calls 1.2-1.4 ms ("look split"). The rest (known writes, guarded views, pages found ahead, the hot runs, the sort) had no split. And 0.4 ms a look went to ~28 calls over ~470 MB that found nothing: which blocks were they, and why hot? - the sparse lock's "GPU-view tiles" were 0.3-2.2 ms a submit. Now, with XCL_LOOK_STATS=2: - a "look parts" line every 256 looks: the look's time before its calls, making its hot runs, and after its calls; the hot blocks in calls that found pages and in calls that found nothing, those by why they were hot (a look found them written, the walk did, new to the ranges, committed or placed there: `HotBlocks::hot` keeps the reason) and by how long (<100 ms, <500 ms, <1 s, longer). That says what a shorter hot time (XCL_WATCH_HOT_MS, 1500) would leave to the walk before it is tried. - the sparse lock split line gives the GPU-view tiles part as pages moved (`remap_mirrors`), asked for (`map_mirrors`) and CPU views written (`mirror_writes`), with the time asking Windows which pages are committed (`source_holes`) and making pool heaps (`take_tile`). No behaviour changes. Test: staleness_and_own_writes_are_summed sums and prints the new parts. (cherry picked from commit 102ba10ca36eeeb68fa120063a43644caf3e77cc) --- crates/xcl/src/hle/d3d12x/look_stats.rs | 66 +++++++++++++++++++++ crates/xcl/src/hle/d3d12x/sparse.rs | 52 +++++++++++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 64 +++++++++++++++++--- 3 files changed, 173 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/look_stats.rs b/crates/xcl/src/hle/d3d12x/look_stats.rs index 88db61c8df..3026d3a5dd 100644 --- a/crates/xcl/src/hle/d3d12x/look_stats.rs +++ b/crates/xcl/src/hle/d3d12x/look_stats.rs @@ -133,6 +133,63 @@ pub(super) fn own_writes(written: usize, in_look: usize, scanned: usize, unchang OWN.add(4, unchanged as u64); } +/// The parts of the looks besides their write-watch calls (`look_parts`, `hot_blocks`): [looks, +/// ns before the calls (known writes, guarded views, pages found ahead), ns making the hot runs, +/// ns after the calls (blocks made hot, the pages sorted), hot blocks in calls that found pages, +/// then those in calls that found nothing by why they were hot (`HOT_WHY`), then by how long +/// they had been (`HOT_AGES`)]. A call that finds nothing costs a walk of its blocks' page tables: +/// the hot blocks' reasons and ages say what a shorter hot time would leave to the walk. +static PARTS: Sums<13> = Sums::new(); + +/// why a block is hot, the order of `hot_blocks`' counts +pub(super) const HOT_WHY: [&str; 4] = ["a look found it written", "the walk did", "new to the ranges", "committed or placed there"]; +/// the upper ends (ms) of the ages `hot_blocks` counts by; the last has none +pub(super) const HOT_AGES: [u128; 3] = [100, 500, 1000]; + +/// A look's time before its write-watch calls and after them (`deep` only). +pub(super) fn look_parts(before: Duration, after: Duration) { + PARTS.add(0, 1); + PARTS.add(1, before.as_nanos() as u64); + PARTS.add(3, after.as_nanos() as u64); +} + +/// A hot look's runs (`deep` only): `runs` making them, `marking` the blocks it found written +/// made hot, `busy` hot blocks in calls that found pages, and those in calls that found nothing +/// by why (`HOT_WHY`) and how long (`HOT_AGES`) they had been hot. +pub(super) fn hot_blocks(runs: Duration, marking: Duration, busy: u64, idle_why: [u64; 4], idle_age: [u64; 4]) { + PARTS.add(2, runs.as_nanos() as u64); + PARTS.add(3, marking.as_nanos() as u64); + PARTS.add(4, busy); + for k in 0..4 { + PARTS.add(5 + k, idle_why[k]); + PARTS.add(9 + k, idle_age[k]); + } +} + +/// The look parts line of `p` (`PARTS`' sums). +fn parts_line(p: &[u64; 13]) -> String { + let looks = p[0].max(1) as f64; + let idle: u64 = p[5..9].iter().sum(); + let pct = |v: u64| v * 100 / idle.max(1); + let why: Vec = (0..4).map(|k| format!("{} % {}", pct(p[5 + k]), HOT_WHY[k])).collect(); + format!( + "look parts (256 looks): {:.2} ms a look before its calls, {:.2} ms making its hot runs, {:.2} ms after its calls; {:.0} hot blocks a look in calls that found pages, {:.0} in calls that found nothing: {}; hot for <{} ms {} %, <{} ms {} %, <{} ms {} %, longer {} %", + p[1] as f64 / looks / 1e6, + p[2] as f64 / looks / 1e6, + p[3] as f64 / looks / 1e6, + p[4] as f64 / looks, + idle as f64 / looks, + why.join(", "), + HOT_AGES[0], + pct(p[9]), + HOT_AGES[1], + pct(p[10]), + HOT_AGES[2], + pct(p[11]), + pct(p[12]) + ) +} + /// The scans (`scan_split`): [submits, ns gathering, ns scanning, jobs shared, their items, those /// the caller did, ns until a job's first worker began, jobs a worker began] static SCAN: Sums<8> = Sums::new(); @@ -221,6 +278,7 @@ pub(super) fn look(pages: &[usize], ahead: usize, took: Duration, closed: Option (x[5] / 256) >> 20, x[6] / 256 ); + crate::xlog_info!("D3D12.X: {}", parts_line(&PARTS.take())); let c = SCAN.take(); let per = |v: u64, of: u64| v as f64 / of.max(1) as f64; crate::xlog_info!( @@ -362,5 +420,13 @@ mod tests { own_writes(40, 30, 28, 25); own_writes(2, 0, 0, 0); assert_eq!(OWN.take(), [2, 42, 30, 28, 25]); + // (`PARTS` too) + look_parts(Duration::from_micros(30), Duration::from_micros(5)); + hot_blocks(Duration::from_micros(7), Duration::from_micros(2), 9, [1, 0, 2, 1], [0, 3, 0, 1]); + let p = PARTS.take(); + assert_eq!(p, [1, 30_000, 7_000, 7_000, 9, 1, 0, 2, 1, 0, 3, 0, 1]); + let line = parts_line(&p); + assert!(line.contains("4 in calls that found nothing: 25 % a look found it written, 0 % the walk did, 50 % new to the ranges"), "{line}"); + assert!(line.contains("<500 ms 75 %, <1000 ms 0 %, longer 25 %"), "{line}"); } } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 3b462a4917..9724611e13 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -217,6 +217,8 @@ unsafe fn source_holes(tiles: &[usize]) -> Vec { use windows_sys::Win32::System::Threading::GetCurrentProcess; /// tiles a working-set query asks for const BATCH: usize = 256; + // (`XCL_LOOK_STATS=2`: the time Windows is asked, with the sparse lock split line) + let t0 = super::look_stats::deep().then(std::time::Instant::now); let mut out = Vec::with_capacity(tiles.len()); let mut ws: Vec = Vec::with_capacity(BATCH.min(tiles.len()) * PAGES_PER_TILE); // the region the last VirtualQuery reported: [start, end), and whether its pages are accessible @@ -258,9 +260,42 @@ unsafe fn source_holes(tiles: &[usize]) -> Vec { out.push(holes); } } + if let Some(t0) = t0 { + VIEW_SPLIT.add(VS_ASKED_US, t0.elapsed().as_micros() as u64); + VIEW_SPLIT.add(VS_ASKED_TILES, tiles.len() as u64); + } out } +/// `XCL_LOOK_STATS=2`: where the GPU-view tiles part of a submit's time with the sparse lock goes +/// (`LS_VIEWS`, the sparse lock split line): [µs linking tiles whose page changed +/// (`remap_mirrors`), µs giving asked tiles video memory (`map_mirrors`), µs for the CPU writes +/// their CPU views took (`mirror_writes`), then of all uses of the lock: µs asking Windows which +/// pages of CPU tiles are committed (`source_holes`), the tiles asked about, µs making pool heaps +/// (`take_tile`)] +static VIEW_SPLIT: super::look_stats::Sums<6> = super::look_stats::Sums::new(); +const VS_REMAP_US: usize = 0; +const VS_MAP_US: usize = 1; +const VS_WRITES_US: usize = 2; +const VS_ASKED_US: usize = 3; +const VS_ASKED_TILES: usize = 4; +const VS_HEAPS_US: usize = 5; + +/// The GPU-view tiles part of the sparse lock split line (`VIEW_SPLIT`'s sums over `submits`). +fn view_split_line(x: &[u64; 6], submits: u64) -> String { + let n = submits.max(1) as f64; + let ms = |k: usize| x[k] as f64 / n / 1e3; + format!( + "GPU-view tiles: pages moved {:.3}, asked for {:.3}, CPU views written {:.3} ms a submit; asking Windows which pages are committed {:.3} ms ({:.1} tiles), pool heaps made {:.3} ms a submit (all uses of the lock)", + ms(VS_REMAP_US), + ms(VS_MAP_US), + ms(VS_WRITES_US), + ms(VS_ASKED_US), + x[VS_ASKED_TILES] as f64 / n, + ms(VS_HEAPS_US) + ) +} + /// Query actual OS page commitment across the 64 KiB tile at `tile`. /// Bit `i` in the returned mask is set whenever 4 KiB page `tile + i * PAGE` is not committed /// and accessible (`MEM_RESERVE`, `MEM_FREE`, `PAGE_NOACCESS`, `PAGE_GUARD`, etc.). @@ -1564,7 +1599,12 @@ impl State { // CPU signal that asks meanwhile gives up after 2 ms) self.flush_pending(); let mut heap: Option = None; - if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) { + let t0 = super::look_stats::deep().then(std::time::Instant::now); + let made = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)); + if let Some(t0) = t0 { + VIEW_SPLIT.add(VS_HEAPS_US, t0.elapsed().as_micros() as u64); + } + if let Err(e) = made { crate::xlog_warn!("sparse windows: no video memory for more tiles ({e})"); return None; } @@ -5532,7 +5572,9 @@ impl State { // them: before the flushes below, so their mappings reach the title's work (a tile taken // back from `parked` needs none) s.remap_mirrors(); + let t_remap = stamp(); s.map_mirrors(); + let t_asks = stamp(); s.diag.submits += 1; if s.diag.stats && !(s.later.is_empty() && s.asks.is_empty()) { s.diag.deferred += 1; @@ -5562,6 +5604,11 @@ impl State { LOCK_SPLIT.add(LS_BACK, us(t0, t_back)); LOCK_SPLIT.add(LS_BACK_BYTES, work(3)); LOCK_SPLIT.add(LS_VIEWS, us(t_back, t_views)); + if let (Some(t_remap), Some(t_asks)) = (t_remap, t_asks) { + VIEW_SPLIT.add(VS_REMAP_US, us(t_back, t_remap)); + VIEW_SPLIT.add(VS_MAP_US, us(t_remap, t_asks)); + VIEW_SPLIT.add(VS_WRITES_US, us(t_asks, t_views)); + } LOCK_SPLIT.add(LS_MAP, us(t_views, t_map)); LOCK_SPLIT.add(LS_MAP_TILES, work(0)); LOCK_SPLIT.add(LS_MAP_CALLS, work(1)); @@ -5571,8 +5618,9 @@ impl State { let x = LOCK_SPLIT.take(); let [made, kept] = RANGES_TAKEN.take(); crate::xlog_info!( - "D3D12.X: {}; {}; {}; mapped ranges asked for {made} times under the lock, {kept} times not", + "D3D12.X: {}; {}; {}; {}; mapped ranges asked for {made} times under the lock, {kept} times not", lock_split_line(&x), + view_split_line(&VIEW_SPLIT.take(), x[LS_SUBMITS]), holders_line(&HELD.take(), x[LS_SUBMITS]), cpu_reads_line(&CPU_READS.take(), x[LS_SUBMITS]) ); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 9fab961022..fb7062494a 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1519,8 +1519,9 @@ fn hot_for() -> std::time::Duration { #[derive(Default)] struct HotBlocks { - /// block -> when a look or the walk last found a written page in it - hot: BTreeMap, + /// block -> when a look or the walk last found a written page in it, and why it is hot + /// (`HOT_WRITTEN`, `HOT_WALKED`, `HOT_NEW`, `HOT_MARKED`: `look_stats::HOT_WHY`) + hot: BTreeMap, /// the ranges `known` was made for ranges: Option>>, /// the blocks of those ranges (a block new to the ranges starts hot) @@ -1528,6 +1529,11 @@ struct HotBlocks { } static HOT: Mutex> = Mutex::new(None); +/// why a block is hot (`HotBlocks::hot`, in the order of `look_stats::HOT_WHY`) +const HOT_WRITTEN: u8 = 0; +const HOT_WALKED: u8 = 1; +const HOT_NEW: u8 = 2; +const HOT_MARKED: u8 = 3; /// the ranges of the last look, for the walk static WALK_RANGES: Mutex>>> = Mutex::new(None); /// a look is at its write-watch calls: the walk stays out of the way (the kernel does one such @@ -1549,7 +1555,7 @@ fn hot_runs(ranges: &Arc>, now: std::time::Instant) -> (Vec< let mut b = base & !(HOT_BLOCK - 1); while b < base + size { if !h.known.contains(&b) { - h.hot.insert(b, now); + h.hot.insert(b, (now, HOT_NEW)); } known.insert(b); b += HOT_BLOCK; @@ -1559,7 +1565,7 @@ fn hot_runs(ranges: &Arc>, now: std::time::Instant) -> (Vec< h.ranges = Some(Arc::clone(ranges)); } let keep = hot_for(); - h.hot.retain(|_, t| now.saturating_duration_since(*t) < keep); + h.hot.retain(|_, (t, _)| now.saturating_duration_since(*t) < keep); let mut runs: Vec<(usize, usize)> = Vec::new(); for (&b, _) in h.hot.iter() { let mut j = ranges.partition_point(|&(base, size)| base + size <= b); @@ -1592,13 +1598,39 @@ fn keep_hot(pages: &[usize], now: std::time::Instant) { for &p in pages { let b = p & !(HOT_BLOCK - 1); if b != last { - h.hot.insert(b, now); + h.hot.insert(b, (now, HOT_WRITTEN)); last = b; } } } } +/// `XCL_LOOK_STATS=2`: the hot blocks of a look's `runs` by whether their call found pages +/// (`found`, a count a run), and those of the calls that found nothing by why and how long +/// before `now` they were made hot (`look_stats::hot_blocks`, with `made`: the runs' making, and +/// `marking`: the found blocks made hot). +fn note_hot_blocks(runs: &[(usize, usize)], found: &[usize], now: std::time::Instant, made: std::time::Duration, marking: std::time::Duration) { + let (mut busy, mut why, mut age) = (0u64, [0u64; 4], [0u64; 4]); + if let Some(h) = HOT.lock().unwrap().as_ref() { + for (&(base, size), &n) in runs.iter().zip(found) { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if let Some(&(t, w)) = h.hot.get(&b) { + if n > 0 { + busy += 1; + } else { + why[(w as usize).min(3)] += 1; + let ms = now.saturating_duration_since(t).as_millis(); + age[super::look_stats::HOT_AGES.partition_point(|&e| e <= ms)] += 1; + } + } + b += HOT_BLOCK; + } + } + } + super::look_stats::hot_blocks(made, marking, busy, why, age); +} + /// `XCL_LOOK_AHEAD=ms` (off unless given): a thread takes the written pages of the hot blocks every /// so many milliseconds while the title submits. They are dirty by XCL's account from then on /// (`AHEAD`): the next submit takes them with what its own look finds, and one whose lists were @@ -1690,13 +1722,25 @@ unsafe fn take_hot(ranges: &Arc>, buf: &mut [*mut c_void], d start_walk(ranges); let now = std::time::Instant::now(); let (runs, hot_now) = hot_runs(ranges, now); + // (`XCL_LOOK_STATS=2`: the hot runs' making timed, and the pages each call found) + let deep = super::look_stats::deep(); + let made = deep.then(|| now.elapsed()); + let mut found: Vec = Vec::new(); let first = dirty.len(); LOOKING.store(true, Ordering::Release); for &(base, size) in &runs { + let before = dirty.len(); take_written(base, size, buf, dirty, page); + if deep { + found.push(dirty.len() - before); + } } LOOKING.store(false, Ordering::Release); + let t_keep = deep.then(std::time::Instant::now); keep_hot(&dirty[first..], now); + if let (Some(made), Some(t_keep)) = (made, t_keep) { + note_hot_blocks(&runs, &found, now, made, t_keep.elapsed()); + } let n = HOT_STATS[0].fetch_add(1, Ordering::Relaxed) + 1; let r = HOT_STATS[1].fetch_add(runs.len() as u64, Ordering::Relaxed) + runs.len() as u64; let covered: usize = runs.iter().map(|r| r.1).sum(); @@ -1780,7 +1824,7 @@ unsafe fn walk() { let h = g.get_or_insert_with(HotBlocks::default); for b in found.drain(..) { if let std::collections::btree_map::Entry::Vacant(v) = h.hot.entry(b) { - v.insert(now); + v.insert((now, HOT_WALKED)); HOT_STATS[3].fetch_add(1, Ordering::Relaxed); WALK_FOUND.fetch_max(now_us(), Ordering::Release); } @@ -1868,7 +1912,7 @@ pub(super) fn mark_hot(at: usize, len: usize) { let now = std::time::Instant::now(); let mut b = at & !(HOT_BLOCK - 1); while b < at + len { - h.hot.insert(b, now); + h.hot.insert(b, (now, HOT_MARKED)); b += HOT_BLOCK; } } @@ -1986,6 +2030,8 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { super::sparse::note_look(); } LOOK_BEGAN.fetch_max(began, Ordering::AcqRel); + // (`XCL_LOOK_STATS=2`: the look's time before its calls and after them) + let t_calls = super::look_stats::deep().then(std::time::Instant::now); WATCH_BUF.with(|wcell| { let mut buf = wcell.borrow_mut(); if buf.len() < 16384 { @@ -2000,8 +2046,12 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool) { } } }); + let t_sort = t_calls.map(|_| std::time::Instant::now()); dirty.sort_unstable(); dirty.dedup(); + if let (Some(t_calls), Some(t_sort)) = (t_calls, t_sort) { + super::look_stats::look_parts(t_calls - watch_t0, t_sort.elapsed()); + } dirty.len() }); if look { From 5ff2b66338097c8d02657d79b524592c453a11a1 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:51:23 +0100 Subject: [PATCH 078/175] D3D12.X: a look finds the blocks new to the watched ranges by their change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `hot_runs` makes a block new to the watched ranges hot. To find those it kept a set of all blocks (2 MiB) of the ranges of the last look and, each time the ranges changed, made the set again over every block of every range while holding `HOT` (the walk thread takes it too). The ranges are made again whenever a tile is mapped, a texture is placed, a GPU-view page is shown: in a retail title's world that is ~3.5 GB in 16 ranges, ~1,800 blocks, and the ranges change between many of the submits. Now `new_blocks` compares the ranges with the last look's (both sorted and apart, as `watch_ranges` makes them): a range found among the old ones as it is has no new block, and a block of a changed range is new when no old range meets it, which is what the set said. 16 ranges with one changed: 4 µs against 1.4 ms for a set of all their blocks (debug build, the test's own timing; not measured in a release build or a game). Test: new_blocks_are_those_no_old_range_meets (against a set of all the old blocks: ranges grown, shifted, merged, new, gone, in part of a block). (cherry picked from commit 5b660277a9460246eca668b144872fe4c66c1594) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 108 +++++++++++++++++--- 1 file changed, 93 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index fb7062494a..1481e8f3d2 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1522,10 +1522,33 @@ struct HotBlocks { /// block -> when a look or the walk last found a written page in it, and why it is hot /// (`HOT_WRITTEN`, `HOT_WALKED`, `HOT_NEW`, `HOT_MARKED`: `look_stats::HOT_WHY`) hot: BTreeMap, - /// the ranges `known` was made for + /// the ranges of the last look (a block new to the ranges starts hot: `new_blocks`) ranges: Option>>, - /// the blocks of those ranges (a block new to the ranges starts hot) - known: std::collections::HashSet, +} + +/// The `HOT_BLOCK`s of `ranges` that no range of `old` meets (both sorted and apart, as `watch_ranges` +/// makes them): a range found in `old` as it is has none, so the ranges changed by a mapping are +/// gone over and not all blocks of all of them. (Before, a set of all the blocks was made again +/// at each change of the ranges: ~1,800 blocks, 3.5 GB, in a retail title's world.) +fn new_blocks(old: &[(usize, usize)], ranges: &[(usize, usize)]) -> Vec { + let met = |lo: usize, hi: usize| { + let i = old.partition_point(|&(a, n)| a + n <= lo); + old.get(i).is_some_and(|&(a, _)| a < hi) + }; + let mut out = Vec::new(); + for &(base, size) in ranges { + if old.binary_search(&(base, size)).is_ok() { + continue; + } + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if !met(b, b + HOT_BLOCK) { + out.push(b); + } + b += HOT_BLOCK; + } + } + out } static HOT: Mutex> = Mutex::new(None); @@ -1550,19 +1573,10 @@ fn hot_runs(ranges: &Arc>, now: std::time::Instant) -> (Vec< let h = g.get_or_insert_with(HotBlocks::default); // a block new to the ranges starts hot: memory just mapped is often written and used at once if !h.ranges.as_ref().is_some_and(|r| Arc::ptr_eq(r, ranges)) { - let mut known = std::collections::HashSet::with_capacity(h.known.len()); - for &(base, size) in ranges.iter() { - let mut b = base & !(HOT_BLOCK - 1); - while b < base + size { - if !h.known.contains(&b) { - h.hot.insert(b, (now, HOT_NEW)); - } - known.insert(b); - b += HOT_BLOCK; - } + let old = h.ranges.replace(Arc::clone(ranges)); + for b in new_blocks(old.as_deref().map_or(&[], |v| &v[..]), ranges) { + h.hot.insert(b, (now, HOT_NEW)); } - h.known = known; - h.ranges = Some(Arc::clone(ranges)); } let keep = hot_for(); h.hot.retain(|_, (t, _)| now.saturating_duration_since(*t) < keep); @@ -4653,6 +4667,70 @@ pub(super) mod tests { assert_eq!(watch_ranges(®ions, vec![(0x1000_0000, 0x1000_1000), (0x2008_0000, 0x2009_0000)]), vec![(0x2008_0000, 0x1_0000)]); } + /// `new_blocks` finds the blocks a set of all the old ranges' blocks did not have (what + /// `hot_runs` made before), going over the changed ranges only. + #[test] + fn new_blocks_are_those_no_old_range_meets() { + let blocks_of = |ranges: &[(usize, usize)]| -> std::collections::BTreeSet { + let mut out = std::collections::BTreeSet::new(); + for &(base, size) in ranges { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + out.insert(b); + b += HOT_BLOCK; + } + } + out + }; + let reference = |old: &[(usize, usize)], new: &[(usize, usize)]| -> Vec { + let known = blocks_of(old); + let mut v: Vec = Vec::new(); + for &(base, size) in new { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if !known.contains(&b) { + v.push(b); + } + b += HOT_BLOCK; + } + } + v + }; + let g = 0x4000_0000usize; + let m = 1usize << 20; + let old = vec![(g, 8 * m), (g + 64 * m, 3 * m), (g + 70 * m + 0x1000, 0x1000), (g + 200 * m, 64 * m)]; + let cases: Vec> = vec![ + old.clone(), + vec![], + // one grown at its end, one shifted inside its blocks, one new, one gone + vec![(g, 13 * m), (g + 64 * m + 0x1000, 3 * m), (g + 100 * m, 5 * m), (g + 200 * m, 64 * m)], + // a range now over what two were + vec![(g, 80 * m)], + // pieces of blocks the old ranges met only in part + vec![(g + 67 * m - 0x1000, 0x2000), (g + 71 * m, 0x1000), (g + 264 * m, 0x1000)], + ]; + for new in &cases { + assert_eq!(new_blocks(&old, new), reference(&old, new), "{new:x?}"); + assert_eq!(new_blocks(&[], new), reference(&[], new)); + } + assert!(new_blocks(&old, &old).is_empty()); + assert_eq!(new_blocks(&old, &cases[2]), vec![g + 8 * m, g + 10 * m, g + 12 * m, g + 100 * m, g + 102 * m, g + 104 * m]); + // (the measured case: ~1,800 blocks in 16 ranges, one of them changed) + let big: Vec<(usize, usize)> = (0..16).map(|k| (g + k * (256 * m), 224 * m)).collect(); + let mut changed = big.clone(); + changed[7].1 += 2 * m; + let t = std::time::Instant::now(); + for _ in 0..100 { + assert_eq!(new_blocks(&big, &changed), vec![changed[7].0 + 224 * m]); + } + let ours = t.elapsed(); + let t = std::time::Instant::now(); + for _ in 0..100 { + assert_eq!(reference(&big, &changed), vec![changed[7].0 + 224 * m]); + } + println!("new blocks of 16 ranges, one changed: {:?} a time, a set of all blocks {:?}", ours / 100, t.elapsed() / 100); + } + #[test] fn watch_ranges_merge_at_the_gap_limit_and_split_past_it() { let base = 0x1000_0000usize; From eabf2de0f0b73f175f46d6ed70a84d0c5ba6b2e8 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:00:07 +0100 Subject: [PATCH 079/175] Tests: a CPU read longer than the readback buffer, and its partial chunks `a_long_cpu_read_lands_in_pieces_and_its_ends_only_in_range`: a read of 16 MiB + 128 KiB that starts and ends inside 64-byte chunks takes two copies of the readback buffer, each waited for with the sparse lock released (`readback_now_with`), and lands the GPU's bytes in the whole range and nowhere outside it. The same test passes with the read that holds the lock (`readback_ranges`). `gpu_fill` sends the tiles' clears first, as a submit does before the title's work: a tile taken from a pool's free list is cleared at the next use of the queue, which was the read's own copy. (cherry picked from commit dd5ecda9bfcb69fa7ed30e2ea8ef9dd973350edb) --- crates/xcl/src/hle/d3d12x/sparse.rs | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 9724611e13..a38c585964 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -9611,6 +9611,12 @@ mod tests { /// `len` bytes of `byte` put into the window's video memory at `va`, not into its CPU memory: /// what the GPU wrote there. unsafe fn gpu_fill(s: &mut State, va: usize, len: usize, byte: u8) { + // (the tiles' clears first, as a submit sends them before the title's work) + let zeroed = zero_runs(std::mem::take(&mut s.to_zero)); + for &(a, n) in &zeroed { + s.clear_sent_range(a, n); + } + s.upload_zeros(&zeroed); let mut d = buffer_desc(len as u64); d.Flags = D3D12_RESOURCE_FLAG_NONE; let mut up: Option = None; @@ -9672,6 +9678,44 @@ mod tests { assert_ne!(again, fake); } + /// A CPU read longer than the readback buffer goes in copies of it one after the other, each + /// waited for with the lock released, and one that begins and ends inside a 64-byte chunk lands + /// those bytes only. + #[test] + fn a_long_cpu_read_lands_in_pieces_and_its_ends_only_in_range() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, PAGE_READWRITE}; + if !cpu_read_unlocked() { + return crate::gpu::recomp::runner::skip_test("XCL_CPU_READ_UNLOCKED=0"); + } + unsafe { + let tiles = READBACK_STAGING / TILE + 2; + let (base, mut s) = test_state_with_reserved(tiles); + if s.rbq.is_none() { + let _ = VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + return crate::gpu::recomp::runner::skip_test("no readback queue"); + } + assert!(!VirtualAlloc(base as *const c_void, tiles * TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + s.commit_range(base, tiles * TILE); + s.flush_pending(); + gpu_fill(&mut s, base, tiles * TILE, 0x3C); + let state = Mutex::new(Some(s)); + // (from 0x1234 into the first tile to 7 bytes into a chunk of the last) + let (va, end) = (base + 0x1234, base + (tiles - 1) * TILE + 0x5007); + readback_now_with(&state, va, end - va); + // (the first byte that is not as it should be, by its distance from `base`) + let other = |a: usize, n: usize, b: u8| std::slice::from_raw_parts(a as *const u8, n).iter().position(|&x| x != b).map(|k| a + k - base); + assert_eq!(other(va, end - va, 0x3C), None, "the whole read has the GPU's bytes, past the readback buffer's size too"); + assert_eq!((other(base, va - base, 0), other(end, base + tiles * TILE - end, 0)), (None, None), "nothing lands outside the read"); + let mut g = state.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.reading.is_none()); + assert_eq!(s.rb_last_fence, s.value, "the last copy was the read's"); + s.wait_for(s.value); + drop(g); + let _ = VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + #[test] fn meets_finds_overlaps_with_sorted_runs() { let runs = [(0x100, 0x140), (0x800, 0x900)]; From 451aad40ef301a92032ce66eab9f24f609c078a1 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:03:10 +0100 Subject: [PATCH 080/175] Docs: list the VIctory-Neo ambient ports in THIRD_PARTY.md The reflection hold, the transparent-light bound and the blue garbage test in ambient.rs are adapted from VIctory-Neo (GPL-3.0-or-later); the row that the mirror port added now names them too. --- THIRD_PARTY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 6202f2aaeb..5f80288fae 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -12,7 +12,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | | [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs` (the programs left out); `crates/xcl/src/hle/d3d12x/ambient.rs`: the cells and their slow mean, and the stand-in for the indirect light made in space – `LIGHT_PLACE_HLSL`, `LIGHT_GATHER_HLSL`, the depth path of `AMBIENT_FILL_R9G9B9E5_HLSL`, `AIR_CAP_HLSL` and the resolve's descriptor slots, after `place`, `gather`, `raise`, `clear_air`, `LIGHT` and `DEPTH` of its `ambient.rs` (commit 99a7f9b) | port of the HLSL into XCL's ambient pass (2026-11-28) | -| [VIctory-Neo](https://github.com/KyleS98/VIctory-Neo) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/mirror.rs`: the light around a mirror's view – the programs' parts by name, `XCL_MIRROR_AMBIENT` and the pass and its programs, after its `crates/victory-gpu/src/mirror.rs` (commits a3af274, 9b61dc9); `crates/xcl/src/hle/d3d12x/depth_uav.rs`: a depth plane brought up to date from its twin before the draws that test against it, after 7da5c9d | port adapted to XCL's passes and state (2026-11-29) | +| [VIctory-Neo](https://github.com/KyleS98/VIctory-Neo) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/mirror.rs`: the light around a mirror's view – the programs' parts by name, `XCL_MIRROR_AMBIENT` and the pass and its programs, after its `crates/victory-gpu/src/mirror.rs` (commits a3af274, 9b61dc9); `crates/xcl/src/hle/d3d12x/depth_uav.rs`: a depth plane brought up to date from its twin before the draws that test against it, after 7da5c9d; `crates/xcl/src/hle/d3d12x/ambient.rs`: the reflections' hold to the light around and their resolve slots (3aca295), the bound on transparent surfaces' light (`CS_SpatialFilterAlpha`, a6e85c6) and the probes' blue garbage test, after its `crates/victory-gpu/src/ambient.rs` at bdc3f38 | port adapted to XCL's passes and state (2026-11-29) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | From f5ccab5bb114b79b96b427e807e64f1762aa3741 Mon Sep 17 00:00:00 2001 From: Enrique Villa Date: Sun, 29 Nov 2026 17:59:13 +0800 Subject: [PATCH 081/175] Tests: give the last-release test's fake resource a GetDesc a68f609f made res_release ask the resource for its desc on the last release (to log a buffer's GPU address). The fake resource in release_tests::the_last_release_drops_entries_before_the_object_goes has only AddRef and Release in its vtable, so the GetDesc slot is a null pointer: the child process the test runs in (XCL_LATE_RELEASE=0) dies with an access violation (0xC0000005) before printing anything, and the parent's assertion fails with an empty output. Fails on CI and on a PC alike. The fake now answers GetDesc with a texture's desc, which takes no GPU address, so the test checks what it checked before. Assisted-by: Claude Code (Claude Opus 5.5) Signed-off-by: Enrique Villa (cherry picked from commit d2fb996414a320812385a5e02c756ea7a689ea34) --- crates/xcl/src/hle/d3d12x/real.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ac22c442ea..473d5e987f 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -11044,9 +11044,15 @@ mod release_tests { } n } + // (the last release asks for the desc, to log a buffer's address: a texture's has none) + unsafe extern "system" fn get_desc(_this: *mut c_void, out: *mut D3D12_RESOURCE_DESC) -> *mut D3D12_RESOURCE_DESC { + *out = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, ..Default::default() }; + out + } let mut orig = [0usize; 12]; orig[1] = add_ref as usize; orig[2] = release as usize; + orig[pc_slot!("ID3D12Resource", "GetDesc")] = get_desc as usize; let mut ext = vec![0usize; 13]; ext[0] = orig.as_ptr() as usize; ext[1..].copy_from_slice(&orig); From 1e75126c0c61b9756f56e6ac3879ea11779dba7f Mon Sep 17 00:00:00 2001 From: DzXAnt22 Date: Thu, 26 Nov 2026 12:07:31 -0500 Subject: [PATCH 082/175] Tests: sparse tests take CI's Basic Render Driver for a software device On nvidia-dev, a_gpu_view_tile_is_filled_from_its_cpu_view_and_follows_its_writes sizes its GPU view by software(): 53 tiles on a software device, 3 GiB on a GPU. software() only looked at DXGI_ADAPTER_FLAG_SOFTWARE. On the CI runner the default adapter is the Microsoft Basic Render Driver (0 MiB VRAM), and the CI log of af2cecc4 shows the test reserving the 3 GiB view there; the device is then removed (0x887a0020) and the device-removal handler ends the test process, so the CI job fails on nvidia-dev and on every PR against it. software() now also counts the Microsoft software adapter by its IDs (vendor 0x1414, device 0x8c), which WARP and the Basic Render Driver share. small_runs_go_up_in_dispatches_and_leave_what_lies_between uses the same check and skips there as its comment intends. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9d967cf8d65ae9dfdd36fd48c51149284c5a9a98) Signed-off-by: Enrique Villa (cherry picked from commit 94be9f5186cf6b80714db6bf6fa6c7f9927cbec1) --- crates/xcl/src/hle/d3d12x/sparse.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index a38c585964..e42486ac89 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -6151,12 +6151,13 @@ mod tests { dev.expect("D3D12 device") } - /// Whether `dev` is a software device (WARP). + /// Whether `dev` is a software device (WARP, or the Microsoft Basic Render Driver CI runs on, + /// which is the default adapter there and need not carry DXGI_ADAPTER_FLAG_SOFTWARE). unsafe fn software(dev: &ID3D12Device) -> bool { use windows::Win32::Graphics::Dxgi::*; let Ok(factory) = CreateDXGIFactory1::() else { return false }; let adapter: windows::core::Result = factory.EnumAdapterByLuid(dev.GetAdapterLuid()); - adapter.and_then(|a| a.GetDesc1()).is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) + adapter.and_then(|a| a.GetDesc1()).is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 || (d.VendorId, d.DeviceId) == (0x1414, 0x8c)) } /// The small ones of an upload's runs go up in dispatches: each lands where it belongs (far From f1a10f1e8c639f4fb8238a3d9b8350e6b1c35976 Mon Sep 17 00:00:00 2001 From: MarcosMDev <54442113+MarcosMDev@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:42:06 -0300 Subject: [PATCH 083/175] Tests: a console MS in the AS slot is refused by its MS translation console_ms_in_as_slot_and_ms_with_as_are_refused_cleanly (#2015) expects the "in the AS slot" refusal. #541 (70f91859) removed that refusal on purpose: a console MS alone in the AS slot is now translated as the mesh shader it is. nvidia-dev has both, so the test failed on every GPU run. The synthetic container has no NGG variant, so it is still refused with E_INVALIDARG, now by the MS translation ("MS: no NGG hardware variant"). The test now expects that. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 2331f2ea810c4c32d4915e1654ba7c02ddc9a06d) Signed-off-by: Enrique Villa (cherry picked from commit 95e3651549275061af72b31141a4efbbdc64c2c5) --- crates/xcl/tests/d3d12_mesh_stream.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/xcl/tests/d3d12_mesh_stream.rs b/crates/xcl/tests/d3d12_mesh_stream.rs index d742ee26d0..3a9cdbdd0a 100644 --- a/crates/xcl/tests/d3d12_mesh_stream.rs +++ b/crates/xcl/tests/d3d12_mesh_stream.rs @@ -2,8 +2,8 @@ //! (`d3d12x::real::dev_create_pipeline_state` / `translated_mesh_stream`), with no game data. //! //! Runs on any D3D12 adapter (AMD, NVIDIA, Intel, or WARP) with zero vendor-specific skips: -//! 1. Synthetic console MS placed in the AS slot with no MS slot is refused cleanly with -//! `E_INVALIDARG` and records the `"in the AS slot – refused"` error. +//! 1. Synthetic console MS placed in the AS slot with no MS slot is taken as the mesh shader +//! (#541) and, having no NGG variant, refused cleanly with `E_INVALIDARG` by its translation. //! 2. Synthetic console MS paired with an AS subobject is refused cleanly with `E_INVALIDARG`. //! 3. Empty, truncated, unknown-subobject, and unreadable-shader pipeline streams fail cleanly //! without panicking or crashing. @@ -91,11 +91,13 @@ fn console_ms_in_as_slot_and_ms_with_as_are_refused_cleanly() { SizeInBytes: std::mem::size_of::(), pPipelineStateSubobjectStream: &st as *const _ as *mut c_void, }; - let err = unsafe { d2.CreatePipelineState::(&desc) }.expect_err("MS in AS slot must be refused"); + let err = unsafe { d2.CreatePipelineState::(&desc) }.expect_err("MS with no NGG variant must be refused"); assert_eq!(err.code(), E_INVALIDARG); + // since #541 it is not refused for its slot: it is translated as the MS it is, and this + // container has no NGG variant to translate assert!( - real::stats().translation_errors.iter().any(|e| e.contains("in the AS slot")), - "expected AS-slot refusal in translation_errors: {:?}", + real::stats().translation_errors.iter().any(|e| e.starts_with("MS: ")), + "expected the MS translation's refusal in translation_errors: {:?}", real::stats().translation_errors ); From e46947d04a51923c6805fbbd51a7964bdf845185 Mon Sep 17 00:00:00 2001 From: Enrique Villa Date: Sun, 29 Nov 2026 16:32:30 +0800 Subject: [PATCH 084/175] D3D12.X: drop CopyScratch resources outside COPY_SCRATCH lock and skip own-work reset hooks Fixes #3069. ID3D12Resource::Release enters vram::PAGES, so dropping a CopyScratch's resource while holding COPY_SCRATCH inverted the lock order against threads that hold PAGES. The cache now hands evicted scratch back to the caller, who drops it after releasing COPY_SCRATCH, and cl_reset leaves the title-recording hooks out for XCL's own (own-work) command lists. Signed-off-by: Enrique Villa (cherry picked from commit e2f500d1991a2c3f78feae35df576b1abdc4d374) --- crates/xcl/src/hle/d3d12x/list_x.rs | 130 ++++++++++++++++++---------- crates/xcl/src/hle/d3d12x/real.rs | 2 +- 2 files changed, 84 insertions(+), 48 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 3cefb413fb..373fd85054 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -170,7 +170,10 @@ pub(super) unsafe fn acquire_scratch_for_copy(list: *mut c_void, n: u64) -> Opti return None; } let bytes = n.next_power_of_two().max(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64).min(MAX_COPY_SCRATCH); - let (raw, cap) = COPY_SCRATCH.lock().unwrap().acquire(list, bytes)?; + let mut dropped = Vec::new(); + let res = COPY_SCRATCH.lock().unwrap().acquire(list, bytes, &mut dropped); + drop(dropped); + let (raw, cap) = res?; (cap >= n).then_some(raw) } @@ -991,10 +994,13 @@ pub fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) /// Remove a released command queue so `KickoffX` never submits to a dead queue. pub(super) fn on_queue_release(queue: usize) { - let mut scratch = COPY_SCRATCH.lock().unwrap(); - scratch.fences.remove(&queue); - scratch.collect_released(); - drop(scratch); + let mut dropped = Vec::new(); + { + let mut scratch = COPY_SCRATCH.lock().unwrap(); + scratch.fences.remove(&queue); + scratch.collect_released(&mut dropped); + } + drop(dropped); LIVE_QUEUES.lock().unwrap().retain(|q| q.queue != queue); every_list(|s| { if s.last_queue == Some(queue) { @@ -2765,25 +2771,31 @@ struct CopyScratchCache { } impl CopyScratchCache { - fn collect_released(&mut self) { - self.released.retain_mut(|scratch| { - if !scratch.idle() { - return true; + /// Move idle released scratch entries into `dropped` so callers drop their COM resources + /// outside `COPY_SCRATCH`: `ID3D12Resource::Release` enters `vram::PAGES`, and a thread holding + /// `PAGES` can wait for `COPY_SCRATCH` (lock-order inversion, #3069). + fn collect_released(&mut self, dropped: &mut Vec) { + let mut i = 0; + while i < self.released.len() { + if self.released[i].idle() { + let scratch = self.released.swap_remove(i); + self.bytes -= scratch.bytes; + dropped.push(scratch); + } else { + i += 1; } - self.bytes -= scratch.bytes; - false - }); + } } - fn release(&mut self, list: usize) { + fn release(&mut self, list: usize, dropped: &mut Vec) { if let Some(scratch) = self.active.remove(&list) { self.released.push(scratch); } - self.collect_released(); + self.collect_released(dropped); } - unsafe fn acquire(&mut self, list: *mut c_void, bytes: u64) -> Option<(usize, u64)> { - self.collect_released(); + unsafe fn acquire(&mut self, list: *mut c_void, bytes: u64, dropped: &mut Vec) -> Option<(usize, u64)> { + self.collect_released(dropped); let key = list as usize; if let Some(scratch) = self.active.get_mut(&key) { // Reset can happen while the previous recording is executing on another queue. @@ -2794,8 +2806,10 @@ impl CopyScratchCache { scratch.recorded = true; return Some((scratch.buffer.as_raw() as usize, scratch.bytes)); } - // Drop the old allocation before growing so the peak stays within the budget. - self.bytes -= self.active.remove(&key).unwrap().bytes; + // Account for the old allocation now; its COM resource is dropped outside `COPY_SCRATCH`. + let old = self.active.remove(&key).unwrap(); + self.bytes -= old.bytes; + dropped.push(old); } if bytes > MAX_COPY_SCRATCH - self.bytes { return None; @@ -2813,24 +2827,34 @@ impl CopyScratchCache { static COPY_SCRATCH: LazyLock> = LazyLock::new(|| Mutex::new(CopyScratchCache::default())); fn release_copy_scratch(list: usize) { - let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.release(list); - if cache.reaping || !cache.released.iter().any(|s| !s.untracked_submission) { - return; - } - // A title can stop submitting work after releasing the list. Reclaim its scratch when - // the GPU finishes even if no call touches the cache again. - cache.reaping = std::thread::Builder::new().name("xcl-copy-scratch".into()).spawn(|| loop { - { - let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.collect_released(); - if !cache.released.iter().any(|s| !s.untracked_submission) { - cache.reaping = false; - return; - } + let mut dropped = Vec::new(); + { + let mut cache = COPY_SCRATCH.lock().unwrap(); + cache.release(list, &mut dropped); + if !cache.reaping && cache.released.iter().any(|s| !s.untracked_submission) { + // A title can stop submitting work after releasing the list. Reclaim its scratch when + // the GPU finishes even if no call touches the cache again. + cache.reaping = std::thread::Builder::new().name("xcl-copy-scratch".into()).spawn(|| loop { + let mut reaped = Vec::new(); + let done = { + let mut cache = COPY_SCRATCH.lock().unwrap(); + cache.collect_released(&mut reaped); + if !cache.released.iter().any(|s| !s.untracked_submission) { + cache.reaping = false; + true + } else { + false + } + }; + drop(reaped); + if done { + return; + } + std::thread::sleep(Duration::from_millis(16)); + }).is_ok(); } - std::thread::sleep(Duration::from_millis(16)); - }).is_ok(); + } + drop(dropped); } unsafe fn copy_scratch(list: *mut c_void, n: u64) -> Option<(usize, u64)> { @@ -2838,7 +2862,10 @@ unsafe fn copy_scratch(list: *mut c_void, n: u64) -> Option<(usize, u64)> { return None; } let bytes = n.next_power_of_two().max(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64); - COPY_SCRATCH.lock().unwrap().acquire(list, bytes) + let mut dropped = Vec::new(); + let res = COPY_SCRATCH.lock().unwrap().acquire(list, bytes, &mut dropped); + drop(dropped); + res } fn reset_copy_scratch(list: *mut c_void) { @@ -2850,9 +2877,12 @@ fn reset_copy_scratch(list: *mut c_void) { /// Mark GPU ownership on the queue that actually submitted each PC list or split segment. pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_void]) { + let mut dropped = Vec::new(); let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.collect_released(); + cache.collect_released(&mut dropped); if !lists.iter().any(|l| cache.active.get(&(*l as usize)).is_some_and(|s| s.recorded)) { + drop(cache); + drop(dropped); return; } let mark = (|| { @@ -2879,6 +2909,8 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_ } } } + drop(cache); + drop(dropped); } unsafe fn make_copy_scratch(list: *mut c_void, bytes: u64) -> Option { @@ -5845,27 +5877,29 @@ mod tests { let first_raw = first.as_raw(); let second_raw = second.as_raw(); - let initial = cache.acquire(first_raw, small).unwrap(); - assert_eq!(cache.acquire(first_raw, MAX_COPY_SCRATCH), Some(initial)); + let mut dropped = Vec::new(); + let initial = cache.acquire(first_raw, small, &mut dropped).unwrap(); + assert_eq!(cache.acquire(first_raw, MAX_COPY_SCRATCH, &mut dropped), Some(initial)); let scratch = cache.active.get_mut(&(first_raw as usize)).unwrap(); scratch.recorded = false; scratch.marks.insert(fence.as_raw() as usize, (fence.clone(), 1)); - assert!(cache.acquire(first_raw, MAX_COPY_SCRATCH).is_none()); + assert!(cache.acquire(first_raw, MAX_COPY_SCRATCH, &mut dropped).is_none()); fence.Signal(1).unwrap(); - assert_eq!(cache.acquire(first_raw, MAX_COPY_SCRATCH).unwrap().1, MAX_COPY_SCRATCH); + assert_eq!(cache.acquire(first_raw, MAX_COPY_SCRATCH, &mut dropped).unwrap().1, MAX_COPY_SCRATCH); assert_eq!(cache.bytes, MAX_COPY_SCRATCH); - assert!(cache.acquire(second_raw, small).is_none()); + assert!(cache.acquire(second_raw, small, &mut dropped).is_none()); let scratch = cache.active.get_mut(&(first_raw as usize)).unwrap(); scratch.marks.insert(fence.as_raw() as usize, (fence.clone(), 2)); - cache.release(first_raw as usize); + cache.release(first_raw as usize, &mut dropped); assert!(!cache.active.contains_key(&(first_raw as usize))); - assert!(cache.acquire(second_raw, small).is_none()); + assert!(cache.acquire(second_raw, small, &mut dropped).is_none()); fence.Signal(2).unwrap(); - assert!(cache.acquire(second_raw, small).is_some()); + assert!(cache.acquire(second_raw, small, &mut dropped).is_some()); assert_eq!(cache.bytes, small); - cache.release(second_raw as usize); + cache.release(second_raw as usize, &mut dropped); assert_eq!(cache.bytes, 0); + drop(dropped); } } @@ -5888,12 +5922,14 @@ mod tests { let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); let (raw, key) = (list.as_raw(), list.as_raw() as usize); let small = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64; + let mut dropped = Vec::new(); { let mut cache = COPY_SCRATCH.lock().unwrap(); - cache.acquire(raw, small).unwrap(); + cache.acquire(raw, small, &mut dropped).unwrap(); let scratch = cache.active.get_mut(&key).unwrap(); scratch.marks.insert(fence.as_raw() as usize, (fence.clone(), 1)); } + drop(dropped); on_create(raw, alloc.as_raw() as usize, 0, ty); // Read under the lock, assert after it: a failed assert while holding the lock poisons // COPY_SCRATCH, the list's Release hook (`real::cl_release`) then panics on it while the diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 473d5e987f..cbbaa9e693 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4260,7 +4260,7 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, in let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; let hr = f(this, allocator, resolved); preserve_vtable(this, ext); - if hr >= 0 { + if hr >= 0 && !super::title_textures::is_own_work() { super::list_x::on_pc_reset(this); super::dred::reset(this); if !initial_state.is_null() { From 28510c2705e1f47934cc62b14ae8f2835fbf17c1 Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 07:59:57 +0300 Subject: [PATCH 085/175] Recompiler: serialize dxc::wait_for_memory slot admission wait_for_memory previously checked WORKING against commit headroom and WANTED_AT_ONCE with an unlocked load before calling fetch_add(1), allowing concurrent worker wakeups to admit an unbounded burst past both limits. Wrap the admission check and working-slot increment in a MemoryGate mutex while keeping MemorySlot::drop lock-free and sleeping outside the mutex, and add multi-threaded unit tests verifying tight-headroom, WANTED_AT_ONCE, low-commit single-slot, and timeout behavior. Part of #2463 Part of #1566 Part of #1269 Assisted-by: Antigravity (Gemini 4 Hydrogen) Assisted-by: Codex (GPT-5.6-sol) (cherry picked from commit a34eaed4d9a49626ca1e84c4f4a2f09f89c8a82b) --- crates/xcl/src/gpu/recomp/dxc.rs | 187 +++++++++++++++++++++++++++---- 1 file changed, 168 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index fe6dd06801..4a5e4b3fb5 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -678,17 +678,62 @@ pub fn set_memory_reserve(gb: u64) { } /// Compiles running on the DXC workers (`wait_for_memory` lets them in). -static WORKING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +struct MemoryGate { + gate: Mutex<()>, + working: std::sync::atomic::AtomicUsize, +} + +impl MemoryGate { + const fn new() -> Self { + Self { gate: Mutex::new(()), working: std::sync::atomic::AtomicUsize::new(0) } + } + + /// Evaluates commit headroom and `WANTED_AT_ONCE` atomically with `working` admission so + /// concurrent worker wakeups cannot admit a burst past either cap. + fn try_admit(&self, reserve_bytes: u64, avail: impl FnOnce() -> Option, timed_out: bool, wanted: &Wanted) -> bool { + let _guard = self.gate.lock().unwrap_or_else(|e| e.into_inner()); + let cur = self.working.load(Ordering::Acquire); + let need = reserve_bytes.saturating_add((cur as u64) << 30); + let plenty = avail().is_none_or(|a| a >= need); + if plenty || timed_out || cur == 0 || (cur < WANTED_AT_ONCE && wanted()) { + self.working.fetch_add(1, Ordering::AcqRel); + return true; + } + false + } + + /// Waits until [`Self::try_admit`] grants a slot, sleeping outside the gate mutex. + fn wait_with(&self, reserve_bytes: u64, mut avail: impl FnMut() -> Option, timeout: std::time::Duration, wanted: &Wanted) { + let start = std::time::Instant::now(); + while !self.try_admit(reserve_bytes, &mut avail, start.elapsed() >= timeout, wanted) { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } + + fn release(&self) { + self.working.fetch_sub(1, Ordering::AcqRel); + } +} + +static MEMORY_GATE: MemoryGate = MemoryGate::new(); /// A compile let in by `wait_for_memory`, until it is dropped. pub struct MemorySlot; impl Drop for MemorySlot { fn drop(&mut self) { - WORKING.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + MEMORY_GATE.release(); } } +/// Available page-file commit bytes from Windows, or `None` if the query fails. +fn avail_page_file() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) +} + /// Before a compile: with 6 GB of commit left or more, plus 1 GB for every compile already /// running (each can still grow to ~0.7 GB), at once; with less, one compile at a /// time – it goes when no other is running (and after a minute in any case). Each compile used @@ -698,23 +743,8 @@ impl Drop for MemorySlot { /// of its threads waited for cold compiles, four of which stood in this queue, until its watchdog /// ended it. pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { - use std::sync::atomic::Ordering; - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; - let start = std::time::Instant::now(); - loop { - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - let need = (RESERVE_GB.load(Ordering::Relaxed) << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30); - let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= need; - if plenty || start.elapsed().as_secs() >= 60 || (WORKING.load(Ordering::Acquire) < WANTED_AT_ONCE && wanted()) { - WORKING.fetch_add(1, Ordering::AcqRel); - return MemorySlot; - } - if WORKING.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).is_ok() { - return MemorySlot; - } - std::thread::sleep(std::time::Duration::from_millis(50)); - } + MEMORY_GATE.wait_with(RESERVE_GB.load(Ordering::Relaxed) << 30, avail_page_file, std::time::Duration::from_secs(60), wanted); + MemorySlot } /// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started @@ -2031,3 +2061,122 @@ mod accessor_library_tests { assert!(!gate.close()); } } + +#[cfg(test)] +mod memory_gate_tests { + use super::*; + use std::sync::atomic::AtomicUsize; + use std::sync::Barrier; + use std::time::Duration; + + #[test] + fn tight_commit_headroom_bounds_concurrent_admissions() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let avail_gb = 7u64 << 30; // fits working == 0 (6 GiB) and working == 1 (7 GiB), not 2 (8 GiB) + let threads = 16; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| false); + barrier.wait(); + if gate.try_admit( + reserve, + || { + std::thread::sleep(Duration::from_millis(2)); + Some(avail_gb) + }, + false, + &wanted, + ) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), 2, "burst admitted more compiles than commit headroom allows"); + assert_eq!(gate.working.load(Ordering::SeqCst), 2); + } + + #[test] + fn wanted_burst_never_exceeds_wanted_at_once() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 16; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| { + std::thread::sleep(Duration::from_millis(2)); + true + }); + barrier.wait(); + if gate.try_admit(reserve, || Some(low_avail), false, &wanted) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), WANTED_AT_ONCE, "wanted burst exceeded WANTED_AT_ONCE"); + assert_eq!(gate.working.load(Ordering::SeqCst), WANTED_AT_ONCE); + } + + #[test] + fn wait_for_memory_drains_concurrent_waiters_within_cap() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 12; + let barrier = Barrier::new(threads); + let active = AtomicUsize::new(0); + let max_active = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| true); + barrier.wait(); + gate.wait_with(reserve, || Some(low_avail), Duration::from_secs(60), &wanted); + let cur = active.fetch_add(1, Ordering::SeqCst) + 1; + max_active.fetch_max(cur, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(25)); + active.fetch_sub(1, Ordering::SeqCst); + gate.release(); + }); + } + }); + let peak = max_active.load(Ordering::SeqCst); + assert!(peak <= WANTED_AT_ONCE, "peak concurrent slots {peak} exceeded WANTED_AT_ONCE ({WANTED_AT_ONCE})"); + assert_eq!(gate.working.load(Ordering::SeqCst), 0); + } + + #[test] + fn low_commit_unwanted_admits_only_one_progress_slot() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 8; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| false); + barrier.wait(); + if gate.try_admit(reserve, || Some(low_avail), false, &wanted) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), 1, "only one progress compile may run when commit is short and unwanted"); + assert_eq!(gate.working.load(Ordering::SeqCst), 1); + let wanted: Wanted = Box::new(|| false); + assert!(gate.try_admit(reserve, || Some(low_avail), true, &wanted), "timed-out waiter must still admit"); + assert_eq!(gate.working.load(Ordering::SeqCst), 2); + } +} From 725fd9e35ed6a3838e8773a09d0e628f46e4059b Mon Sep 17 00:00:00 2001 From: bmjask <> Date: Thu, 26 Nov 2026 03:02:11 +0300 Subject: [PATCH 086/175] DXC: keep LINK_GATE open on OOM and forward opt/extra args to IDxcLinker::Link Fix two linked-compilation bugs in dxc.rs introduced alongside accessor-library linking (#174): 1. Keep LINK_GATE open and propagate transient E_OUTOFMEMORY errors directly from compile_linked_or_fallback instead of permanently disabling linked compilation and falling back to the heavier compile_whole path under memory pressure. Deterministic non-OOM failures still close LINK_GATE once and fall back to compile_whole. 2. Forward the shader optimization tier and caller extra arguments to IDxcLinker::Link, and reject library blobs whose length cannot be represented by the API. Add unit tests for OOM gate retention, link argument boundaries, and live DXC argument forwarding. Part of #174 Part of #1566 Part of #1269 Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) Assisted-by: Codex (GPT-5.6-sol) (cherry picked from commit f4708511d8e49a4f3a0739574723ecc2ce5f8f20) --- crates/xcl/src/gpu/recomp/dxc.rs | 118 ++++++++++++++++++++++++++++--- 1 file changed, 107 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 4a5e4b3fb5..59470407e6 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -789,15 +789,11 @@ fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result // linear this way (`emit::linked_form`). Anything wrong with it: as one program, as before. if profile.starts_with("cs_") && linking() { if let Some((program, library)) = super::emit::linked_form(src, LINK_MIN_ACCESSES) { - match compile_linked(&program, &library, entry, profile, extra) { - Ok(dxil) => return Ok(dxil), - Err(e) => { - // the same DXC fails the same way for the next program: stop trying - if LINK_GATE.close() { - crate::xlog_warn!("DXC: a program could not be linked with its memory accessors, compiled whole, and no more programs are linked: {e}"); - } - } - } + return compile_linked_or_fallback( + &LINK_GATE, + || compile_linked(&program, &library, entry, profile, extra), + || compile_whole(src, entry, profile, extra), + ); } } compile_whole(src, entry, profile, extra) @@ -828,6 +824,47 @@ impl LinkGate { static LINK_GATE: LinkGate = LinkGate::new(); +fn is_oom_error(err: &str) -> bool { + let lower = err.to_ascii_lowercase(); + lower.contains("0x8007000e") || lower.contains("e_outofmemory") +} + +/// Try `linked()` while `gate` is open; transient OOM propagates without closing `gate` or +/// falling back to the heavier `whole()`, while deterministic failures close `gate` and retry whole. +fn compile_linked_or_fallback( + gate: &LinkGate, + linked: impl FnOnce() -> Result, String>, + whole: impl FnOnce() -> Result, String>, +) -> Result, String> { + if !gate.open() { + return whole(); + } + match linked() { + Ok(dxil) => Ok(dxil), + Err(e) if is_oom_error(&e) => Err(e), + Err(e) => { + // the same DXC fails the same way for the next program: stop trying + if gate.close() { + crate::xlog_warn!("DXC: a program could not be linked with its memory accessors, compiled whole, and no more programs are linked: {e}"); + } + whole() + } + } +} + +fn link_opt_args<'a>(src_len: usize, extra: &'a [&'a str]) -> Vec<&'a str> { + let mut args = Vec::with_capacity(extra.len() + 3); + if !extra.iter().any(|a| a.starts_with("-O") || *a == "-Od") { + if src_len > UNOPTIMISED_ABOVE { + args.extend(["-O0", "-opt-disable", "debug-nops"]); + } else if src_len > 1024 * 1024 { + args.push("-O1"); + } + } + args.extend(extra.iter().copied()); + args +} + /// `XCL_LINK_MEM=0`: every program is compiled whole (into the same cache: compare with /// another `XCL_DXIL_CACHE`). fn linking() -> bool { @@ -852,6 +889,7 @@ fn kept_once(map: &Mutex>>> /// Compile `program` and `library` (its memory accessors, kept once compiled) as libraries and /// link them to `profile`. fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { + let program_src_len = program.len(); let model = profile.split_once('_').map_or("6_6", |(_, m)| m); let lib = format!("lib_{model}"); let accessors = { @@ -868,17 +906,20 @@ fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extr } Ok(p) }; + let link_args_w: Vec> = link_opt_args(program_src_len, extra).into_iter().map(crate::util::wide).collect(); + let link_ptrs: Vec = link_args_w.iter().map(|a| PCWSTR(a.as_ptr())).collect(); unsafe { let linker = IDxcLinker::from_raw(instance(&CLSID_DxcLinker, &IDxcLinker::IID)?); let utils = IDxcUtils::from_raw(instance(&CLSID_DxcUtils, &IDxcUtils::IID)?); let names = [crate::util::wide("program"), crate::util::wide("accessors")]; for (name, dxil) in names.iter().zip([&program, &*accessors]) { - let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, dxil.len() as u32, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?; + let len = u32::try_from(dxil.len()).map_err(|_| "DXIL library larger than 4 GiB".to_string())?; + let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, len, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?; linker.RegisterLibrary(PCWSTR(name.as_ptr()), &blob).map_err(|e| format!("RegisterLibrary: {e}"))?; } let (entry, profile) = (crate::util::wide(entry), crate::util::wide(profile)); let r = linker - .Link(PCWSTR(entry.as_ptr()), PCWSTR(profile.as_ptr()), &names.each_ref().map(|n| PCWSTR(n.as_ptr())), None) + .Link(PCWSTR(entry.as_ptr()), PCWSTR(profile.as_ptr()), &names.each_ref().map(|n| PCWSTR(n.as_ptr())), (!link_ptrs.is_empty()).then_some(link_ptrs.as_slice())) .map_err(|e| format!("Link: {e}"))?; output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult()) } @@ -2060,6 +2101,61 @@ mod accessor_library_tests { assert!(!gate.open()); assert!(!gate.close()); } + + #[test] + fn compile_linked_or_fallback_keeps_gate_open_on_oom() { + let gate = LinkGate::new(); + for oom in ["dxc (0x8007000E): out of memory", "Link: HRESULT(0x8007000e)", "CreateBlob: E_OUTOFMEMORY"] { + let mut whole_ran = false; + let err = compile_linked_or_fallback(&gate, || Err(oom.into()), || { whole_ran = true; Ok(vec![1]) }).unwrap_err(); + assert_eq!(err, oom); + assert!(gate.open() && !whole_ran, "OOM must keep LinkGate open and skip whole fallback: {oom}"); + } + // Deterministic non-OOM failure closes the gate and falls back to whole; subsequent calls skip linked. + let mut whole_runs = 0usize; + let ok = compile_linked_or_fallback(&gate, || Err("dxc: unsupported WaveSize on library".into()), || { whole_runs += 1; Ok(vec![42]) }).unwrap(); + assert_eq!((ok, gate.open(), whole_runs), (vec![42], false, 1)); + let ok = compile_linked_or_fallback(&gate, || panic!("linked must not run once gate is closed"), || { whole_runs += 1; Ok(vec![99]) }).unwrap(); + assert_eq!((ok, whole_runs), (vec![99], 2)); + } + + #[test] + fn link_opt_args_selects_tier_and_preserves_extra() { + assert_eq!(link_opt_args(1024 * 1024, &[]), Vec::<&str>::new()); + assert_eq!(link_opt_args(1024 * 1024 + 1, &[]), vec!["-O1"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE, &[]), vec!["-O1"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &[]), vec!["-O0", "-opt-disable", "debug-nops"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-O2"]), vec!["-O2"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-Od"]), vec!["-Od"]); + assert_eq!(link_opt_args(512, &["-Gis"]), vec!["-Gis"]); + assert_eq!(link_opt_args(1024 * 1024 + 1, &["-Gis"]), vec!["-O1", "-Gis"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-Gis"]), vec!["-O0", "-opt-disable", "debug-nops", "-Gis"]); + } + + #[test] + fn compile_linked_forwards_opt_and_extra_args_to_dxc_linker() { + if location().is_err() { + return super::super::runner::skip_test("no DXC"); + } + let library = "RWByteAddressBuffer res : register(u0);\nexport uint helper_add(uint a, uint b) { return a + b; }\n"; + let program = "RWByteAddressBuffer res : register(u0);\nuint helper_add(uint a, uint b);\n[shader(\"compute\")]\n[numthreads(64, 1, 1)]\nvoid main(uint gi : SV_GroupIndex) {\n float x = asfloat(res.Load(gi * 4u));\n float y = (x + 1.0) - 1.0;\n res.Store(gi * 4u, helper_add(asuint(y), gi));\n}\n"; + let run = |args: &[&str]| -> String { + let dxil = compile_linked(program, library, "main", "cs_6_6", args).unwrap_or_else(|e| panic!("args={args:?}: {e}")); + super::super::super::dxil::validate::validate(&dxil).unwrap_or_else(|e| panic!("validate args={args:?}: {e}")); + disassemble(&dxil).unwrap_or_else(|e| panic!("disasm args={args:?}: {e}")) + }; + let d_def = run(&[]); + assert!(!d_def.contains("fadd "), "default link should optimize (x + 1) - 1 away:\n{d_def}"); + let _ = run(&["-O1"]); + let d_o0 = run(&["-O0", "-opt-disable", "debug-nops"]); + assert!(d_o0.contains("fadd fast float") && d_o0.contains("mul i32 ") && !d_o0.contains("dx.op.nop"), "-O0 link must skip -O3 folding and debug-nops:\n{d_o0}"); + let d_gis = run(&["-Gis"]); + assert!(d_gis.contains("fadd float ") && !d_gis.contains("fadd fast "), "-Gis must keep strict IEEE fadd:\n{d_gis}"); + // Also check auto -O1 / -O0 when program.len() > 1 MiB (while library is small). + let big_prog = format!("{program}// {}\n", "a".repeat(1024 * 1024 + 16)); + let dxil_big = compile_linked(&big_prog, library, "main", "cs_6_6", &[]).unwrap(); + super::super::super::dxil::validate::validate(&dxil_big).unwrap(); + } } #[cfg(test)] From 5e48878112f89d7f721d3da4e5eba27c9a1d859d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:30:05 +0100 Subject: [PATCH 087/175] Recompiler: direct compute LDS is the block the program declares The direct DXIL translator gave every compute program that uses LDS the whole 8,192-dword groupshared block D3D12 allows. A one-wave group then holds 32 KB, so an RDNA WGP (128 KB) runs four groups: one wave a SIMD. The title's CS_GenerateShadowMasks_Checkerboard_NoHair (cs d9fac2f1d8f646fd, 4x8 threads, one wave a group, one LDS dword used, LDS_SIZE 1 granule) is the top GPU program of the open world (20-139 ms a frame) and ran so. The block is now the LDS COMPUTE_PGM_RSRC2 declares (CsInterface::lds_dwords, 128-dword granules) followed by the translator's words: a native 2-D / 3-D group's arrival counter, a multi-wave safe barrier's two words, the split form's exchange slots and counters. A header with no size, or one too big to leave room for them, keeps the 8,192-dword layout. LDS addresses are kept below the declared top. XCL_DECLARED_LDS=0 restores the old layout; the translated-shader caches key the switch. Measured offline (Radeon GPU Analyzer, amdxc64 gfx1201, the run's heap windows): the title program's LDS goes from 32,768 to 5,008 bytes (the driver's own share included); VGPRs (256) now limit it, not LDS. Ported from xcl-dev/xcl#2937 (Kalmarv, "XCL_DECLARED_LDS=1 sizes direct compute LDS from the header"), adapted to this tree's safe-barrier words and made default-on; its compute_build_key.rs part has no counterpart here. --- crates/xcl/src/gpu/dxil/core_tests.rs | 99 +++++++++++++++++++-- crates/xcl/src/gpu/dxil/kernel.rs | 40 ++++++++- crates/xcl/src/gpu/dxil/lanes.rs | 35 +++++--- crates/xcl/src/gpu/dxil/lower.rs | 3 + crates/xcl/src/gpu/dxil/lower_mem.rs | 2 +- crates/xcl/src/gpu/dxil/robustness_tests.rs | 4 +- crates/xcl/src/gpu/recomp/link_tests.rs | 4 +- crates/xcl/src/gpu/recomp/lower.rs | 4 +- crates/xcl/src/gpu/recomp/mod.rs | 4 + crates/xcl/src/gpu/recomp/pso.rs | 18 ++++ crates/xcl/src/gpu/recomp/tests.rs | 38 ++++---- 11 files changed, 206 insertions(+), 45 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index a237b2170a..f9f560dcea 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -25,7 +25,7 @@ fn a_single_split_wave_of_a_compute_group_exchanges_without_a_group_barrier() { let code = prog(&[("V_READLANE_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 256), ("SRC1", 160)], None)]); let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; let dis = |threads: u32, code: &[u8]| { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; super::validate::disassemble(&super::kernel::translate_compute(code, o, &cs).unwrap_or_else(|e| panic!("{threads} threads: {e}")).dxil) }; // (barrier mode 9: the thread group's sync with its memory fence, `ops::barrier::GROUP_SYNC`) @@ -150,7 +150,7 @@ fn split_lds_reads_meet_after_writes() { assert!(looped(&[read, write]) >= looped(&[read]) + 2, "the loop's read and write meet when the bits are set"); // compute groups: the counters' meet (two more atomics), none without a partner half let atomics = |threads: u32, list: &[Inst]| { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; let d = super::validate::disassemble(&super::kernel::translate_compute(&prog(list), o, &cs).unwrap_or_else(|e| panic!("{threads} threads: {e}")).dxil).unwrap(); d.matches("atomicrmw").count() @@ -993,7 +993,7 @@ fn count_phis(dis: &str, cap: &str, b: &str) -> Vec { #[test] fn direct_compute_loops_count_each_entry() { use crate::gpu::recomp::CsInterface; - let cs = CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let straight = prog(&[ ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 2)], None), ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)], None), @@ -1066,7 +1066,7 @@ fn the_compute_entry_lets_only_the_lanes_below_the_thread_limits_in() { let load = format!("i32 {}, i32 undef, i8 7, i32 4)", IO_THREAD_LIMIT[0] * 4); for (wave64, split, threads) in [(false, false, 32), (true, false, 64), (true, true, 64), (true, true, 32)] { let o = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; // (a split wave64 of 64 threads is two hardware waves: its barrier is the HLSL path's) for barrier in [false, true].into_iter().filter(|&b| !(b && split && threads == 64)) { let what = format!("wave64 {wave64}, split {split}, {threads} threads, barrier {barrier}"); @@ -1142,7 +1142,7 @@ fn gpu_direct_compute_loop_passes_follow_the_dispatch() { Err(e) => return runner::skip_test(&e), } let threads = 64u32; - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; for wave64 in [false, true] { let o = KernelOptions { wave64, split: wave64, mem_windows: 1, sampler_base: 0 }; let run = |code: &[u8], slot: u32| -> u32 { @@ -1287,7 +1287,7 @@ fn compute_movrel_uses_program_max_vgpr_and_masks_m0() { ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 130)], None), ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), ]); - let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let k = super::kernel::translate_compute(&code, ko, &cs).expect("compute movrel translates"); super::validate::validate(&k.dxil).expect("validates"); if let Ok(dis) = super::validate::disassemble(&k.dxil) { @@ -1537,3 +1537,90 @@ fn scratch_reads_addr_only_in_the_sv_form() { assert!(kernel(0x7D, 2) != kernel(0x7D, 3), "SV (SADDR 0x7d) addresses VADDR + offset"); assert!(kernel(0x7F, 2) != kernel(0x7D, 2), "ST is not the SV form"); } + +/// `f` with `XCL_DECLARED_LDS` taken as `on` by the translations of this thread. +fn with_declared_lds(on: bool, f: impl FnOnce() -> R) -> R { + let before = super::kernel::DECLARED_LDS_FOR_TEST.with(|c| c.replace(Some(on))); + let r = f(); + super::kernel::DECLARED_LDS_FOR_TEST.with(|c| c.set(before)); + r +} + +/// `XCL_DECLARED_LDS=1`: a compute program's groupshared block is the LDS its header declares +/// (COMPUTE_PGM_RSRC2 LDS_SIZE, 128-dword granules) and the translator's words after it – a +/// native 2-D group's arrival counter, a multi-wave barrier's two words, the split form's +/// exchange slots and counters – or the whole 8,192 dwords when the header gives no size or +/// those words would not fit. Off: always 8,192. +#[test] +fn compute_lds_is_the_declared_block_and_the_translators_words() { + use crate::gpu::recomp::CsInterface; + let write = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None)]); + let barrier = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None), ("S_BARRIER", "ENC_SOPP", &[], None)]); + let barrier_words = if crate::gpu::recomp::emit::safe_barrier_wanted() { 2 } else { 0 }; + // (threads, granules, split, program, words with the switch) + let cases: [([u32; 3], u32, bool, &[u8], u32); 8] = [ + ([64, 1, 1], 2, false, &write, 256), + ([8, 8, 1], 1, false, &write, 129), + ([8, 8, 1], 1, false, &barrier, 129 + barrier_words), + ([64, 1, 1], 2, false, &barrier, 256 + barrier_words), + ([8, 8, 1], 1, true, &write, 135), + ([128, 1, 1], 2, true, &write, 269), + ([8, 8, 1], 0, true, &write, 8192), + ([8, 8, 1], 64, true, &write, 8192), + ]; + for (threads, granules, split, code, words) in cases { + // the size comes from the stage descriptor (COMPUTE_PGM_RSRC2 at +0x38, LDS_SIZE at bit 15) + let mut descriptor = [0u8; 0x48]; + for (i, v) in [granules << 15 | 2 << 11, threads[0], threads[1], threads[2]].into_iter().enumerate() { + descriptor[0x38 + 4 * i..0x3C + 4 * i].copy_from_slice(&v.to_le_bytes()); + } + let cs = CsInterface::from_descriptor(&descriptor, 0).unwrap(); + assert_eq!(cs.lds_dwords, granules * 128); + let o = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; + for on in [false, true] { + let k = with_declared_lds(on, || super::kernel::translate_compute(code, o, &cs)).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let dis = super::validate::disassemble(&k.dxil).unwrap(); + let want = if on { words } else { 8192 }; + assert!(dis.contains(&format!("@xcl_lds = external addrspace(3) global [{want} x i32]")), "{threads:?}, {granules} granules, split {split}, switch {on}: {want} words"); + } + } +} + +/// The declared block on the GPU (`XCL_DECLARED_LDS`): a native 2-D wave32 group of two +/// hardware waves (its arrival counter after the program's LDS) whose threads write their +/// index to the LDS, meet at a group barrier (its two words there too) and read another +/// thread's; the same with the switch off. +#[test] +fn gpu_compute_declared_lds_keeps_the_programs_words() { + use crate::gpu::recomp::{runner, CsInterface, KERNEL_SGPRS}; + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + const V: u64 = 256; + let code = prog(&[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 1)], None), // y · 8 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 2), ("VSRC1", 0)], None), // i + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 2)], None), // 4i + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 3), ("DATA0", 2)], None), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)], None), + ("S_BARRIER", "ENC_SOPP", &[], None), + ("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 128 + 63), ("VSRC1", 2)], None), // 63 - i + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 130), ("VSRC1", 4)], None), + ("DS_READ_B32", "ENC_DS", &[("VDST", 6), ("ADDR", 5)], None), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 3)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 8), ("DATA", 6), ("SADDR", 0x7D)], None), + ]); + let cs = CsInterface { threads: [8, 8, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 2, lds_dwords: 128 }; + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + for on in [false, true] { + let k = with_declared_lds(on, || super::kernel::translate_compute(&code, o, &cs)).unwrap_or_else(|e| panic!("switch {on}: {e}")); + let mem = runner::dispatch(&k.dxil, [1, 1, 1], &vec![0u32; KERNEL_SGPRS], &vec![0xFFFF_FFFFu32; 64]).expect("GPU run"); + for i in 0..64 { + assert_eq!(mem[i], 63 - i as u32, "switch {on}: thread {i}"); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index e0063a5a14..92e18bf458 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -40,6 +40,27 @@ pub struct KernelOptions { /// (the `gpu/dxil` sources are not in build.rs's translator source hash). pub const TRANSLATOR_VERSION: u32 = 12; +/// `XCL_DECLARED_LDS` (default on; `=0` off): a compute program's groupshared block is the LDS +/// its header declares (`CsInterface::lds_dwords`) plus the translator's own words after it, +/// instead of the whole 8,192 dwords D3D12 allows (still so when the header gives no size). A +/// one-wave group holding 32 KB let an RDNA WGP (128 KB) run 4 groups: one wave a SIMD. The +/// caches key it apart. (After xcl-dev/xcl#2937, Kalmarv: "XCL_DECLARED_LDS=1 sizes direct +/// compute LDS from the header", there opt-in.) +pub fn declared_lds_enabled() -> bool { + #[cfg(test)] + if let Some(on) = DECLARED_LDS_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_DECLARED_LDS").map_or(true, |v| v.trim() != "0")) +} + +#[cfg(test)] +thread_local! { + /// `declared_lds_enabled` for the translations of this test thread + pub(crate) static DECLARED_LDS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// Console compute shaders (and the kernel tests) go through this translator, with the HLSL /// path as the fallback for what it cannot translate yet: the default, and `XCL_DIRECT_DXIL=1`. /// `XCL_DIRECT_DXIL=0` keeps every stage on the HLSL path. @@ -259,10 +280,16 @@ fn translate_entry_with( // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs let code = code.to_vec(); + #[cfg(test)] + let declared_lds = DECLARED_LDS_FOR_TEST.with(|c| c.get()); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, rodata)) + .spawn(move || { + #[cfg(test)] + DECLARED_LDS_FOR_TEST.with(|c| c.set(declared_lds)); + translate_on_this_thread(&code, o, entry, compact, nest, rodata) + }) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -722,6 +749,7 @@ impl Lw { xslot: 1, lds: None, lds_top: 8191, + lds_declared: false, dpp_enable: None, partner: Partner::Present, mesh: None, @@ -809,7 +837,13 @@ impl Lw { let safe_bar = lw.barrier_waves.is_some_and(|w| w > 1) && has_s_barrier && crate::gpu::recomp::emit::safe_barrier_wanted(); - lw.setup_storage(uses_lds, if split { slot } else { 1 }, safe_bar); + // `XCL_DECLARED_LDS`: the program's own LDS, then the translator's words; a native 2-D + // / 3-D group's arrival counter (`setup_lanes_compute`) is one of them + let (declared, native_counter) = match entry { + Entry::Compute(cs) if declared_lds_enabled() => (cs.lds_dwords, !split && (cs.threads[1] > 1 || cs.threads[2] > 1)), + _ => (0, false), + }; + lw.setup_storage(uses_lds, if split { slot } else { 1 }, safe_bar, declared, native_counter); lw } @@ -963,7 +997,7 @@ fn a_split_wave64_compute_program_stays_whole() { fn a_dispatch_chain_leaves_the_lanes_past_a_thread_limit_out() { use crate::gpu::recomp::{runner, IO_THREAD_LIMIT}; let threads = [32, 1, 1]; - let cs = CsInterface { threads, user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads, user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let options = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs.clone())); let (tid, gtid) = lw.setup_lanes_compute(threads, false); diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index e0a5bfaf3c..c5680de86f 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -21,28 +21,43 @@ impl Lw { /// the program's LDS (`lds_words` > 0), multi-wave safe-barrier counters /// (`safe_bar`, 2 words), and, in the split form, the halves' exchange /// words — in the top of the LDS block when there is one (D3D12 allows - /// 32 KB, the whole LDS), as the HLSL kernel lays it out. - pub fn setup_storage(&mut self, lds: bool, slot: u32, safe_bar: bool) { + /// 32 KB, the whole LDS), as the HLSL kernel lays it out. With `declared` + /// dwords (`XCL_DECLARED_LDS`, 0 = not known) the block is the program's + /// LDS followed by those words (and a native 2-D / 3-D group's arrival + /// counter, `native_counter`), when they fit in 8,192. + pub fn setup_storage(&mut self, lds: bool, slot: u32, safe_bar: bool, declared: u32, native_counter: bool) { let i32 = self.s.m.i32(); self.xslot = slot.max(1); if lds { - let g = self.s.groupshared("xcl_lds", i32, 8192); + // the translator's words at the top: [exchange slots, counters (split)], + // [XCL_BAR_ALIVE, XCL_BAR_STATE (safe_bar)], XCL_XW / XCL_WT + let bar_words = if safe_bar { 2 } else { 0 }; + let slots = 4 * self.xslot * self.waves; + let control = if self.split { slots + 2 * self.waves + 1 + bar_words } else { bar_words + u32::from(native_counter) }; + let fits = declared != 0 && declared <= 8192u32.saturating_sub(control); + let words = if fits { declared + control } else { 8192 }; + let g = self.s.groupshared("xcl_lds", i32, words as u64); self.lds = Some(g); if safe_bar { // Words 8189 = XCL_BAR_ALIVE, 8190 = XCL_BAR_STATE (8191 = XCL_XW / XCL_WT), - // matching `recomp::emit::safe_barrier_prelude`. - self.safe_bar = Some((g, 8189)); + // matching `recomp::emit::safe_barrier_prelude`; with the declared LDS of a + // native group right after the program's + self.safe_bar = Some((g, if fits && !self.split { declared } else { words - 3 })); } if self.split { // HLSL: exchange base = 8192 - slots - counters - 1 (- 2 if safe_bar) // (slots = 4 · slot per console wave, 2 counters each); program LDS stops below it. - let bar_words = if safe_bar { 2 } else { 0 }; - let slots = 4 * self.xslot * self.waves; - let base = 8192 - slots - 2 * self.waves - 1 - bar_words; + let base = words - control; self.lds_top = base - 1; self.xs = Some((g, base)); self.xc = Some((g, base + slots)); - self.xw = Some((g, 8191)); + self.xw = Some((g, words - 1)); + } else if fits { + self.lds_top = declared - 1; + self.lds_declared = true; + if native_counter { + self.xw = Some((g, words - 1)); + } } else { self.lds_top = if safe_bar { 8188 } else { 8191 }; } @@ -133,7 +148,7 @@ impl Lw { } else if y * z > 1 { let i32 = self.s.m.i32(); let (g, at) = match (self.lds, lds_top_word) { - (Some(l), true) => (l, 8191), + (Some(l), true) => self.xw.unwrap_or((l, 8191)), _ => (self.s.groupshared("xcl_wt", i32, 1), 0), }; let ai = self.c(at); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index d42a7f93a4..b32e10c6c1 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -278,6 +278,9 @@ pub struct Lw { /// the program's LDS (`xcl_lds`, 8192 dwords) and its last usable dword pub lds: Option, pub lds_top: u32, + /// the block is the declared LDS and the words after it (`XCL_DECLARED_LDS`): addresses + /// are kept below them + pub lds_declared: bool, /// DPP write enable of the instruction being lowered pub dpp_enable: Option, /// the split form's partner half: present, missing (a console wave of at most 32 diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 14372057c0..f874dc8fa3 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2125,7 +2125,7 @@ impl Lw { fn lds_index(&mut self, at: Value) -> Value { let i = self.lshrc(at, 2); let i = self.andc(i, 8191); - if self.split { + if self.split || self.lds_declared { let k = self.c(self.lds_top); self.umin(i, k) } else { diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index 95495ca409..eda598d683 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -70,7 +70,7 @@ fn translate_all() -> Vec> { attrs: None, early_depth: false, }; - let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; let mut out = Vec::new(); for (w, s) in [(false, false), (true, true), (true, false)] { @@ -105,7 +105,7 @@ fn a_group_barrier_of_several_hardware_waves_uses_safe_barrier_directly() { } let code = prog(&[("S_BARRIER", "ENC_SOPP", &[], None)]); let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; - let cs = |threads| CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = |threads| CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; // 16 x 16 threads: 8 hardware waves in the split form, 4 native 64-lane ones, 8 of a // 32-lane program; and the two 32-lane halves of one console wave for (wave64, split, threads) in [(true, true, [16, 16, 1]), (true, false, [16, 16, 1]), (false, false, [16, 16, 1]), (true, true, [64, 1, 1])] { diff --git a/crates/xcl/src/gpu/recomp/link_tests.rs b/crates/xcl/src/gpu/recomp/link_tests.rs index b2e99dfab9..c28b6acf4f 100644 --- a/crates/xcl/src/gpu/recomp/link_tests.rs +++ b/crates/xcl/src/gpu/recomp/link_tests.rs @@ -162,7 +162,7 @@ fn bench_memory_window_accessors() { for round in 0..3 { for windows in [1, 4] { nonce = nonce.wrapping_mul(0x9E37_79B1) | 1; - let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 24, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let t = translate(&program(n, nonce), &on_gpu(Options { mode: Mode::Compute(cs), wave64: true, mem_windows: windows, ..Default::default() })).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let forms = if windows == 1 { @@ -212,7 +212,7 @@ fn linked_programs_keep_their_declarations() { let list = [buf("BUFFER_LOAD_DWORD", 2, coherent), buf("BUFFER_STORE_DWORD", 3, false)]; let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let p = prog(&refs); - let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 16, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let t = translate(&p, &Options { mode: Mode::Compute(cs), wave64, mem_windows: 4, ..Default::default() }).unwrap(); let size = if wave64 { 64 } else { 32 }; assert!(t.hlsl.contains(&format!("[WaveSize({size})]")), "{}", t.hlsl); diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 9cdf0f441d..a59e5380da 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -3122,7 +3122,7 @@ pub(crate) mod tests { } pub(crate) fn compute_cs() -> crate::gpu::recomp::CsInterface { - crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 } + crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() } } /// A compute program run on the CPU over `groups` groups (wave32): the memory after. @@ -3194,7 +3194,7 @@ pub(crate) mod tests { } mem }; - let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 } }; + let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 }, ..Default::default() }; let limit = |x: u32, y: u32| vec![(IO_THREAD_LIMIT[0], x), (IO_THREAD_LIMIT[1], y)]; for wave64 in [false, true] { let lanes = if wave64 { 64 } else { 32 }; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 12433340ff..b2dad4c544 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -282,6 +282,9 @@ pub struct CsInterface { pub tg_size: bool, /// thread id VGPRs: 1 (v0), 2 (v0, v1) or 3 (v0..v2) pub tid_components: u32, + /// the group's LDS from COMPUTE_PGM_RSRC2 (LDS_SIZE, 128-dword granules), in dwords; 0 = not + /// given (`gpu::dxil::kernel::declared_lds_enabled`) + pub lds_dwords: u32, } impl CsInterface { @@ -303,6 +306,7 @@ impl CsInterface { tgid: [(r >> 7) & 1 == 1, (r >> 8) & 1 == 1, (r >> 9) & 1 == 1], tg_size: (r >> 10) & 1 == 1, tid_components: ((r >> 11) & 3) + 1, + lds_dwords: ((r >> 15) & 0x1FF) * 128, } } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 7b704cd9c8..108272f5ac 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -307,6 +307,10 @@ mod translated { let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::rt_all_miss() { identity_for(&id.to_string(), "xcl-rt-all-miss") } else { id }; + // `XCL_DECLARED_LDS` (on): compute programs' groupshared blocks are another output + let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::declared_lds_enabled() { + identity_for(&id.to_string(), "xcl-declared-lds") + } else { id }; // `XCL_NAN_GUARD=0`: disabling PS float NaN/Inf sanitization changes pixel DXIL let id = if Backend::current() != Backend::Hlsl && !crate::gpu::dxil::kernel::nan_guard_enabled() { identity_for(&id.to_string(), "xcl-nan-guard-0") @@ -556,6 +560,7 @@ mod translated { Some(tag) => identity_for(&id.to_string(), tag), None => id, }; + let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); if crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) @@ -1579,6 +1584,19 @@ mod slab_tests { mod shader_cache_tests { use super::*; + /// `XCL_DECLARED_LDS=1` translations are other entries of the direct translator's caches. + #[test] + fn declared_lds_is_another_direct_output() { + let with = |on| { + let before = crate::gpu::dxil::kernel::DECLARED_LDS_FOR_TEST.with(|c| c.replace(Some(on))); + let id = translated::direct_output_identity(None, 1); + crate::gpu::dxil::kernel::DECLARED_LDS_FOR_TEST.with(|c| c.set(before)); + id + }; + assert_ne!(with(false), with(true)); + assert_eq!(with(true), with(true)); + } + /// The switch form (no heap windows, or a pipeline retried in it) has 4 root UAVs: a wider /// count there is 4, which every translator takes; the heap form keeps all of them. #[test] diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 9c77f38bd0..0f319e9e78 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -5781,7 +5781,7 @@ fn gpu_compute_mode_dispatch_abi() { return; } use super::{dxc, CsInterface}; - let cs = CsInterface { threads: [16, 8, 1], user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2 }; + let cs = CsInterface { threads: [16, 8, 1], user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2, ..Default::default() }; let p = prog(&[ ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 132), ("VSRC1", 1)], None), // y · 16 ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V + 2), ("VSRC1", 0)], None), // index in group @@ -7758,7 +7758,7 @@ fn split_wave64_meet_form_by_group_size() { let lane = prog(&[("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)], None)]); for (dims, want) in [([64u32, 1, 1], 0), ([8, 8, 1], 0), ([4, 4, 4], 0), ([40, 1, 1], 0), ([32, 1, 1], 0), ([16, 1, 1], 0), ([256, 1, 1], 1), ([8, 8, 4], 1)] { let threads = dims.iter().product::(); - let cs = CsInterface { threads: dims, user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: dims, user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let t = translate(&lane, &Options { mode: Mode::Compute(cs), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); assert!(t.hlsl.contains(&format!("#define XCL_X_THREADS {threads}u")), "{dims:?}"); @@ -7768,7 +7768,7 @@ fn split_wave64_meet_form_by_group_size() { assert!(t.hlsl.contains("xcl_x_rla_uniform("), "{dims:?}"); } // a half without a partner (32 threads or fewer: `xcl_xn == 0`) leaves before either form - let t = translate(&lane, &Options { mode: Mode::Compute(CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); + let t = translate(&lane, &Options { mode: Mode::Compute(CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }), wave64: true, split_wave64: true, ..Default::default() }).unwrap(); let meet = &t.hlsl[t.hlsl.find("bool xcl_x_meet()").unwrap()..]; let (leave, spin, barrier) = (meet.find("if (xcl_xn == 0u) return false;").unwrap(), meet.find("#if XCL_X_SPIN").unwrap(), meet.find("GroupMemoryBarrierWithGroupSync();").unwrap()); assert!(leave < spin && spin < barrier); @@ -7836,7 +7836,7 @@ fn split_wave64_lds_reads_meet_after_writes() { } // a compute group of several console waves (the counters' meet) and one of a single half for threads in [128u32, 32] { - let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let h = hlsl(&[write, read], &Options { mode: Mode::Compute(cs), ..split.clone() }); assert!(h.contains(AFTER_WRITE) && h.contains(WROTE), "{threads} threads"); } @@ -8239,7 +8239,7 @@ fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { ]); for dims in [[256u32, 1, 1], [8, 8, 4]] { let threads = dims.iter().product::(); - let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; + let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -8318,7 +8318,7 @@ fn gpu_split_wave64_waves_diverge() { ]); for dims in [[256u32, 1, 1], [64, 1, 1], [8, 8, 4], [16, 4, 1]] { let threads = dims.iter().product::(); - let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3 }; + let cs = CsInterface { threads: dims, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 3, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -8384,7 +8384,7 @@ fn gpu_split_wave64_one_wave_groups_end_early() { ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 4), ("SADDR", 0x7D)], None), ]); for threads in [64u32, 48, 40] { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -8495,7 +8495,7 @@ fn gpu_split_wave64_lds_write_then_read_across_halves() { let base = 0x1000usize; let groups = 64usize; for threads in [64u32, 128, 256] { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 5, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 5, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -8574,7 +8574,7 @@ fn bench_split_wave64() { let mut ms = Vec::new(); let mut exchanges = 0; for wave64 in [false, true] { - let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); let t = translate(&p, &opt).unwrap(); // the loop's exchanges: masks read whole (`x64_masks`: not the v_cndmask @@ -8625,7 +8625,7 @@ fn gpu_compute_tg_size_counts_a_partial_last_wave() { ]); for (threads, wave64) in [(96u32, true), (96, false), (64, true), (40, false), (128, true)] { let lanes = if wave64 { 64 } else { 32 }; - let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: true, tid_components: 1 }; + let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: true, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -8694,7 +8694,7 @@ fn dispatch_loop_budget_shrinks_with_the_groups() { /// the HLSL of every other program (and with it the DXIL cache's key) is as it was. #[test] fn only_compute_programs_with_a_loop_read_the_dispatch_loop_budget() { - let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let compute = Options { mode: Mode::Compute(cs), wave64: false, ..Default::default() }; let looping = translate(&endless_loop_program(), &compute).unwrap(); assert!(looping.complete(), "{:?}", looping.unsupported_why); @@ -8725,7 +8725,7 @@ fn compute_loop_counts_compile() { if super::dxc::location().is_err() { return runner::skip_test("no DXC"); } - let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [8, 4, 2], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; for wave64 in [false, true] { let compute = Options { mode: Mode::Compute(cs.clone()), wave64, ..Default::default() }; for code in [endless_loop_program(), endless_loop_entered_three_times()] { @@ -8749,7 +8749,7 @@ fn gpu_compute_loop_passes_follow_the_dispatch() { } let threads = 64u32; let run = |p: &[u8], wave64: bool, slot: u32| -> u32 { - let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [threads, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1, ..Default::default() }; let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64, ..Default::default() }); let t = translate(p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); @@ -8809,7 +8809,7 @@ fn gpu_compute_folded_dispatch_runs_each_console_group_once() { 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 }; + let cs = super::CsInterface { threads: [1, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; // 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] { @@ -8855,7 +8855,7 @@ fn compute_prologues_leave_the_lanes_past_a_thread_limit_out_of_exec() { (false, false, [64, 1, 1], true), ] { let what = format!("wave64 {wave64}, split {split}, {threads:?}, barrier {with_barrier}"); - let cs = super::CsInterface { threads, user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2 }; + let cs = super::CsInterface { threads, user_sgprs: 2, tgid: [true, true, false], tg_size: false, tid_components: 2, ..Default::default() }; let mut lines = store.to_vec(); if with_barrier { lines.insert(0, ("S_BARRIER", "ENC_SOPP", &[], None)); @@ -8921,7 +8921,7 @@ fn gpu_compute_thread_limits_leave_the_lanes_past_them_out() { forms.push(("direct wave64", true, |l, cs| translate_compute(&code_of(l), KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }, cs).unwrap().dxil)); forms.push(("per-lane wave64", true, |l, cs| super::lower_dxil::compute_code(&code_of(l), cs, true).unwrap())); } - let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 } }; + let cs = |threads: [u32; 3], y: bool| CsInterface { threads, user_sgprs: 2, tgid: [true, y, false], tg_size: false, tid_components: if y { 2 } else { 1 }, ..Default::default() }; let io = |x: u32, y: u32, folded: u32| { let mut io = vec![0u32; 128]; (io[IO_THREAD_LIMIT[0]], io[IO_THREAD_LIMIT[1]], io[IO_GROUP_LIMIT]) = (x, y, folded); @@ -10394,7 +10394,7 @@ fn gpu_safe_s_barrier_multi_warp_and_early_endpgm() { ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 5), ("SADDR", 0x7D)], None), ]); - let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false, false, false], tg_size: false, tid_components: 1 }; + let cs = CsInterface { threads: [128, 1, 1], user_sgprs: 2, tgid: [false, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let base = 0x100usize; let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -10929,7 +10929,7 @@ fn jumps_to_outer_loop_heads_are_structured() { /// backends follow the same predicate. #[test] fn compute_globallycoherent_only_when_needed() { - let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let prog = |insts: &[(&str, &str, &[(&str, u64)])]| { let mut c = Vec::new(); @@ -11009,7 +11009,7 @@ fn gpu_compute_coherent_and_cached_loads() { if !gpu_ready() { return; } - let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); // 1. Plain cached compute: each thread reads a uniform dword via SMEM (s[0:1] = 0x100) and From 93629237296cf81d8b2df746c6e68a16670c7c14 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:32:54 +0100 Subject: [PATCH 088/175] Recompiler: one-wave 2-D compute groups number their threads by lane A native 2-D / 3-D compute group numbers its threads through an LDS arrival counter between two group barriers (the next `lanes` threads of full waves). With one hardware wave the counter's base is always 0, so the thread index is the lane: such a group (the title's 4x8 shadow-mask program, 14,400 groups a dispatch) now skips the counter's store, atomic and barriers, and with the declared LDS also the counter's word. XCL_ONE_WAVE_GROUP_IDS=0 keeps the counter; the caches key the switch. Expected saving is small: in the title program's ISA (RGA, gfx1201) the driver had already dropped the barriers of a one-wave group; the LDS store, atomic and its wait at the entry of each group go. After the lanes.rs part of xcl-dev/xcl#2349 ("split native wave32 compute groups beyond [32, 1, 1]"); its dispatch-split part is not taken. --- crates/xcl/src/gpu/dxil/core_tests.rs | 76 +++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 30 ++++++++++- crates/xcl/src/gpu/dxil/lanes.rs | 5 +- crates/xcl/src/gpu/recomp/pso.rs | 17 ++++++ 4 files changed, 126 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index f9f560dcea..bb66cb4432 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -1624,3 +1624,79 @@ fn gpu_compute_declared_lds_keeps_the_programs_words() { } } } + +/// `f` with `XCL_ONE_WAVE_GROUP_IDS` taken as `on` by the translations of this thread. +fn with_one_wave_ids(on: bool, f: impl FnOnce() -> R) -> R { + let before = super::kernel::ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.replace(Some(on))); + let r = f(); + super::kernel::ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(before)); + r +} + +/// The thread-id program of the one-wave group tests: mem[i] = (gid · 4096) | (y << 8) | x at +/// i = gid · 64 + y · 8 + x. +fn group_ids_program() -> Vec { + const V: u64 = 256; + prog(&[ + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 1)], None), // y · 8 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)], None), // + x + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 134)], None), // gid · 64 + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)], None), // i + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 136), ("VSRC1", 1)], None), // y << 8 + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)], None), // | x + ("S_LSHL_B32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 2), ("SSRC1", 140)], None), // gid << 12 + ("V_OR_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 5), ("VSRC1", 3)], None), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 2)], None), // 4i + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 3), ("SADDR", 0x7D)], None), + ]) +} + +/// `XCL_ONE_WAVE_GROUP_IDS`: a native 2-D group of one hardware wave numbers its threads by +/// lane, with no arrival counter (an LDS atomic) and no group barrier; a group of two waves +/// keeps them. Off: the counter in both. +#[test] +fn a_one_wave_2d_group_numbers_its_threads_without_the_arrival_counter() { + use crate::gpu::recomp::CsInterface; + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + for (threads, one_wave) in [([4u32, 8, 1], true), ([4, 4, 1], true), ([2, 4, 4], true), ([8, 8, 1], false)] { + let cs = CsInterface { threads, user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 3, ..Default::default() }; + for on in [false, true] { + let k = with_one_wave_ids(on, || super::kernel::translate_compute(&group_ids_program(), o, &cs)).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let dis = super::validate::disassemble(&k.dxil).unwrap(); + let counter = !(on && one_wave); + assert_eq!(dis.contains("atomicrmw add"), counter, "{threads:?}, switch {on}: the arrival counter"); + assert_eq!(dis.contains("@dx.op.barrier"), counter, "{threads:?}, switch {on}: the group barriers"); + } + } +} + +/// The thread ids of one-wave 2-D / 3-D groups on the GPU, with `XCL_ONE_WAVE_GROUP_IDS` off and +/// on: every thread of every group stores its own (group, y, x), a full wave and a partial one. +#[test] +fn gpu_one_wave_2d_groups_number_their_threads_by_lane() { + use crate::gpu::recomp::{runner, CsInterface, KERNEL_SGPRS}; + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + for threads in [[4u32, 8, 1], [4, 4, 1]] { + let cs = CsInterface { threads, user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2, ..Default::default() }; + let groups = 8u32; + let mut want = vec![0xFFFF_FFFFu32; 64 * groups as usize]; + for g in 0..groups { + for y in 0..threads[1] { + for x in 0..threads[0] { + want[(g * 64 + y * 8 + x) as usize] = g << 12 | y << 8 | x; + } + } + } + for on in [false, true] { + let k = with_one_wave_ids(on, || super::kernel::translate_compute(&group_ids_program(), o, &cs)).unwrap_or_else(|e| panic!("{threads:?}: {e}")); + let mem = runner::dispatch(&k.dxil, [groups, 1, 1], &vec![0u32; KERNEL_SGPRS], &vec![0xFFFF_FFFFu32; want.len()]).expect("GPU run"); + assert_eq!(&mem[..want.len()], &want[..], "{threads:?}, switch {on}"); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 92e18bf458..85bea86f31 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -61,6 +61,26 @@ thread_local! { pub(crate) static DECLARED_LDS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +/// `XCL_ONE_WAVE_GROUP_IDS` (default on; `=0` off): a native 2-D / 3-D compute group of one +/// hardware wave takes its thread indices from the lanes, without the arrival counter, its +/// atomic and the two group barriers around it (`Lw::setup_lanes_compute`: with one wave the +/// counter's base is always 0). The caches key it apart. (After xcl-dev/xcl#2349, "split native +/// wave32 compute groups beyond [32, 1, 1]", its lanes.rs part.) +pub fn one_wave_group_ids() -> bool { + #[cfg(test)] + if let Some(on) = ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_ONE_WAVE_GROUP_IDS").map_or(true, |v| v.trim() != "0")) +} + +#[cfg(test)] +thread_local! { + /// `one_wave_group_ids` for the translations of this test thread + pub(crate) static ONE_WAVE_GROUP_IDS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// Console compute shaders (and the kernel tests) go through this translator, with the HLSL /// path as the fallback for what it cannot translate yet: the default, and `XCL_DIRECT_DXIL=1`. /// `XCL_DIRECT_DXIL=0` keeps every stage on the HLSL path. @@ -282,12 +302,16 @@ fn translate_entry_with( let code = code.to_vec(); #[cfg(test)] let declared_lds = DECLARED_LDS_FOR_TEST.with(|c| c.get()); + #[cfg(test)] + let one_wave = ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.get()); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) .spawn(move || { #[cfg(test)] DECLARED_LDS_FOR_TEST.with(|c| c.set(declared_lds)); + #[cfg(test)] + ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(one_wave)); translate_on_this_thread(&code, o, entry, compact, nest, rodata) }) .map_err(|e| format!("translator thread: {e}"))? @@ -840,7 +864,11 @@ impl Lw { // `XCL_DECLARED_LDS`: the program's own LDS, then the translator's words; a native 2-D // / 3-D group's arrival counter (`setup_lanes_compute`) is one of them let (declared, native_counter) = match entry { - Entry::Compute(cs) if declared_lds_enabled() => (cs.lds_dwords, !split && (cs.threads[1] > 1 || cs.threads[2] > 1)), + Entry::Compute(cs) if declared_lds_enabled() => { + let lanes = if o.wave64 { 64 } else { 32 }; + let one_wave = one_wave_group_ids() && cs.threads.iter().product::() <= lanes; + (cs.lds_dwords, !split && (cs.threads[1] > 1 || cs.threads[2] > 1) && !one_wave) + } _ => (0, false), }; lw.setup_storage(uses_lds, if split { slot } else { 1 }, safe_bar, declared, native_counter); diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index c5680de86f..51956911da 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -145,7 +145,7 @@ impl Lw { let t = self.s.m.i1c(true); let rank = self.s.wave_prefix_bit_count(t); self.add(base, rank) - } else if y * z > 1 { + } else if y * z > 1 && !(total <= lanes && super::kernel::one_wave_group_ids()) { let i32 = self.s.m.i32(); let (g, at) = match (self.lds, lds_top_word) { (Some(l), true) => self.xw.unwrap_or((l, 8191)), @@ -169,6 +169,9 @@ impl Lw { let tid = self.add(base, hw); self.s.barrier(barrier::GROUP_SYNC); tid + } else if y * z > 1 { + // one native wave (`XCL_ONE_WAVE_GROUP_IDS`): the counter's base would be 0 + self.s.wave_lane_index() } else { self.s.flattened_thread_id_in_group() }; diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 108272f5ac..dbb45f0073 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -311,6 +311,10 @@ mod translated { let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; + // `XCL_ONE_WAVE_GROUP_IDS` (on): one-wave 2-D / 3-D groups' entries are another output + let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::one_wave_group_ids() { + identity_for(&id.to_string(), "xcl-one-wave-group-ids") + } else { id }; // `XCL_NAN_GUARD=0`: disabling PS float NaN/Inf sanitization changes pixel DXIL let id = if Backend::current() != Backend::Hlsl && !crate::gpu::dxil::kernel::nan_guard_enabled() { identity_for(&id.to_string(), "xcl-nan-guard-0") @@ -561,6 +565,7 @@ mod translated { None => id, }; let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; + let id = if crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); if crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) @@ -1597,6 +1602,18 @@ mod shader_cache_tests { assert_eq!(with(true), with(true)); } + /// `XCL_ONE_WAVE_GROUP_IDS` translations are other entries of the direct translator's caches. + #[test] + fn one_wave_group_ids_are_another_direct_output() { + let with = |on| { + let before = crate::gpu::dxil::kernel::ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.replace(Some(on))); + let id = translated::direct_output_identity(None, 1); + crate::gpu::dxil::kernel::ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(before)); + id + }; + assert_ne!(with(false), with(true)); + } + /// The switch form (no heap windows, or a pipeline retried in it) has 4 root UAVs: a wider /// count there is 4, which every translator takes; the heap form keeps all of them. #[test] From 2d53b4c1f49f5fdadc725052832241011dd381fc Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:35:34 +0100 Subject: [PATCH 089/175] Recompiler: XCL_COHERENT_PER_ACCESS=1 keeps plain heap-window loads cached A compute program with one atomic or one GLC / DLC / SLC access takes all its memory windows globallycoherent (needs_coherent_mem), so every load of it bypasses the L0 cache. The title's shadow-mask program (cs d9fac2f1d8f646fd) has three buffer_atomic_add glc; all 199 of its buffer loads in the driver's ISA (RGA, gfx1201) were scope:SCOPE_DEV, among them the per-light constant data its light loop reads with s_buffer_load, the same address in every lane. With XCL_COHERENT_PER_ACCESS=1 and heap windows (XCL_HEAP_WINDOWS=1: a handle per access), a program that needs coherent memory and invalidates no cache takes its windows coherent only for its stores, atomics and the loads that ask for it (recomp::coherent_access); its plain loads may be cached, as the console's are. Measured offline: the title program's coherent loads go from 199 to 0, nothing else in its ISA changes. The root-UAV window form is unchanged (it would need coherent alias views). Off by default; the caches key the switch. After xcl-dev/xcl#2067 (a03bc75e, "emit per-instruction globallycoherent on compute flat memory"), its direct-DXIL heap-window part. --- crates/xcl/src/gpu/dxil/core_tests.rs | 41 +++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 29 +++++++++++++++++++ crates/xcl/src/gpu/dxil/lower.rs | 5 ++++ crates/xcl/src/gpu/dxil/lower_mem.rs | 22 ++++++++++---- crates/xcl/src/gpu/recomp/mod.rs | 18 ++++++++++++ crates/xcl/src/gpu/recomp/pso.rs | 5 ++++ 6 files changed, 114 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index bb66cb4432..ae2577829d 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -1700,3 +1700,44 @@ fn gpu_one_wave_2d_groups_number_their_threads_by_lane() { } } } + +/// `XCL_COHERENT_PER_ACCESS=1` on heap memory windows: in a compute program with an atomic, its +/// plain loads (`s_load`, `global_load` without GLC) take non-coherent windows, its GLC load, the +/// atomic and the store coherent ones; without the switch, or in a program that invalidates a +/// cache, every window access is coherent; a program with neither has none. +#[test] +fn heap_windows_are_coherent_per_access_with_the_switch() { + use crate::gpu::recomp::{CsInterface, HEAP_FLAT, HEAP_WINDOWS}; + let body: &[(&str, &str, &[(&str, u64)], Option)] = &[ + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 2), ("SADDR", 0x7D)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 4), ("ADDR", 2), ("SADDR", 0x7D), ("GLC", 1)], None), + ("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 2), ("DATA", 6), ("SADDR", 0x7D), ("GLC", 1)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 0x7D)], None), + ]; + let atomic = prog(body); + let mut with_inv = body.to_vec(); + with_inv.push(("BUFFER_GL0_INV", "ENC_MUBUF", &[], None)); + let invalidating = prog(&with_inv); + let plain = prog(&body[..2]); + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; + let o = KernelOptions { wave64: false, split: false, mem_windows: 4 | HEAP_WINDOWS | HEAP_FLAT, sampler_base: 0 }; + // (heap window handles: RAW_BUFFER | IsUAV, and | IsGloballyCoherent) + let windows = |code: &[u8], on: bool| { + let before = super::kernel::COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.replace(Some(on))); + let k = super::kernel::translate_compute(code, o, &cs); + super::kernel::COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.set(before)); + let dis = super::validate::disassemble(&k.unwrap().dxil).unwrap(); + let heap: Vec<&str> = dis.lines().filter(|l| l.contains("@dx.op.annotateHandle") && l.contains("RWByteAddressBuffer")).collect(); + let coherent = heap.iter().filter(|l| l.contains("i32 20491,")).count(); + // (io at u0 is a plain one: not counted) + (heap.len() - coherent - 1, coherent) + }; + let (plain_on, coherent_on) = windows(&atomic, true); + assert!(plain_on >= 2 && coherent_on >= 3, "switch on: {plain_on} plain, {coherent_on} coherent"); + assert_eq!(windows(&atomic, false).0, 0, "switch off: every window access coherent"); + assert_eq!(windows(&invalidating, true).0, 0, "a cache invalidation keeps every access coherent"); + for on in [false, true] { + assert_eq!(windows(&plain, on).1, 0, "no atomic, no GLC: no coherent window (switch {on})"); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 85bea86f31..7587ac368b 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -61,6 +61,28 @@ thread_local! { pub(crate) static DECLARED_LDS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; } +/// `XCL_COHERENT_PER_ACCESS=1`: in a compute program that needs coherent memory (an atomic or a +/// `GLC` / `DLC` / `SLC` access, `recomp::needs_coherent_mem`) and invalidates no cache, only its +/// stores, atomics and coherent loads take its heap memory windows `globallycoherent`; its plain +/// loads, as the console's, may be cached (L0) - before, one atomic made every load of the +/// program bypass the cache. Heap windows only (`XCL_HEAP_WINDOWS=1`: a handle per access); off +/// by default; the caches key it apart. (After xcl-dev/xcl#2067, "Recompiler: emit +/// per-instruction globallycoherent on compute flat memory".) +pub fn coherent_per_access() -> bool { + #[cfg(test)] + if let Some(on) = COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_COHERENT_PER_ACCESS").is_ok_and(|v| v.trim() == "1")) +} + +#[cfg(test)] +thread_local! { + /// `coherent_per_access` for the translations of this test thread + pub(crate) static COHERENT_PER_ACCESS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// `XCL_ONE_WAVE_GROUP_IDS` (default on; `=0` off): a native 2-D / 3-D compute group of one /// hardware wave takes its thread indices from the lanes, without the arrival counter, its /// atomic and the two group barriers around it (`Lw::setup_lanes_compute`: with one wave the @@ -303,6 +325,8 @@ fn translate_entry_with( #[cfg(test)] let declared_lds = DECLARED_LDS_FOR_TEST.with(|c| c.get()); #[cfg(test)] + let per_access = COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.get()); + #[cfg(test)] let one_wave = ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.get()); std::thread::Builder::new() .name("xcl-dxil-translate".into()) @@ -311,6 +335,8 @@ fn translate_entry_with( #[cfg(test)] DECLARED_LDS_FOR_TEST.with(|c| c.set(declared_lds)); #[cfg(test)] + COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.set(per_access)); + #[cfg(test)] ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(one_wave)); translate_on_this_thread(&code, o, entry, compact, nest, rodata) }) @@ -715,6 +741,7 @@ impl Lw { } let coherent = cs.is_some() && crate::gpu::recomp::needs_coherent_mem(insts); let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, coherent); + let per_access = heap_mem == Some(true) && coherent_per_access() && !crate::gpu::recomp::invalidates_caches(insts); let i32 = s.m.i32(); let z = s.m.i32c(0); let mut lw = Lw { @@ -729,6 +756,8 @@ impl Lw { half: z, mems, heap_mem, + per_access, + coherent_inst: true, heap_flat: heap_mem.is_some() && o.mem_windows & crate::gpu::recomp::HEAP_FLAT != 0, res, fmt_table: None, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index b32e10c6c1..0dd2a1dd76 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -208,6 +208,10 @@ pub struct Lw { pub heap_mem: Option, /// heap windows read without a branch (`recomp::HEAP_FLAT`) pub heap_flat: bool, + /// coherent heap windows for the stores, atomics and coherent loads alone + /// (`kernel::coherent_per_access`); `coherent_inst`: the instruction being lowered is one + pub per_access: bool, + pub coherent_inst: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, @@ -1009,6 +1013,7 @@ impl Lw { let name = d.inst.name.to_ascii_lowercase(); self.pc = d.pc; self.dpp_enable = None; + self.coherent_inst = !self.per_access || crate::gpu::recomp::coherent_access(d); if name == "s_sendmsg" && self.mesh.is_some() { return self.mesh_sendmsg(d); } diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index f874dc8fa3..d2c5aa46c1 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -161,6 +161,7 @@ impl Lw { &mut self, mut guard: Option, out_tys: &[super::module::Ty], + read: bool, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { if let Some(c) = guard { @@ -172,7 +173,8 @@ impl Lw { } // Descriptor-heap windows (`#1693`, `XCL_HEAP_WINDOWS=1`): single guarded heap lookup // combined with `guard`, stacking cleanly with vector loads/stores & FormatLoad opt. - if let Some(coherent) = self.heap_mem { + if self.heap_mem.is_some() { + let coherent = self.heap_coherent(read); let windows = self.mems.len() as u32; let w = self.rd(super::lower::VAR_WIN); let inside = self.cmpc(Pred::ULt, w, windows); @@ -411,7 +413,8 @@ impl Lw { n: usize, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { - if let (Some(coherent), true) = (self.heap_mem, self.heap_flat) { + if let (Some(_), true) = (self.heap_mem, self.heap_flat) { + let coherent = self.heap_coherent(true); let z = self.c(0); if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) { return vec![z; n]; @@ -431,7 +434,14 @@ impl Lw { } let i32 = self.s.m.i32(); let tys = vec![i32; n]; - self.with_mem_many_tys(guard, &tys, f) + self.with_mem_many_tys(guard, &tys, true, f) + } + + /// Whether this access takes its heap window `globallycoherent`: every access of a program + /// that needs coherent memory, or with `per_access` its stores and atomics (`read` false) + /// and the loads of the instructions that ask for it (`coherent_inst`). + fn heap_coherent(&self, read: bool) -> bool { + self.heap_mem == Some(true) && (!read || self.coherent_inst) } pub(crate) fn with_mem_void( @@ -439,18 +449,18 @@ impl Lw { guard: Option, f: &mut dyn FnMut(&mut Lw, RawUav), ) { - let _ = self.with_mem_many_tys(guard, &[], &mut |lw, m| { + let _ = self.with_mem_many_tys(guard, &[], false, &mut |lw, m| { f(lw, m); Vec::new() }); } fn mraw_atomic(&mut self, op: AtomicOp, a: Value, v: Value) -> Value { let ty = self.s.m.type_of(v); - self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_atomic(m, op, a, v)])[0] + self.with_mem_many_tys(None, &[ty], false, &mut |lw, m| vec![lw.s.raw_atomic(m, op, a, v)])[0] } fn mraw_cmpxchg(&mut self, a: Value, c: Value, n: Value) -> Value { let ty = self.s.m.type_of(c); - self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_cmpxchg(m, a, c, n)])[0] + self.with_mem_many_tys(None, &[ty], false, &mut |lw, m| vec![lw.s.raw_cmpxchg(m, a, c, n)])[0] } /// `mem.Load(a & ~3)` pub fn mem_ld(&mut self, a: Value) -> Value { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index b2dad4c544..a83c57abcd 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1805,6 +1805,24 @@ pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { }) } +/// Whether a memory access of the console's asks for coherent memory: an atomic, or `GLC` / +/// `DLC` / `SLC` set (`needs_coherent_mem`'s test of one instruction). +pub(crate) fn coherent_access(d: &Decoded) -> bool { + let name = d.inst.name; + name.starts_with("BUFFER_ATOMIC_") + || name.starts_with("GLOBAL_ATOMIC_") + || name.starts_with("FLAT_ATOMIC_") + || name.starts_with("S_ATOMIC_") + || matches!(d.enc.name, "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL") + && ["GLC", "DLC", "SLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)) +} + +/// Whether the program invalidates a cache (after which its plain loads see other groups' +/// writes, which D3D12 has no instruction for on memory that is not `globallycoherent`). +pub(crate) fn invalidates_caches(insts: &[Decoded]) -> bool { + insts.iter().any(|d| matches!(d.inst.name, "S_DCACHE_INV" | "S_GL1_INV" | "BUFFER_GL0_INV" | "BUFFER_GL1_INV")) +} + pub fn translate(code: &[u8], opt: &Options) -> Result { let program = code; let normalized; diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index dbb45f0073..d4d943a510 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -311,6 +311,10 @@ mod translated { let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; + // `XCL_COHERENT_PER_ACCESS=1`: coherent heap windows per access are another output + let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::coherent_per_access() { + identity_for(&id.to_string(), "xcl-coherent-per-access") + } else { id }; // `XCL_ONE_WAVE_GROUP_IDS` (on): one-wave 2-D / 3-D groups' entries are another output let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") @@ -565,6 +569,7 @@ mod translated { None => id, }; let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; + let id = if crate::gpu::dxil::kernel::coherent_per_access() { identity_for(&id.to_string(), "xcl-coherent-per-access") } else { id }; let id = if crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); if crate::gpu::recomp::lower_dxil::enabled() { From bb570dd947f6452663a4ec913ff6b2a82988c0af Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:52:30 +0100 Subject: [PATCH 090/175] Recompiler: fold unobserved EXEC selects in direct DXIL Guest VGPR writes preserve inactive lanes as select(exec, new, old). Lane-local operations whose values are ultimately observed only under the same condition cannot observe the preserved arm, so read through it and let DCE remove the resulting dead selects. A conservative observation lattice: phis, memory, atomics, integer division, wave / quad operations, derivatives and unknown calls observe all lanes. XCL_DXIL_NO_OPT=select skips the pass. Measured offline on the title's shadow-mask program (cs d9fac2f1d8f646fd, RGA gfx1201, the run's heap windows): DXIL 162,708 -> 140,072 B, the driver's ISA 63,011 -> 58,333 instructions, scratch 18,480 -> 17,424 B a lane. On the GPU (RX 9070 XT, the program patched past its early exits, 1,600 groups, 32 lights) its compact form takes 4.0 instead of 4.6 ms. Port of upstream 15aa7f36 (xcl-dev/xcl, bmjask, "fold unobserved EXEC selects in direct DXIL") onto this tree's multi-pass optimize(): the pass runs before DCE in each iteration, and instructions made after the replacement table was sized count as live. Its GPU parity test (select_tests.rs) is taken as it is. --- crates/xcl/src/gpu/dxil/kernel.rs | 4 + crates/xcl/src/gpu/dxil/mod.rs | 2 + crates/xcl/src/gpu/dxil/module.rs | 2 + crates/xcl/src/gpu/dxil/module/opt.rs | 126 +++++++++++++++++++++++- crates/xcl/src/gpu/dxil/select_tests.rs | 95 ++++++++++++++++++ 5 files changed, 228 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/gpu/dxil/select_tests.rs diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 7587ac368b..d5b4064dac 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -325,6 +325,8 @@ fn translate_entry_with( #[cfg(test)] let declared_lds = DECLARED_LDS_FOR_TEST.with(|c| c.get()); #[cfg(test)] + let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); + #[cfg(test)] let per_access = COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.get()); #[cfg(test)] let one_wave = ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.get()); @@ -335,6 +337,8 @@ fn translate_entry_with( #[cfg(test)] DECLARED_LDS_FOR_TEST.with(|c| c.set(declared_lds)); #[cfg(test)] + super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); + #[cfg(test)] COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.set(per_access)); #[cfg(test)] ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(one_wave)); diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index a0ec94583f..9540026ed1 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -57,3 +57,5 @@ mod msaa_tests; mod round_tests; #[cfg(test)] mod geometry_tests; +#[cfg(test)] +mod select_tests; diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 9145a21d7e..2ca2350f8d 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -16,6 +16,8 @@ use std::collections::HashMap; use super::bitstream::{signed, AbbrevOp, BitWriter}; mod opt; +#[cfg(test)] +pub(crate) use opt::NO_SELECT_FOLD; pub(super) mod split; // ---------------------------------------------------------------- types diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 1a4155fb7f..47a194e08c 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -68,6 +68,12 @@ impl Op { } } +#[cfg(test)] +thread_local! { + /// Tests can compare emitted code with the guarded-select fold disabled. + pub(crate) static NO_SELECT_FOLD: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + /// How an instruction may be merged with an identical one. #[derive(PartialEq)] enum Cse { @@ -977,7 +983,7 @@ impl Module { /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,cse,cfg,dce,merge,alloca,facts,hoist,barrier` (any subset, or `all`) + /// `XCL_DXIL_NO_OPT=phi,cse,cfg,select,dce,merge,alloca,facts,hoist,barrier` (any subset, or `all`) /// skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); @@ -1253,6 +1259,14 @@ impl Module { iter_changed = true; } + #[cfg(test)] + let skip_select = NO_SELECT_FOLD.with(|c| c.get()); + #[cfg(not(test))] + let skip_select = false; + if !skip("select") && !skip_select { + self.fold_guarded_selects(&order, &repl); + } + // dead instructions: live = side effects, terminators and their operands, transitively let (i64t, f64t) = self.existing_i64_f64(); let wide: Vec = i64t.into_iter().chain(f64t).collect(); @@ -1297,6 +1311,116 @@ impl Module { } } + /// Whether `op` computes each lane from only that lane's operands. Operations whose + /// evaluation observes other lanes, memory, or undefined integer division operands are + /// deliberately excluded. + fn lane_local(&self, op: &Op, ty: Ty) -> bool { + match op { + Op::Bin(BinOp::UDiv | BinOp::URem, ..) => false, + Op::Bin(BinOp::SDiv | BinOp::SRem, ..) => self.is_float(ty), + Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) => true, + Op::Call(f, args) => { + let d = &self.funcs[*f as usize]; + d.attrs == FnAttrs::ReadNone + && d.name.starts_with("dx.op.") + && args.first().and_then(|&a| self.const_u64(a)).is_some_and(|id| matches!(id, 6..=56 | 101 | 102 | 124..=132)) + } + _ => false, + } + } + + /// Reads through `select(c, current, old)` only where the value is ultimately observed + /// under the same `c`. This removes guest-EXEC preservation arms from chains of lane-local + /// operations without changing inactive lanes. Phis and non-lane-local operations observe + /// all lanes and stop the fold. + fn fold_guarded_selects(&mut self, order: &[u32], repl: &[Option]) { + #[derive(Clone, Copy, PartialEq)] + enum Seen { + Unused, + Where(Value), + All, + } + fn meet(s: &mut Seen, by: Seen) { + *s = match (*s, by) { + (x, Seen::Unused) => x, + (Seen::Unused, y) => y, + (Seen::Where(a), Seen::Where(b)) if a == b => Seen::Where(a), + _ => Seen::All, + } + } + + // (instructions made after `repl` was sized have no replacement) + let live = |i: u32| repl.get(i as usize).is_none_or(|r| r.is_none()); + let mut seen = vec![Seen::Unused; self.insts.len()]; + for &b in order { + for &i in &self.blocks[b as usize] { + if let (true, Op::Phi(inc)) = (live(i), &self.insts[i as usize].op) { + for &(v, _) in inc { + if let Value::Inst(j) = v { + seen[j as usize] = Seen::All; + } + } + } + } + } + for &b in order.iter().rev() { + for &i in self.blocks[b as usize].iter().rev() { + if !live(i) { + continue; + } + let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty); + if matches!(op, Op::Phi(_)) { + continue; + } + let me = if self.lane_local(op, ty) { seen[i as usize] } else { Seen::All }; + if me == Seen::Unused { + continue; + } + let mut by = |v: Value, s: Seen| { + if let Value::Inst(j) = v { + meet(&mut seen[j as usize], s); + } + }; + match *op { + Op::Select(c, a, b) => { + by(c, me); + by(a, Seen::Where(c)); + by(b, me); + } + _ => op.for_each_operand(|v| by(v, me)), + } + } + } + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k]; + let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty); + if !live(i) || seen[i as usize] == Seen::Unused || !self.lane_local(op, ty) { + continue; + } + let me = seen[i as usize]; + let outer_condition = if let Op::Select(c, ..) = *op { Some(c) } else { None }; + let mut op = op.clone(); + let mut pos = 0; + op.map_operands(|mut v| { + let at = pos; + pos += 1; + while let Value::Inst(j) = v { + let Op::Select(c, t, f) = self.insts[j as usize].op else { break }; + v = match (outer_condition, at) { + (Some(outer), 1) if outer == c => t, + (Some(outer), 2) if outer == c => f, + _ if me == Seen::Where(c) => t, + _ => break, + }; + } + v + }); + self.insts[i as usize].op = op; + } + } + } + /// Simplifies the CFG to a fixed point: /// 1. Collapses degenerate `CondBr(_, t, t)` and `Switch` cases matching the default target. /// 2. Bypasses empty trampoline blocks (`[Br(t)]`) whenever `t`'s phis allow it. diff --git a/crates/xcl/src/gpu/dxil/select_tests.rs b/crates/xcl/src/gpu/dxil/select_tests.rs new file mode 100644 index 0000000000..2d9c1d3663 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/select_tests.rs @@ -0,0 +1,95 @@ +//! GPU equivalence for the guarded-select fold, including inactive lanes. + +use super::kernel::{translate, KernelOptions}; +use super::module::NO_SELECT_FOLD; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::runner::{self, KernelState}; + +const V: u64 = 256; + +fn program(list: &[(&str, &str, &[(&str, u64)])]) -> Vec { + let mut code = Vec::new(); + for (name, encoding, fields) in list { + code.extend(encode(name, encoding, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code +} + +fn translate_with_fold(code: &[u8], options: KernelOptions, enabled: bool) -> Vec { + NO_SELECT_FOLD.with(|c| c.set(!enabled)); + let result = translate(code, options); + NO_SELECT_FOLD.with(|c| c.set(false)); + result.unwrap_or_else(|e| panic!("translate (select fold {enabled}): {e}")) +} + +#[test] +fn gpu_guarded_select_fold_preserves_inactive_lanes() { + match (runner::adapter(), runner::wave64_programs_supported()) { + (Ok(_), Ok(true)) => {} + (adapter, _) => return runner::skip_test(if adapter.is_err() { "no GPU" } else { "no wave64" }), + } + let code = program(&[ + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 0)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 2)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 4), ("SRC1", V + 3), ("SRC2", V + 4)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 4)]), + ("V_CMP_GT_F32", "ENC_VOPC", &[("SRC0", V + 4), ("VSRC1", 5)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 4), ("VSRC1", 5)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 131)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 6), ("SRC1", 137)]), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 6)]), + ("V_MAX_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 4)]), + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 9), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 4), ("SRC1", 133)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 6), ("VSRC1", 6)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 4), ("VSRC1", 6)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 7), ("VSRC1", 8)]), + ]); + const EDGE: [u32; 12] = [0x7FC0_1234, 0, 0x8000_0000, 0x7F80_0000, 0xFF80_0000, 1, 0x807F_FFFF, 0x3FC0_0000, 0xC000_0000, 0x3F80_0000, 0x4120_0000, 0xBE80_0000]; + let mut state = KernelState::default(); + let mut random = 0x9E37_79B9_7F4A_7C15u64; + for (lane, regs) in state.vgpr.iter_mut().enumerate() { + for word in regs.iter_mut().take(4) { + random ^= random << 13; + random ^= random >> 7; + random ^= random << 17; + *word = if random % 3 == 0 { random as u32 } else { EDGE[(random >> 8) as usize % EDGE.len()] }; + } + for (reg, word) in regs.iter_mut().enumerate().skip(4).take(8) { + *word = 0xA000_0000 | (lane as u32) << 8 | reg as u32; + } + } + (state.sgpr[0], state.sgpr[1]) = (0xF0F0_5A3C, 0x0FF0_C3A5); + (state.sgpr[2], state.sgpr[3]) = (0x3333_FF0F, 0xFFFF_3333); + + let mut ran = 0; + for (wave64, split) in [(false, false), (true, true), (true, false)] { + if wave64 && !split && runner::wave64_supported() != Ok(true) { + continue; + } + let options = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let (before, after) = (translate_with_fold(&code, options, false), translate_with_fold(&code, options, true)); + assert!(after.len() < before.len(), "wave64 {wave64} split {split}: nothing folded ({} -> {} B)", before.len(), after.len()); + let a = runner::run(&before, &state, &[]).expect("GPU run before fold"); + let b = runner::run(&after, &state, &[]).expect("GPU run after fold"); + let lanes = if wave64 { 64 } else { 32 }; + for lane in 0..lanes { + assert_eq!(a.vgpr[lane][..12], b.vgpr[lane][..12], "wave64 {wave64} split {split}: lane {lane}"); + let active = (state.sgpr[lane / 32] >> (lane % 32)) & 1 != 0; + if !active { + for reg in [4, 5, 7, 8] { + assert_eq!(b.vgpr[lane][reg], state.vgpr[lane][reg], "wave64 {wave64} split {split}: inactive lane {lane} v{reg}"); + } + } + } + assert_eq!(a.sgpr, b.sgpr, "wave64 {wave64} split {split}: SGPRs"); + assert_eq!(a.scc, b.scc, "wave64 {wave64} split {split}: SCC"); + ran += 1; + } + assert!(ran >= 2); +} From 41dc012eab08e139095f67825fd79d73cc0cc4f5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:53:23 +0100 Subject: [PATCH 091/175] Recompiler: XCL_DIRECT_COMPACT_MIN= takes big compute programs compact The direct translator picks the compact form (each distinct block lowered once, run from a table) only for size: from 10,000 instructions or 2,000 blocks, and only when most of the program repeats. Below that a big program gets the plain form, whose register allocation in the driver can be the program's cost. The title's shadow-mask program (cs d9fac2f1d8f646fd, ~6,000 instructions, a light loop around nearly all of it; 20-139 ms a frame in the open world) compiles on RDNA4 (RGA, amdxc64 gfx1201, the run's heap windows) to 256 VGPRs and 18 KB of scratch a lane, ~18,000 scratch loads and stores; its compact form to 215 VGPRs, 75 SGPRs and no scratch, 32,146 instead of 58,333 instructions. XCL_DIRECT_COMPACT_MIN=: a compute program of at least n reachable instructions takes the compact form whenever its table fits, however little of it repeats (compact::sized_plan); otherwise the automatic choice as before. Unset by default; the caches key the value. Measured on the GPU (RX 9070 XT, Adrenalin as installed, RDNA4 wave32; the program patched past its early exits with a light mask of all ones, zero memory, 40x40 groups of 4x8, one 32-light word; ms a dispatch): plain 95.6 (8,192-dword LDS) / 80.0 (declared LDS), compact 24.7 / 4.0. --- crates/xcl/src/gpu/dxil/compact.rs | 38 +++++++++++- crates/xcl/src/gpu/dxil/compact_tests.rs | 77 ++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 17 +++++- crates/xcl/src/gpu/recomp/pso.rs | 22 +++++++ 4 files changed, 151 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 2f4f426bf2..0a5a7faff6 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -267,6 +267,41 @@ pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { repeated.then_some(p) } +/// `XCL_DIRECT_COMPACT_MIN=` (unset: off): a compute program of at least that +/// many reachable non-terminator instructions takes the compact form whenever it has one whose +/// table fits (`sized_plan`), however little of it repeats. The automatic choice is about size; +/// this one is about speed: on a big program the driver's register allocation of the plain +/// form can spill most of the program's values (a retail title's 6,000-instruction shadow-mask +/// program: 256 VGPRs and 18 KB of scratch a lane on RDNA4), and the compact form's blocks, +/// each lowered on its own, need none. +pub fn compact_min() -> Option { + #[cfg(test)] + if let Some(v) = COMPACT_MIN_FOR_TEST.with(|c| c.get()) { + return v; + } + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_DIRECT_COMPACT_MIN").ok().and_then(|v| v.trim().parse::().ok()).filter(|&n| n > 0)) +} + +#[cfg(test)] +thread_local! { + /// `compact_min` for the translations of this test thread + pub(crate) static COMPACT_MIN_FOR_TEST: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} + +/// The compact form of a program of at least `min` reachable instructions whose table fits +/// (`compact_min`). +pub fn sized_plan(cfg: &Cfg, lw: &Lw, min: usize) -> Option { + if insts(cfg) < min { + return None; + } + plan(cfg, lw).filter(|p| p.words() <= MAX_TABLE_WORDS) +} + +fn insts(cfg: &Cfg) -> usize { + cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum() +} + /// Reachable non-terminator instruction count threshold for trying the compact form. const LARGE_INSTS: usize = 10_000; /// Reachable basic-block count threshold for trying the compact form: branch-heavy @@ -277,8 +312,7 @@ const LARGE_BLOCKS: usize = 2_000; /// Whether to consider compaction based on the reachable instruction and block counts. pub fn large(cfg: &Cfg) -> bool { - cfg.rpo.len() >= LARGE_BLOCKS - || cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= LARGE_INSTS + cfg.rpo.len() >= LARGE_BLOCKS || insts(cfg) >= LARGE_INSTS } pub const END: u32 = u32::MAX; diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index ea9a52a654..5b12a47c09 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -425,3 +425,80 @@ fn gpu_nested_compact_matches_plain_and_flat() { .expect("nested budget GPU run"); assert_eq!((got3.sgpr, got3.vgpr, got3.scc), (plain3.sgpr, plain3.vgpr, plain3.scc), "nested loop budget"); } + +/// `f` with `XCL_DIRECT_COMPACT_MIN` taken as `min` by the translations of this thread. +fn with_compact_min(min: Option, f: impl FnOnce() -> R) -> R { + let before = super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.replace(Some(min))); + let r = f(); + super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.set(before)); + r +} + +/// `XCL_DIRECT_COMPACT_MIN`: a compute program of at least that many instructions takes the +/// compact form, below the automatic choice's size; a smaller one, or a kernel, keeps the plain +/// form. +#[test] +fn a_compute_program_from_the_compact_size_takes_the_compact_form() { + if compact_mode().is_some() { + return; + } + use crate::gpu::recomp::CsInterface; + let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1, ..Default::default() }; + let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + // 100 copies: 900 instructions, below the automatic thresholds + let code = repeated(100); + let compute = |min| with_compact_min(min, || super::kernel::translate_compute(&code, o, &cs)).unwrap().dxil.len(); + let plain = compute(None); + assert!(compute(Some(500)) * 3 < plain, "compact {} B, plain {plain} B", compute(Some(500))); + assert_eq!(compute(Some(5000)), plain, "below the size"); + let kernel = |min| with_compact_min(min, || translate_full(&code, o)).unwrap().dxil; + assert_eq!(kernel(Some(500)), kernel(None), "a kernel keeps its form"); +} + +/// A compute program in the compact form `XCL_DIRECT_COMPACT_MIN` gives it runs as in the plain +/// one: every thread of a 2-D wave32 group stores its own (group, y, x). +#[test] +fn gpu_compute_compact_form_from_the_size_runs_as_the_plain_form() { + use crate::gpu::recomp::{CsInterface, KERNEL_SGPRS}; + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + const V: u64 = 256; + let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut code = Vec::new(); + code.extend(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 131), ("VSRC1", 1)])); // y · 8 + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", V), ("VSRC1", 2)])); // + x + code.extend(i("S_LSHL_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 134)])); // gid · 64 + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 2)])); // i + // v3 = x · (y + 1): a loop of y + 1 passes, each lane leaving EXEC after its own + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)])); + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 1)])); + code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", V), ("VSRC1", 3)])); // loop: v3 += x + code.extend(i("V_SUBREV_NC_U32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 129), ("VSRC1", 5)])); // v5 -= 1 + code.extend(i("V_CMP_GT_I32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 5)])); // vcc = 0 > v5 + code.extend(i("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)])); // exec &= !vcc + code.extend(i("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)])); + code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])); // exec = all + code.extend(i("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 2)])); // 4i + code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)])); + code.extend(i("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 3), ("SADDR", 0x7D)])); + code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); + let cs = CsInterface { threads: [8, 4, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2, ..Default::default() }; + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let groups = 4u32; + let mut want = vec![0xFFFF_FFFFu32; 64 * groups as usize]; + for g in 0..groups { + for y in 0..4 { + for x in 0..8 { + want[(g * 64 + y * 8 + x) as usize] = x * (y + 1); + } + } + } + for min in [None, Some(1)] { + let k = with_compact_min(min, || super::kernel::translate_compute(&code, o, &cs)).unwrap_or_else(|e| panic!("{min:?}: {e}")); + let mem = runner::dispatch(&k.dxil, [groups, 1, 1], &vec![0u32; KERNEL_SGPRS], &vec![0xFFFF_FFFFu32; want.len()]).expect("GPU run"); + assert_eq!(&mem[..want.len()], &want[..], "compact size {min:?}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index d5b4064dac..f3e9d3f184 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -214,6 +214,14 @@ pub fn compact_mode() -> Option { } } +/// `XCL_DIRECT_COMPACT_MIN` (`compact::compact_min`), for the caches' identities. +pub fn compact_min() -> Option { + super::compact::compact_min() +} + +#[cfg(test)] +pub(crate) use super::compact::COMPACT_MIN_FOR_TEST; + /// Non-default `XCL_DIRECT_COMPACT_NEST` cache tag for the translated cache identity. pub fn compact_nest_tag() -> Option { super::compact::nest_mode().cache_tag() @@ -325,6 +333,8 @@ fn translate_entry_with( #[cfg(test)] let declared_lds = DECLARED_LDS_FOR_TEST.with(|c| c.get()); #[cfg(test)] + let compact_min = super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.get()); + #[cfg(test)] let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); #[cfg(test)] let per_access = COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.get()); @@ -337,6 +347,8 @@ fn translate_entry_with( #[cfg(test)] DECLARED_LDS_FOR_TEST.with(|c| c.set(declared_lds)); #[cfg(test)] + super::compact::COMPACT_MIN_FOR_TEST.with(|c| c.set(compact_min)); + #[cfg(test)] super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); #[cfg(test)] COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.set(per_access)); @@ -488,7 +500,10 @@ fn translate_on_this_thread_inner( _ if !compute && !kernel => None, Some(false) => None, Some(true) => super::compact::plan(&cfg, &lw), - None => super::compact::automatic_plan(&cfg, &lw, compute && split), + None => match super::compact::compact_min() { + Some(min) if compute => super::compact::sized_plan(&cfg, &lw, min).or_else(|| super::compact::automatic_plan(&cfg, &lw, split)), + _ => super::compact::automatic_plan(&cfg, &lw, compute && split), + }, }; if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index d4d943a510..ab4c9fcfc3 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -295,6 +295,11 @@ mod translated { Some(on) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }), _ => id, }; + // `XCL_DIRECT_COMPACT_MIN`: compute programs from that size take the compact form + let id = match crate::gpu::dxil::kernel::compact_min() { + Some(n) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &format!("xcl-direct-compact-min-{n}")), + _ => id, + }; // `XCL_DIRECT_COMPACT_NEST`: a non-default nesting policy changes the compact IR let id = match crate::gpu::dxil::kernel::compact_nest_tag() { Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag), @@ -568,6 +573,10 @@ mod translated { Some(tag) => identity_for(&id.to_string(), tag), None => id, }; + let id = match crate::gpu::dxil::kernel::compact_min() { + Some(n) => identity_for(&id.to_string(), &format!("xcl-direct-compact-min-{n}")), + None => id, + }; let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; let id = if crate::gpu::dxil::kernel::coherent_per_access() { identity_for(&id.to_string(), "xcl-coherent-per-access") } else { id }; let id = if crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; @@ -1607,6 +1616,19 @@ mod shader_cache_tests { assert_eq!(with(true), with(true)); } + /// `XCL_DIRECT_COMPACT_MIN` translations are other entries of the direct translator's caches. + #[test] + fn a_compact_size_is_another_direct_output() { + let with = |n| { + let before = crate::gpu::dxil::kernel::COMPACT_MIN_FOR_TEST.with(|c| c.replace(Some(n))); + let id = translated::direct_output_identity(None, 1); + crate::gpu::dxil::kernel::COMPACT_MIN_FOR_TEST.with(|c| c.set(before)); + id + }; + assert_ne!(with(None), with(Some(4096))); + assert_ne!(with(Some(4096)), with(Some(8192))); + } + /// `XCL_ONE_WAVE_GROUP_IDS` translations are other entries of the direct translator's caches. #[test] fn one_wave_group_ids_are_another_direct_output() { From 712f1fe370bf8ed17b33fef848d2305d29ec5d1b Mon Sep 17 00:00:00 2001 From: upipibi Date: Sun, 29 Nov 2026 15:31:11 +0100 Subject: [PATCH 092/175] Recompiler: D16 format loads round UNORM / SNORM once, truncate floats Recompiler: D16 format loads of UNORM / SNORM data round once to nearest (2a4d3c8b): A D16 buffer format load packed a UNORM / SNORM channel with f32tof16 of the decoded f32: two roundings, the second toward zero on D3D12. RDNA2 rounds code / (2^w - 1) once to nearest even, so about half of all codes came back one unit in the last place low (16_UNORM 0x0801: 0x2800 for 0x2801). That value's binary expansion repeats the w-bit code, so its first 32 bits, floor((code << 32) / (2^w - 1)), decide the rounding and a tie cannot happen. Both paths; checked against exact rounding for every code at w = 2..16. #2026 (XCL-BT-020's third item). Recompiler: D16 format loads of float data truncate on every host (0cab3ef3): d16_fmt passed float channels to f32tof16 / legacyF32ToF16, whose rounding is the host's: it truncates on the RTX 3070 and WARP but rounds to nearest under vkd3d-proton (Marvisak/VIctory#2006), where RDNA2 truncates (boykopovar/AnyPS5#22750). Use f16_rtz in both paths, as the format stores already do. gpu_buffer_d16_loads_of_32_bit_floats_truncate loads 32_FLOAT values that the two roundings tell apart (1 + 1.5 / 1.75 ulp, 65535, +/-70000, a denormal half-way, -1.5, +inf). From xcl-dev/xcl#2027 (merge f409867a). Taken as is. (cherry picked from commit f409867a1eae8cc109f567fa1c16e18f7b8d24b4) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/lower_mem.rs | 95 ++++++++++++++++++++++++++-- crates/xcl/src/gpu/recomp/emit.rs | 26 +++++++- crates/xcl/src/gpu/recomp/tests.rs | 79 +++++++++++++++++++++++ 3 files changed, 193 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index d2c5aa46c1..9cc1301e77 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -650,6 +650,89 @@ impl Lw { self.s.m.set_insert_before_term(prev_ins); r } + /// A D16 format load's non-integer channel `s` (decoded f32 bits) of DST_SEL `sel` as f16. + /// UNORM / SNORM data is `code / (2^w - 1)`, rounded once to nearest as RDNA2 does: its + /// binary expansion repeats the w-bit code, so its first 32 bits decide the rounding (a tie + /// cannot happen). Other channels truncate (`f16_rtz`), as RDNA2 does, whatever the host's + /// `legacyF32ToF16` rounds to. + fn d16_fmt(&mut self, s: Value, sel: Value, info: Value) -> Value { + let f = self.f(s); + let plain = self.f16_rtz(f); + let ty = self.lshrc(info, 3); + let ty = self.andc(ty, 7); + let four = self.c(4); + let k = self.sub(sel, four); + let k = self.andc(k, 3); + let six = self.c(6); + let k6 = self.mul(k, six); + let eight = self.c(8); + let shift = self.add(k6, eight); + let w = self.bin(BinOp::LShr, info, shift); + let w = self.andc(w, 63); + let snorm = self.cmpc(Pred::Eq, ty, 1); + let one = self.c(1); + let wm1 = self.sub(w, one); + let we = self.sel(snorm, wm1, w); + let dmax = self.bin(BinOp::Shl, one, we); + let dmax = self.sub(dmax, one); + // the code, back from the decoded value (within 2 ULP of exact) + let zf = self.fc(0.0); + let onef = self.fc(1.0); + let a = self.fabs(f); + let u = self.fmax(f, zf); + let a = self.sel(snorm, a, u); + let a = self.fmin(a, onef); + let df = self.uitof(dmax); + let y = self.fmul(a, df); + let y = self.un(crate::gpu::dxil::ops_core::op::ROUND_NE, y); + let y = self.ftoui(y); + // first 32 bits of y / dmax + let y64 = self.zext64(y); + let k32 = self.c64(32); + let y64 = self.bin(BinOp::Shl, y64, k32); + let d64 = self.zext64(dmax); + let p = self.bin(BinOp::UDiv, y64, d64); + let p = self.trunc32(p); + let lz = self.lzcnt(p); + let fourteen = self.c(14); + let e = self.sub(fourteen, lz); + // normal: 11 bits after the leading one and the round bit + let pn = self.bin(BinOp::Shl, p, lz); + let b = self.lshrc(pn, 20); + let half_ = self.lshrc(b, 1); + let rb = self.andc(b, 1); + let m = self.add(half_, rb); + let em1 = self.sub(e, one); + let eh = self.shlc(em1, 10); + let normal = self.add(eh, m); + // subnormal + let s8 = self.lshrc(p, 8); + let r7 = self.lshrc(p, 7); + let r7 = self.andc(r7, 1); + let sub = self.add(s8, r7); + let is_normal = self.cmp(Pred::SGe, e, one); + let h = self.sel(is_normal, normal, sub); + let zero = self.c(0); + let y0 = self.cmpc(Pred::Eq, y, 0); + let h = self.sel(y0, zero, h); + let full = self.cmp(Pred::UGe, y, dmax); + let h = self.selc(full, 0x3C00, h); + let neg = self.fcmp(Pred::FOLt, f, zf); + let sbit = self.c(0x8000); + let sgn = self.land(snorm, neg); + let sgn = self.sel(sgn, sbit, zero); + let h = self.or(h, sgn); + // which channels: UNORM / SNORM (ty 0 / 1) of 2..16 bits, a component (sel >= 4) + let is_norm = self.cmpc(Pred::ULe, ty, 1); + let comp = self.cmpc(Pred::UGe, sel, 4); + let w_lo = self.cmpc(Pred::UGe, w, 2); + let w_hi = self.cmpc(Pred::ULe, w, 16); + let use_n = self.land(is_norm, comp); + let use_n = self.land(use_n, w_lo); + let use_n = self.land(use_n, w_hi); + self.sel(use_n, h, plain) + } + fn fmt_desc(&mut self, d3: Value, mtbuf_fmt: Option) -> FmtDesc { let key = (d3, mtbuf_fmt); if let Some(&cached) = self.fmt_desc_cache.get(&key) { @@ -1433,8 +1516,8 @@ impl Lw { if let Some((_, _, high)) = d16_format { let cur0 = self.vreg(vdata); let lo16 = self.andc(s_val, 0xFFFF); - let sf = self.f(s_val); - let h16 = self.s.f32_to_f16(sf); + let sel0 = self.andc(d3, 7); + let h16 = self.d16_fmt(s_val, sel0, c1.desc.info); let h = self.sel(c1.desc.isint, lo16, h16); if high { let h = self.shlc(h, 16); @@ -1478,8 +1561,9 @@ impl Lw { let half = |lw: &mut Lw, comp: u64| -> Value { let s = decode_sel(lw, comp); let lo = lw.andc(s, 0xFFFF); - let sf = lw.f(s); - let h = lw.s.f32_to_f16(sf); + let sel = lw.lshrc(d3, 3 * comp as u32); + let sel = lw.andc(sel, 7); + let h = lw.d16_fmt(s, sel, desc.info); lw.sel(desc.isint, lo, h) }; for i in 0..count { @@ -1506,8 +1590,7 @@ impl Lw { let sel = lw.andc(sel, 7); let s = lw.dst_sel(&c, sel, desc.isint); let lo = lw.andc(s, 0xFFFF); - let sf = lw.f(s); - let h = lw.s.f32_to_f16(sf); + let h = lw.d16_fmt(s, sel, desc.info); lw.sel(desc.isint, lo, h) }; for i in 0..count { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 75d11f3bc4..a21897003d 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2354,7 +2354,8 @@ impl Em { if let Some((_, components, high)) = d16_format { let half = |component: u64| { let selected = format!("dst_sel({t}_c, ({d3} >> {}u) & 7u, {t}_int)", 3 * component); - format!("select({t}_int, {selected} & 0xFFFFu, f32tof16(asfloat({selected})))") + let sel = format!("(({d3} >> {}u) & 7u)", 3 * component); + format!("select({t}_int, {selected} & 0xFFFFu, d16_fmt({selected}, {sel}, {t}_info))") }; let mut assigns = Vec::new(); if high { @@ -6438,6 +6439,29 @@ void st_bytes(uint a, uint4 r, uint n) { st_part(b, m << s, r.x << s); if (s != 0u && s + 8u * n > 32u) st_part(b + 4u, m >> (32u - s), r.x >> (32u - s)); } +// code / (2^w - 1) as f16, rounded once to nearest (RDNA2's D16 of UNORM / SNORM data): the +// binary expansion repeats the w-bit code, so p (its first 32 bits) decides the rounding, and a +// tie cannot happen. f32tof16 of the decoded f32 rounds twice, the second time toward zero. +uint norm16_rep(uint y, uint w) { + uint d = (1u << w) - 1u; + if (y == 0u) return 0u; + if (y >= d) return 0x3C00u; + uint p = (uint)(((uint64_t)y << 32) / (uint64_t)d); + uint lz = 31u - firstbithigh(p); + int e = 14 - (int)lz; + if (e >= 1) { uint b = (p << lz) >> 20; return ((uint)(e - 1) << 10) + (b >> 1) + (b & 1u); } + return (p >> 8) + ((p >> 7) & 1u); +} +// a D16 format load's non-integer channel x (decoded f32 bits) of DST_SEL sel +uint d16_fmt(uint x, uint sel, uint info) { + uint ty = (info >> 3) & 7u; + uint w = (info >> (8u + 6u * ((sel - 4u) & 3u))) & 63u; + if (ty > 1u || sel < 4u || w < 2u || w > 16u) return f16_rtz(asfloat(x)); + float f = asfloat(x); + if (ty == 0u) return norm16_rep((uint)round(saturate(f) * (float)((1u << w) - 1u)), w); + uint h = norm16_rep((uint)round(min(abs(f), 1.0f) * (float)((1u << (w - 1u)) - 1u)), w - 1u); + return h | select(f < 0.0f, 0x8000u, 0u); +} uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), pick4(c, (sel - 4u) & 3u))); } "#; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0f319e9e78..fb887b0e65 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1819,6 +1819,85 @@ fn gpu_typed_buffer_loads_and_stores() { assert_eq!(r.sgpr[50], 1 | 1 << 5, "s_bitset1"); } +#[test] +fn gpu_buffer_d16_loads_of_32_bit_floats_truncate() { + // RDNA2 packs a D16 load of a 32-bit float toward zero (boykopovar/AnyPS5#22750). The host's + // legacyF32ToF16 truncates on some drivers and rounds to nearest on others (vkd3d-proton), so + // these values tell the two apart: 1 + 1.5 / 1.75 ulp, overflow, a denormal half-way. + if !gpu_ready() { + return; + } + const IN: [u32; 8] = [0x3F80_3000, 0x3F80_3800, 0x4788_B800, 0xC788_B800, 0x477F_FF00, 0x33C0_0000, 0xBFC0_0000, 0x7F80_0000]; + const WANT: [u16; 8] = [0x3C01, 0x3C01, 0x7BFF, 0xFBFF, 0x7BFF, 0x0001, 0xBE00, 0x7C00]; + let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; + let code = prog(&[("BUFFER_LOAD_FORMAT_D16_X", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None)]); + let mut mem = vec![0u32; 512]; + mem[0x40..0x48].copy_from_slice(&IN); + let mut st = KernelState::default(); + st.sgpr[12..16].copy_from_slice(&[0x100, 0, 0x100, ident | 22 << 12]); // 32_FLOAT + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[1] = 4 * (l % 8) as u32; + } + let r = runner::run_code(&code, &st, &mem).unwrap(); + let mut bad = Vec::new(); + for l in 0..64 { + let got = (r.vgpr[l][10] & 0xFFFF) as u16; + if got != WANT[l % 8] { + bad.push(format!("lane {l}: {:#010x} -> {got:#06x}, want {:#06x}", IN[l % 8], WANT[l % 8])); + } + } + assert!(bad.is_empty(), "{} of 64 differ: +{}", bad.len(), bad.join(" +")); +} + +/// D16 format loads of 16_UNORM / 16_SNORM: RDNA2 rounds the normalised value to f16 once, to +/// nearest even (XCL-BT-020, gfx1031; AnyPS5#22750 over 256 16-bit codes, gfx1036). 64 lanes each +/// load their own code; the expected halves are the exact value rounded once. +#[test] +fn gpu_buffer_d16_loads_of_16_bit_norms_round_once() { + if !gpu_ready() { + return; + } + const UNORM: [u16; 64] = [0x0000, 0xFFFF, 0xFFAF, 0xFFEF, 0x0801, 0x0803, 0x0805, 0x0807, 0x8000, 0x7FFF, 0x1234, 0x4321, 0xEBBE, 0x78FA, 0xE20F, 0xF2BF, 0x4275, 0x8398, 0xBD51, 0x1BC1, 0xB57A, 0x7378, 0x64F0, 0x9631, 0xA93D, 0x1078, 0xE750, 0x620A, 0x03BF, 0x5971, 0x9EFA, 0xA070, 0xC8CB, 0x2DF2, 0xF2DD, 0xEEA9, 0x028F, 0xD55A, 0x6C19, 0x23A3, 0xE272, 0x61DF, 0x186A, 0xB09A, 0x0F62, 0xAD5F, 0x89C7, 0xDB80, 0x92C3, 0x507A, 0x6FF9, 0x5CFD, 0xF790, 0xCFC4, 0xB827, 0xE334, 0x70BB, 0xF609, 0x5ADA, 0x4EDA, 0xDEC6, 0xCA73, 0xAAE7, 0x0E6C]; + const UNORM_F16: [u16; 64] = [0x0000, 0x3C00, 0x3BFD, 0x3BFF, 0x2801, 0x2802, 0x2803, 0x2804, 0x3800, 0x3800, 0x2C8D, 0x3432, 0x3B5E, 0x3790, 0x3B10, 0x3B96, 0x3427, 0x381D, 0x39EB, 0x2EF0, 0x39AC, 0x3738, 0x364F, 0x38B2, 0x394A, 0x2C1E, 0x3B3B, 0x3621, 0x237E, 0x3597, 0x38F8, 0x3904, 0x3A46, 0x31BE, 0x3B97, 0x3B75, 0x211E, 0x3AAB, 0x36C2, 0x3074, 0x3B14, 0x361E, 0x2E1B, 0x3985, 0x2BB1, 0x396B, 0x384E, 0x3ADC, 0x3896, 0x3508, 0x3700, 0x35D0, 0x3BBD, 0x3A7E, 0x39C1, 0x3B1A, 0x370C, 0x3BB0, 0x35AE, 0x34EE, 0x3AF6, 0x3A54, 0x3957, 0x2B36]; + const SNORM: [u16; 64] = [0x0000, 0x7FFF, 0x8000, 0x8001, 0x7FF7, 0x8009, 0x0401, 0x0403, 0xFBFF, 0xC000, 0x4000, 0x0001, 0x0669, 0x5B5B, 0x93FA, 0x9DB5, 0xAA7E, 0x4B72, 0x6920, 0xC24D, 0x6F99, 0x4FDA, 0x507E, 0xE531, 0x1C88, 0x0D1A, 0x3151, 0xDB97, 0xDA66, 0xADB0, 0xF832, 0xE808, 0xFE62, 0xD349, 0xEFCC, 0xFC89, 0xFF9D, 0xAEB5, 0x3CAB, 0xA475, 0x1B07, 0xFCAC, 0x2B11, 0x067A, 0xA023, 0x872F, 0xAC57, 0x775A, 0x3629, 0x315A, 0xA1B8, 0x6C88, 0xA7C3, 0xD5E3, 0xECDC, 0x4E5C, 0x6CEB, 0xFB6D, 0x0ED9, 0x00B7, 0x0A51, 0x205A, 0x490A, 0x246B]; + const SNORM_F16: [u16; 64] = [0x0000, 0x3C00, 0xBC00, 0xBC00, 0x3BFF, 0xBBFF, 0x2801, 0x2803, 0xA801, 0xB800, 0x3800, 0x0200, 0x2A69, 0x39B6, 0xBAC0, 0xBA25, 0xB958, 0x38B7, 0x3A92, 0xB7B6, 0x3AFA, 0x38FE, 0x3908, 0xB2B4, 0x3322, 0x2E8D, 0x362A, 0xB48D, 0xB4B3, 0xB925, 0xABCE, 0xB1FE, 0xA278, 0xB597, 0xB00D, 0xA6EE, 0x9A30, 0xB915, 0x3795, 0xB9B9, 0x32C2, 0xA6A8, 0x3562, 0x2A7A, 0xB9FE, 0xBB8D, 0xB93B, 0x3B76, 0x36C5, 0x362B, 0xB9E5, 0x3AC9, 0xB984, 0xB544, 0xB0C9, 0x38E6, 0x3ACF, 0xA893, 0x2F6D, 0x1DB8, 0x2D29, 0x340B, 0x3891, 0x348D]; + let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; + let vs = |base: u32, fmt: u32| [base, 0, 0x100, ident | fmt << 12]; + let code = prog(&[ + ("BUFFER_LOAD_FORMAT_D16_X", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None), + ("BUFFER_LOAD_FORMAT_D16_X", "ENC_MUBUF", &[("VDATA", 11), ("VADDR", 1), ("SRSRC", 4), ("SOFFSET", 128), ("OFFEN", 1)], None), + ]); + let mut mem = vec![0u32; 512]; + for l in 0..64 { + let put = |mem: &mut Vec, base: usize, v: u16| { + let (w, sh) = ((base + 2 * l) / 4, 16 * (l % 2)); + mem[w] |= (v as u32) << sh; + }; + put(&mut mem, 0x100, UNORM[l]); + put(&mut mem, 0x200, SNORM[l]); + } + let mut st = KernelState::default(); + st.sgpr[12..16].copy_from_slice(&vs(0x100, 7)); // 16_UNORM + st.sgpr[16..20].copy_from_slice(&vs(0x200, 8)); // 16_SNORM + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[1] = 2 * l as u32; + } + let r = runner::run_code(&code, &st, &mem).unwrap(); + let mut bad = Vec::new(); + for l in 0..64 { + let (u, s) = ((r.vgpr[l][10] & 0xFFFF) as u16, (r.vgpr[l][11] & 0xFFFF) as u16); + if u != UNORM_F16[l] { + bad.push(format!("16_UNORM {:#06x}: {u:#06x}, want {:#06x}", UNORM[l], UNORM_F16[l])); + } + if s != SNORM_F16[l] { + bad.push(format!("16_SNORM {:#06x}: {s:#06x}, want {:#06x}", SNORM[l], SNORM_F16[l])); + } + } + assert!(bad.is_empty(), "{} of 128 differ:\n{}", bad.len(), bad.join("\n")); +} + fn el(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gpu::dxbc::SigElement { crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } } From 50acd77e3b4f892740cf74eb970daf2d77686536 Mon Sep 17 00:00:00 2001 From: upipibi Date: Sun, 29 Nov 2026 15:31:26 +0100 Subject: [PATCH 093/175] Recompiler: a 2-bit SNORM store component rounds a half away from zero Recompiler: a 2-bit SNORM store component rounds a half away from zero (fc5a8efa): fmt_encode rounded every SNORM component to nearest even, so 0.5 and -0.5 stored 0 in the 2-bit W of 2_10_10_10_SNORM (0x28120100 for 0x68120100). RDNA2 stores +-1 from a magnitude of 0.5 up; its 8-, 10- and 16-bit SNORM components do round to nearest even (AnyPS5#25877, a store sweep of 75 formats on gfx1036). Both paths. Recompiler: a 2-bit SNORM store component below 0.5 stores 0 (d25e85f1): floor(|x| + 0.5) stored +-1 for the f32 neighbours just below +-0.5 (0x3effffff, 0xbeffffff): 0.49999997 + 0.5 rounds to 1.0 in f32, so W read 0x68120100 / 0xe8120100 instead of 0x28120100 on both paths (reported by nnonno91 on AMD). The 2-bit magnitude is at most 1, so compare it with 0.5 directly; +-0.5 still stores +-1. The test gains the two below-half inputs and their +-0.5 neighbours. From xcl-dev/xcl#2051 (merge 8da3a64f). Taken as is. (cherry picked from commit 8da3a64fc63464e902914cc7532340b77daeeb53) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/lower_mem.rs | 13 +++++++- crates/xcl/src/gpu/recomp/emit.rs | 5 +++- crates/xcl/src/gpu/recomp/tests.rs | 45 ++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 9cc1301e77..736077f99a 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -1124,7 +1124,18 @@ impl Lw { let cl = self.fmin(cl, p1); let cl = self.sel(n, z, cl); let s1 = self.fmul(cl, maxs); - let s1 = self.un(super::ops_core::op::ROUND_NE, s1); + let rne = self.un(super::ops_core::op::ROUND_NE, s1); + // a 2-bit component (+-1 / 0) rounds a half away from zero (RDNA2: 0.5 stores 1). Its + // magnitude is at most 1, so compare it with 0.5 directly: floor(|s1| + 0.5) would store 1 + // for 0.49999997 (the f32 sum rounds to 1.0) + let half = self.fc(0.5); + let a1 = self.fabs(s1); + let ge = self.fcmp(Pred::FOGe, a1, half); + let neg = self.fcmp(Pred::FOLt, s1, z); + let pm1 = self.sel(neg, m1, p1); + let away = self.sel(ge, pm1, z); + let w2 = self.cmpc(Pred::Eq, w, 2); + let s1 = self.sel(w2, away, rne); let e1 = self.ftosi(s1); let e2 = self.ftoui(f); let e3 = self.ftosi(f); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index a21897003d..c12a11efe1 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -6410,7 +6410,10 @@ uint fmt_encode(uint x, uint info, uint c) { float maxu = w >= 32u ? 4294967295.0f : (float)((1u << w) - 1u); float maxs = w >= 32u ? 2147483647.0f : (float)((1u << (w - 1u)) - 1u); if (ty == 0u) return (uint)round(saturate(f) * maxu); - if (ty == 1u) return (uint)(int)round((isnan(f) ? 0.0f : clamp(f, -1.0f, 1.0f)) * maxs); + // SNORM to nearest even, but a 2-bit component (+-1 / 0) rounds a half away from zero + // (RDNA2: 0.5 stores 1, -0.5 stores -1). Its magnitude is at most 1, so compare it with 0.5 directly: + // floor(abs(sn) + 0.5f) would store 1 for 0.49999997 (the f32 sum rounds to 1.0) + if (ty == 1u) { float sn = (isnan(f) ? 0.0f : clamp(f, -1.0f, 1.0f)) * maxs; return (uint)(int)(w == 2u ? (abs(sn) >= 0.5f ? (sn < 0.0f ? -1.0f : 1.0f) : 0.0f) : round(sn)); } if (ty == 2u) return (uint)f; if (ty == 3u) return (uint)(int)f; if (ty == 4u) return w >= 32u ? x : min(x, (1u << w) - 1u); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index fb887b0e65..e6e4e8a18f 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -10201,6 +10201,51 @@ fn gpu_fmt_encode_direct_dxil_int_sat_and_f16_rtz() { } } +/// The 2-bit component of a 2_10_10_10_SNORM format store is ±1 from a magnitude of 0.5 up and 0 +/// below; RDNA2 does not round it to nearest even (AnyPS5#25877, a store sweep of 75 formats on +/// gfx1036: only this component differs). 12 lanes store x = 0.5, y = 0.25, z = -0.75 and their own w; +/// the f32 neighbours just below ±0.5 (0x3effffff, 0xbeffffff) store 0, which `floor(|x| + 0.5)` +/// misses: 0.49999997 + 0.5 rounds to 1.0 in f32. +#[test] +fn gpu_buffer_store_two_bit_snorm_rounds_half_away() { + if !gpu_ready() { + return; + } + let ident = 4 | 5 << 3 | 6 << 6 | 7 << 9; + let code = prog(&[ + ("BUFFER_STORE_FORMAT_XYZW", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("OFFEN", 1)], None), + ]); + // (w, packed word): x, y, z are 10-bit at 0 / 10 / 20, w 2-bit at 30 + let cases: [(f32, u32); 12] = [ + (0.5, 0x6812_0100), + (-0.5, 0xE812_0100), + (0.49, 0x2812_0100), + (-0.75, 0xE812_0100), + (1.0, 0x6812_0100), + (-1.0, 0xE812_0100), + (0.499_999_9, 0x2812_0100), + (0.500_000_1, 0x6812_0100), + (f32::from_bits(0x3EFF_FFFF), 0x2812_0100), + (f32::from_bits(0xBEFF_FFFF), 0x2812_0100), + (f32::from_bits(0x3F00_0000), 0x6812_0100), + (f32::from_bits(0xBF00_0000), 0xE812_0100), + ]; + let mut st = KernelState::default(); + st.sgpr[12..16].copy_from_slice(&[0x100, 0, 0x100, ident | 51 << 12]); // 2_10_10_10_SNORM + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[1] = 4 * (l % cases.len()) as u32; + r[4] = f(0.5); + r[5] = f(0.25); + r[6] = f(-0.75); + r[7] = f(cases[l % cases.len()].0); + } + let mem = vec![0u32; 512]; + let r = runner::run_code(&code, &st, &mem).unwrap(); + for (k, &(w, want)) in cases.iter().enumerate() { + assert_eq!(r.mem[0x100 / 4 + k], want, "w = {w}: {:#010x}, want {want:#010x}", r.mem[0x100 / 4 + k]); + } +} + #[test] fn gpu_signed_bfe_arithmetic_shift() { for wave64 in gpu_waves() { From 31f45f339cc401cde2efcc84ca08bd9aa945dd40 Mon Sep 17 00:00:00 2001 From: emirduran707 Date: Sun, 29 Nov 2026 15:31:33 +0100 Subject: [PATCH 094/175] Direct DXIL: v_cvt_f16_u16 / v_cvt_f16_i16 decode inline float constants as f32 Direct DXIL: decode inline float constants as f32 for `v_cvt_f16_u16` and `v_cvt_f16_i16` (1506f4ba): `Lw::valu16` passed `name.contains("f16")` as `src_f16` to `self.sources()`, decoding inline float constants (`240..=248`) as f16 bit patterns for `v_cvt_f16_u16` and `v_cvt_f16_i16`. Both instructions take a 16-bit integer source (not f16), so inline constants decode as f32 bit patterns per the RDNA2 ISA and `emit.rs` (e.g. `v_cvt_f16_u16 v0, 1.0` produced `0x7380` instead of `0x0000`). Exclude `v_cvt_f16_u16` and `v_cvt_f16_i16` from `src_f16`, matching `recomp/emit.rs`, and add a GPU parity test against HLSL. From xcl-dev/xcl#1870 (merge 5fc135af). Taken as is. (cherry picked from commit 5fc135af6f3807c17c5a8cd8141e8c06d10203e7) Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/core_tests.rs | 28 +++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_wide.rs | 3 ++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index ae2577829d..76bf061906 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -724,6 +724,34 @@ fn ps_get_lod_with_a_static_sampler() { } } +/// `v_cvt_f16_u16` and `v_cvt_f16_i16` take 16-bit integer sources, not f16: inline float +/// constants (`240..=248`) must decode as f32 bit patterns (matching `emit.rs` and RDNA2 ISA), +/// not f16 constants. +#[test] +fn v_cvt_f16_int_decodes_inline_float_constants_as_f32() { + use crate::gpu::recomp::{dxc, runner, Options}; + let code = prog(&[ + ("V_CVT_F16_U16", "ENC_VOP1", &[("VDST", 0), ("SRC0", 242)], None), // f32 1.0 = 0x3F80_0000 -> low16 = 0 + ("V_CVT_F16_I16", "ENC_VOP1", &[("VDST", 1), ("SRC0", 243)], None), // f32 -1.0 = 0xBF80_0000 -> low16 = 0 + ("V_CVT_F16_U16", "ENC_VOP1", &[("VDST", 2), ("SRC0", 248)], None), // f32 1/(2pi) = 0x3E22_F983 -> low16 = 0xF983 + ]); + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = translate(&code, ko).unwrap_or_else(|e| panic!("direct DXIL failed: {e}")); + if runner::wave32_supported() != Ok(true) { + return runner::skip_test("no wave32"); + } + if dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let st = runner::KernelState::default(); + let direct = runner::run(&dxil, &st, &[]).unwrap(); + let t = crate::gpu::recomp::translate(&code, &Options { wave64: false, ..Default::default() }).unwrap(); + let hlsl = runner::run(&dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(), &st, &[]).unwrap(); + for r in 0..=2 { + assert_eq!(direct.vgpr[0][r], hlsl.vgpr[0][r], "v{r}: {:#x} vs {:#x}", direct.vgpr[0][r], hlsl.vgpr[0][r]); + } +} + /// Without a program-set `MODE[3:2]`, `v_cvt_f16_f32`, `v_mul_f16` and `v_pk_mul_f16` /// must round to nearest-even (matching RDNA2 and the HLSL path) rather than using /// `dx.op.legacyF32ToF16` (which rounds toward zero / flushes below the smallest f16 denormal). diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index b52981140d..bab4290aba 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -378,7 +378,8 @@ impl Lw { pub fn valu16(&mut self, d: &Decoded, name: &str) -> LResult<()> { let (outs, ins) = Self::ops(d); let m = Self::mods(d); - let u: Vec = self.sources(d, &ins, name.contains("f16"))?.into_iter().map(Src::w).collect(); + let src_f16 = name.contains("f16") && !matches!(name, "v_cvt_f16_u16" | "v_cvt_f16_i16"); + let u: Vec = self.sources(d, &ins, src_f16)?.into_iter().map(Src::w).collect(); let plain = d.variant == Variant::Plain; let z = self.c(0); let half = |s: &mut Self, i: usize| -> Value { From 55e296b39e558115fb08e0b3893710a0aee4d7e2 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:31:48 +0100 Subject: [PATCH 095/175] Direct DXIL: saturate v_pk_*_i16 CLAMP with masked select Direct DXIL: saturate v_pk_*_i16 CLAMP with masked select (NVIDIA) (651fc050): Packed signed 16-bit add/sub/mad with `CLAMP=1` in `Lw::valu_pk` previously lowered saturation as `IMax(IMin(t, 0x7FFF), -32768) & 0xFFFF` before OR-ing the low and high halves. On NVIDIA Ampere drivers (RTX 3070 616.56 and RTX 3060 610.88), the driver drops the trailing `& 0xFFFF` mask for negative clamped low halves, leaving sign-extended `0xFFFF_xxxx` to clobber bits [31:16] of the packed destination (for example `[-1, 1] - [1, 1]` yields `0xFFFF_FFFE` instead of `0x0000_FFFE`). Replace the `IMin`/`IMax`/`& 0xFFFF` sequence with signed 32-bit comparisons and a `select` chain over 16-bit constants (`0x7FFF`, `0x8000`) and `t & 0xFFFF`, matching the masked-select saturation form used in #2398 for non-packed 16-bit integer ops. Add `i16_clamp_mask_tests::v_pk_i16_clamp_uses_masked_select_without_imin_imax` (DXIL validator + IR check) and `i16_clamp_mask_tests::gpu_i16_clamp_negative_low_half_keeps_high_half` covering `V_PK_ADD_I16`, `V_PK_SUB_I16`, and `V_PK_MAD_I16` with `CLAMP=1` alongside `V_CVT_PK_I16_I32` and `V_CVT_I16_F16` controls. Based on @upipibi's root-cause analysis and fix (`upipibi/xcl@6fe2b3e7`) and @Smokeyqdqd's independent RTX 3060 reproduction. From xcl-dev/xcl#2855 (merge a936ab42). Taken as is. (cherry picked from commit a936ab427bc30bc24b923ee5a1a4aff299e49660) Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/lower_wide.rs | 189 +++++++++++++++++++++++++- 1 file changed, 185 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index bab4290aba..7888467060 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -179,10 +179,14 @@ impl Lw { self.add(t, w) } }; - let (lo, hi) = (self.c(0xFFFF_8000), self.c(0x7FFF)); - let t = self.imin(t, hi); - let t = self.imax(t, lo); - self.andc(t, 0xFFFF) + // Select between 16-bit patterns instead of masking `IMax(IMin(t, 0x7FFF), -32768)`: + // NVIDIA Ampere drivers (610.88 / 616.56) drop the `& 0xFFFF` after `IMax(IMin(...))`, + // leaving a sign-extended negative low half (`0xFFFF_xxxx`) that clobbers bits [31:16]. + let gt = self.cmpc(Pred::SGt, t, 0x7FFF); + let lt = self.cmpc(Pred::SLt, t, 0xFFFF_8000); + let low = self.andc(t, 0xFFFF); + let r = self.selc(gt, 0x7FFF, low); + self.selc(lt, 0x8000, r) } "v_pk_add_u16" | "v_pk_add_i16" => { let t = self.add(a, b); @@ -1458,6 +1462,183 @@ mod cmp64_tests { } } +#[cfg(test)] +mod i16_clamp_mask_tests { + use crate::gpu::dxil::{kernel, validate}; + use crate::gpu::rdna2; + use crate::gpu::recomp::runner; + + fn sat16(v: i32) -> u32 { + v.clamp(-32768, 32767) as u32 & 0xFFFF + } + + fn pk(lo: i16, hi: i16) -> u32 { + (lo as u16 as u32) | ((hi as u16 as u32) << 16) + } + + /// Direct DXIL `v_pk_add_i16`, `v_pk_sub_i16`, and `v_pk_mad_i16` with `CLAMP=1` must saturate + /// via 32-bit signed comparisons and `select` over 16-bit masked values without `IMin`/`IMax` + /// or `Int64Ops`. + #[test] + fn v_pk_i16_clamp_uses_masked_select_without_imin_imax() { + const V: u64 = 256; + let pk2 = |dst: u64| [("VDST", dst), ("SRC0", V), ("SRC1", V + 1), ("OP_SEL_HI", 3), ("CLAMP", 1)]; + let mut code = rdna2::encode("V_PK_ADD_I16", "ENC_VOP3P", &pk2(4), None).unwrap(); + code.extend(rdna2::encode("V_PK_SUB_I16", "ENC_VOP3P", &pk2(5), None).unwrap()); + code.extend( + rdna2::encode( + "V_PK_MAD_I16", + "ENC_VOP3P", + &[("VDST", 6), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1), ("CLAMP", 1)], + None, + ) + .unwrap(), + ); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let ko = kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = kernel::translate(&code, ko).expect("direct translate"); + if !validate::validator_supported() { + validate::skip_validation(); + return; + } + validate::validate(&dxil).expect("dxil validate"); + let dis = validate::disassemble(&dxil).expect("dxil disassemble"); + assert!(!dis.contains("64-bit integers"), "v_pk_*_i16 CLAMP must not require Int64Ops:\n{dis}"); + assert!(!dis.contains("@dx.op.binary.i32(i32 37,"), "v_pk_*_i16 CLAMP must not emit IMax:\n{dis}"); + assert!(!dis.contains("@dx.op.binary.i32(i32 38,"), "v_pk_*_i16 CLAMP must not emit IMin:\n{dis}"); + assert!(dis.contains("icmp sgt i32"), "v_pk_*_i16 CLAMP must compare against upper i16 bound:\n{dis}"); + assert!(dis.contains("icmp slt i32"), "v_pk_*_i16 CLAMP must compare against lower i16 bound:\n{dis}"); + assert!(dis.contains("select i1"), "v_pk_*_i16 CLAMP must saturate via select:\n{dis}"); + } + + /// Direct DXIL `v_pk_add_i16` / `v_pk_sub_i16` / `v_pk_mad_i16` with `CLAMP=1` (distinct source + /// registers), plus `v_cvt_pk_i16_i32` and `v_cvt_i16_f16` controls across the saturation edges + /// on the GPU: a negative saturated low half must not spill into bits [31:16]. With + /// `IMax(IMin(t, 0x7FFF), -0x8000) & 0xFFFF`, NVIDIA Ampere (RTX 3070 616.56 / RTX 3060 610.88) + /// returned e.g. `0xFFFF_FFFE` for `[-1, 1] - [1, 1]` instead of `0x0000_FFFE`. + #[test] + fn gpu_i16_clamp_negative_low_half_keeps_high_half() { + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + const V: u64 = 256; + let pk2 = |dst: u64| [("VDST", dst), ("SRC0", V), ("SRC1", V + 1), ("OP_SEL_HI", 3), ("CLAMP", 1)]; + let mut code = rdna2::encode("V_PK_ADD_I16", "ENC_VOP3P", &pk2(4), None).unwrap(); + code.extend(rdna2::encode("V_PK_SUB_I16", "ENC_VOP3P", &pk2(5), None).unwrap()); + code.extend( + rdna2::encode( + "V_PK_MAD_I16", + "ENC_VOP3P", + &[("VDST", 6), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 9), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1), ("CLAMP", 1)], + None, + ) + .unwrap(), + ); + code.extend(rdna2::encode("V_CVT_PK_I16_I32", "ENC_VOP3", &[("VDST", 7), ("SRC0", V + 2), ("SRC1", V + 3)], None).unwrap()); + code.extend(rdna2::encode("V_CVT_I16_F16", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 10)], None).unwrap()); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let ko = kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = kernel::translate(&code, ko).expect("direct translate"); + + // [a_lo, a_hi] and [b_lo, b_hi]; the remaining lanes take pseudo-random halves + let pairs: [[i16; 4]; 16] = [ + [-1, 1, 1, 1], + [-32768, 100, 1, -7], + [-2, 3, -32768, 4], + [5, 1, 1, 1], + [32767, -32768, 1, -1], + [-32768, 32767, -1, 1], + [-32768, -32768, -32768, -32768], + [32767, 32767, 32767, 32767], + [-23, 0, 0, 0], + [-100, 200, -100, 200], + [0, 0, 0, 0], + [-16384, 16384, -16385, 16384], + [-1, -1, -1, -1], + [100, -100, 200, 50], + [-32767, 5, 2, 6], + [1, -1, -32768, 32767], + ]; + // [c_lo, c_hi] addends for `v_pk_mad_i16` (`sat16(a * b + c)`), exercising negative + // in-range low halves, positive/negative saturation, and 32-bit intermediate cancellation. + let mad_c: [[i16; 2]; 16] = [ + [-1, 0], + [-1, 10], + [0, 1], + [-10, 0], + [1, -1], + [-32768, 1], + [-32768, 32767], + [32767, -32768], + [-23, 5], + [-20000, -32768], + [0, 0], + [0, 0], + [-32768, -32768], + [-32768, 1000], + [-10, 7], + [-1, 1], + ]; + let cvt_pk: [(i32, i32); 8] = + [(-1, 1), (-40000, 1), (40000, -40000), (-32768, 32767), (-32769, 32768), (5, 7), (i32::MIN, i32::MAX), (-23, -23)]; + // binary16 bits and the truncated, saturated result + let cvt_h: [(u32, i16); 8] = [ + (0xBC00, -1), // -1.0 + (0xCDC0, -23), // -23.0 + (0xF8E2, -32768), // -40000.0 + (0x78E2, 32767), // 40000.0 + (0xF800, -32768), // -32768.0 + (0xFBFF, -32768), // -65504.0 + (0x3C00, 1), // 1.0 + (0x0000, 0), // +0.0 + ]; + let mut seed = 0x1234_5678u32; + let mut rnd = || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + seed + }; + let mut st = runner::KernelState::default(); + let mut want = Vec::new(); + for (lane, r) in st.vgpr.iter_mut().take(32).enumerate() { + let (p, mc) = if lane < pairs.len() { + (pairs[lane], mad_c[lane]) + } else { + let (x, y, z) = (rnd(), rnd(), rnd()); + ([x as i16, (x >> 16) as i16, y as i16, (y >> 16) as i16], [z as i16, (z >> 16) as i16]) + }; + let (c0, c1) = if lane < cvt_pk.len() { + cvt_pk[lane] + } else { + (rnd() as i32 >> (lane % 16), rnd() as i32 >> (lane % 13)) + }; + let (h, hv) = cvt_h[lane % cvt_h.len()]; + (r[0], r[1], r[2], r[3], r[9], r[10]) = (pk(p[0], p[1]), pk(p[2], p[3]), c0 as u32, c1 as u32, pk(mc[0], mc[1]), h); + let (a, b, c) = ([p[0] as i32, p[1] as i32], [p[2] as i32, p[3] as i32], [mc[0] as i32, mc[1] as i32]); + want.push([ + sat16(a[0] + b[0]) | (sat16(a[1] + b[1]) << 16), + sat16(a[0] - b[0]) | (sat16(a[1] - b[1]) << 16), + sat16(a[0] * b[0] + c[0]) | (sat16(a[1] * b[1] + c[1]) << 16), + sat16(c0) | (sat16(c1) << 16), + hv as u16 as u32, + ]); + } + let res = runner::run(&dxil, &st, &[]).expect("GPU run"); + let names = ["v_pk_add_i16 clamp", "v_pk_sub_i16 clamp", "v_pk_mad_i16 clamp", "v_cvt_pk_i16_i32", "v_cvt_i16_f16"]; + let mut bad = Vec::new(); + for (lane, w) in want.iter().enumerate() { + for (k, &e) in w.iter().enumerate() { + let got = res.vgpr[lane][4 + k]; + if got != e { + bad.push(format!("lane {lane} {}: got {got:#010X}, want {e:#010X}", names[k])); + } + } + } + assert!(bad.is_empty(), "{} mismatches:\n{}", bad.len(), bad.join("\n")); + } +} + #[cfg(test)] mod rcp_d_tests { use crate::gpu::dxil::{kernel, validate}; From b2f5729c9d6ad4414c2004371a8cb5e33c82d11c Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:31:55 +0100 Subject: [PATCH 096/175] Direct DXIL: rm_sqrt keeps negative preserved denormals NaN, rm_mad goes by_mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DXIL: fix negative preserved denormal qNaN in rm_sqrt and route rm_mad via by_mode (b3fced11): Fix two direct-DXIL directed f32 rounding bugs in lower_round.rs: 1. Lw::rm_sqrt previously fell back to the native dx.op.unary.f32(Sqrt, fa) value for nonzero special inputs. Under D3D12 / SM 6.x, native f32 sqrt flushes f32 denormals to zero, so a negative preserved denormal (MODE[4] == 1) returned -0.0 instead of qNaN, and static directed modes retained an unnecessary native Sqrt call. Compute the special-case result directly from the MODE[4]-filtered bits u (±0 -> ±0, +inf -> +inf, all negative nonzero inputs and NaNs -> canonical qNaN 0x7FC0_0000) so negative preserved denormals produce qNaN and DCE removes the unused native Sqrt in static directed modes. 2. Route Lw::rm_mad directly through Lw::by_mode (exact f64 multiply -> round_exact -> ext_exact -> round_sum) instead of nesting rm_mul and rm_add around an outer is_ne select. Constant RNE now folds directly to native mad_nf, and dynamic mode avoids emitting redundant dead native fmul/fadd instructions. Update ref_sqrt and directed_reference_basics in round_tests.rs to verify negative sqrt qNaN and denormal flushing, and add DXIL validation/IR and GPU regression tests for both fixes. Part of #675 Part of #1833 From xcl-dev/xcl#2534 (merge 805f9100). Taken as is. (cherry picked from commit 805f9100e9995242cffa42c6467a61c5edf42645) Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/lower_round.rs | 39 +++++----- crates/xcl/src/gpu/dxil/round_tests.rs | 102 ++++++++++++++++++++++++- 2 files changed, 119 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_round.rs b/crates/xcl/src/gpu/dxil/lower_round.rs index a80b3796ca..b7885df4a0 100644 --- a/crates/xcl/src/gpu/dxil/lower_round.rs +++ b/crates/xcl/src/gpu/dxil/lower_round.rs @@ -327,22 +327,17 @@ impl Lw { /// `v_mad_f32` / `v_mac_f32`: the product rounded, then the sum rounded. pub fn rm_mad(&mut self, a: Value, b: Value, c: Value, native: Value) -> Value { - if self.f32_mode().is_none() { - return native; - } - let fa = self.f(a); - let fb = self.f(b); - let pn = self.fmul(fa, fb); - let p = self.rm_mul(a, b, pn); - let pb = self.bits(p); - let fc = self.f(c); - let sn = self.fadd(p, fc); - let r = self.rm_add(pb, c, sn); - // nearest even: the native mad as before - let mode = self.rd(VAR_F32_MODE); - let rm = self.andc(mode, 3); - let is_ne = self.cmpc(Pred::Eq, rm, 0); - self.sel(is_ne, native, r) + let Some(mode) = self.f32_mode() else { return native }; + self.by_mode(native, mode, &mut |lw| { + let x = lw.ext_exact(a, mode); + let y = lw.ext_exact(b, mode); + let p = lw.fmul(x, y); + let z = lw.dc(0.0); + let pb = lw.round_exact(p, z, mode); + let px = lw.ext_exact(pb, mode); + let w = lw.ext_exact(c, mode); + lw.round_sum(px, w, mode) + }) } /// An integer converted to f32 (`v_cvt_f32_i32` / `_u32`). @@ -426,17 +421,21 @@ impl Lw { let back = lw.c(50 << 23); let scaled = lw.sub(res, back); let res = lw.sel(small, scaled, res); - // ±0 (flushed denormals too), negative, inf, NaN: sqrt(±0) = ±0, else native + // ±0 (flushed denormals too) → ±0, +inf → +inf, negative (incl. preserved denormals, + // -inf) and NaN → canonical qNaN (no fallback to native, which flushes f32 denormals) let mag = lw.andc(u, 0x7FFF_FFFF); let z = lw.cmpc(Pred::Eq, mag, 0); let negv = lw.cmpc(Pred::SLt, u, 0); let infnan = lw.cmpc(Pred::UGe, mag, 0x7F80_0000); let sp = lw.lor(z, negv); let sp = lw.lor(sp, infnan); - let nb = lw.bits(native); + let pinf = lw.cmpc(Pred::Eq, u, 0x7F80_0000); + let inf = lw.c(0x7F80_0000); + let qnan = lw.c(0x7FC0_0000); + let spv = lw.sel(pinf, inf, qnan); let sg = lw.andc(u, 0x8000_0000); - let zr = lw.sel(z, sg, nb); - lw.sel(sp, zr, res) + let spv = lw.sel(z, sg, spv); + lw.sel(sp, spv, res) }) } diff --git a/crates/xcl/src/gpu/dxil/round_tests.rs b/crates/xcl/src/gpu/dxil/round_tests.rs index 8987ae8f39..f51fd623a3 100644 --- a/crates/xcl/src/gpu/dxil/round_tests.rs +++ b/crates/xcl/src/gpu/dxil/round_tests.rs @@ -161,7 +161,7 @@ fn ref_sqrt(a: u32, m: Mode) -> Option { return Some((s as u32) << 31); } if s { - return None; + return Some(0x7FC0_0000); } // sqrt(ma · 2^ea): make the exponent even and the integer large (≥ 2^100) let (mut mm, mut e) = (ma, ea); @@ -346,6 +346,11 @@ fn directed_reference_basics() { assert_eq!(ref_sqrt(2.0f32.to_bits(), m(3)), Some(2f32.sqrt().to_bits())); assert_eq!(ref_sqrt(2.0f32.to_bits(), m(1)), Some(2f32.sqrt().to_bits() + 1)); assert_eq!(ref_sqrt(4.0f32.to_bits(), m(1)), Some(2.0f32.to_bits())); + let flush = |rm| Mode { rm, keep_in: false, keep_out: false }; + assert_eq!(ref_sqrt(0x8000_0001, m(1)), Some(0x7FC0_0000)); + assert_eq!(ref_sqrt(0x8000_0001, flush(1)), Some(0x8000_0000)); + assert_eq!(ref_sqrt(0xBF80_0000, m(1)), Some(0x7FC0_0000)); + assert_eq!(ref_sqrt(0x8000_0000, m(1)), Some(0x8000_0000)); assert_eq!(ref_cvt_int(0x0100_0001, false, m(1)), 16777218f32.to_bits()); assert_eq!(ref_cvt_int(0x0100_0001, false, m(3)), 16777216f32.to_bits()); // RNE reference agrees with the host on random sums / products @@ -363,7 +368,7 @@ fn directed_reference_basics() { assert!(r == fa.mul_add(fb, fc).to_bits() || is_nan(r), "fma {a:#x} {b:#x} {c:#x}"); } if let Some(r) = ref_sqrt(a, m(0)) { - assert_eq!(r, fa.sqrt().to_bits(), "sqrt {a:#x}"); + assert!(r == fa.sqrt().to_bits() || (is_nan(r) && fa.sqrt().is_nan()), "sqrt {a:#x}"); } // directed results bracket the exact value: RTN ≤ RNE ≤ RTP, RTZ toward zero if let (Some(lo), Some(hi)) = (ref_add(a, b, m(2)), ref_add(a, b, m(1))) { @@ -548,3 +553,96 @@ fn direct_s_setreg_b32_f32_mode_allows_f64_ops() { super::validate::validate(&dxil).unwrap_or_else(|e| panic!("validator (SIMM16={simm:#06x}): {e}")); } } + +/// Static directed `v_sqrt_f32` must not retain a dead native `Sqrt` fallback (needed only for +/// RNE), and `v_mad_f32` must route through `by_mode` (single `native` `mad_nf` under dynamic +/// mode; folds cleanly to `native` under constant RNE). +#[test] +fn direct_f32_round_sqrt_specials_and_mad_dxil_validate() { + let check = |code: &[u8], tag: &str| -> String { + let dxil = runner::direct_kernel(code, true).unwrap_or_else(|e| panic!("{tag}: {e}")); + super::validate::validate(&dxil).unwrap_or_else(|e| panic!("{tag} validate: {e}")); + super::validate::disassemble(&dxil).unwrap_or_else(|e| panic!("{tag} disasm: {e}")) + }; + let sqrt_code = [ + encode("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap(), + encode("V_SQRT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V)], None).unwrap(), + encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap(), + ] + .concat(); + let dis = check(&sqrt_code, "static directed sqrt"); + assert_eq!(dis.matches("dx.op.unary.f32(i32 24,").count(), 1, "expected 1 Sqrt (dead native eliminated):\n{dis}"); + + let mad_dyn = [ + encode("S_SETREG_B32", "ENC_SOPK", &[("SDST", 0), ("SIMM16", 0x0801)], None).unwrap(), + encode("V_MAD_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2)], None).unwrap(), + encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap(), + ] + .concat(); + let dis = check(&mad_dyn, "dynamic mad"); + assert_eq!(dis.matches("fmul float ").count(), 1, "expected 1 native fmul float in dynamic mad:\n{dis}"); + assert_eq!(dis.matches("fadd float ").count(), 1, "expected 1 native fadd float in dynamic mad:\n{dis}"); + + let mad_rne = [ + encode("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap(), + encode("V_ADD_F32", "ENC_VOP2", &[("VDST", 9), ("SRC0", V), ("VSRC1", 1)], None).unwrap(), + encode("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap(), + encode("V_MAD_F32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2)], None).unwrap(), + encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap(), + ] + .concat(); + let dis = check(&mad_rne, "const RNE mad"); + assert_eq!(dis.matches("fmul float ").count(), 1, "expected const RNE mad native fmul:\n{dis}"); + assert_eq!(dis.matches("fadd float ").count(), 1, "expected const RNE mad native fadd:\n{dis}"); + assert_eq!(dis.matches("fmul double ").count(), 0, "expected const RNE mad to fold without f64:\n{dis}"); +} + +/// Directed `v_sqrt_f32` special values on the GPU, including negative preserved denormals +/// (must produce canonical qNaN, not `-0.0` from D3D12 native sqrt flushing) and flushed +/// denormals (`s_denorm_mode 0`), plus `v_mad_f32` preserved `denormal * +inf + 1.0`. +#[test] +fn gpu_direct_f32_round_sqrt_negative_denormals_and_specials() { + if !gpu_ready() { + return; + } + let cases: [u32; 12] = [ + 0x8000_0001, 0x807F_FFFF, 0x0000_0001, 0x0000_0000, 0x8000_0000, 0xBF80_0000, + 0x7F80_0000, 0xFF80_0000, 0x7FC0_0001, 0xFFC0_0001, 0x7F80_0001, 0xFF80_0001, + ]; + for (denorm_imm, keep) in [(3u64, true), (0u64, false)] { + for rm in [1u32, 2, 3] { + let code = [ + encode("S_DENORM_MODE", "ENC_SOPP", &[("SIMM16", denorm_imm)], None).unwrap(), + encode("S_ROUND_MODE", "ENC_SOPP", &[("SIMM16", rm as u64)], None).unwrap(), + encode("V_SQRT_F32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V)], None).unwrap(), + encode("V_MAD_F32", "ENC_VOP3", &[("VDST", 11), ("SRC0", V + 1), ("SRC1", V + 2), ("SRC2", V + 3)], None).unwrap(), + encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap(), + ] + .concat(); + let mut st = KernelState::default(); + for (l, &x) in cases.iter().enumerate() { + st.vgpr[l][0] = x; + } + st.vgpr[0][1] = 0x0000_0001; // +denorm + st.vgpr[0][2] = 0x7F80_0000; // +inf + st.vgpr[0][3] = 0x3F80_0000; // 1.0 + let r = run(&code, &st); + let m = Mode { rm, keep_in: keep, keep_out: keep }; + let want = [ + if keep { 0x7FC0_0000 } else { 0x8000_0000 }, + if keep { 0x7FC0_0000 } else { 0x8000_0000 }, + ref_sqrt(0x0000_0001, m).unwrap(), + 0x0000_0000, 0x8000_0000, 0x7FC0_0000, + 0x7F80_0000, 0x7FC0_0000, 0x7FC0_0000, 0x7FC0_0000, 0x7FC0_0000, 0x7FC0_0000, + ]; + for (l, &w) in want.iter().enumerate() { + assert_eq!(r.vgpr[l][10], w, "rm={rm} keep={keep} lane={l} in={:#010x}: got={:#010x} want={:#010x}", cases[l], r.vgpr[l][10], w); + } + if keep { + assert_eq!(r.vgpr[0][11], 0x7F80_0000, "rm={rm} mad(+denorm, +inf, 1.0) keep=true"); + } else { + assert!(is_nan(r.vgpr[0][11]), "rm={rm} mad(+denorm flushed to 0 * +inf + 1.0) keep=false: got={:#010x}", r.vgpr[0][11]); + } + } + } +} From b5002510c7678c322643ff95046c3e91d034c80f Mon Sep 17 00:00:00 2001 From: joeypercia <81598667+joeypercia@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:32:29 +0100 Subject: [PATCH 097/175] =?UTF-8?q?Recompiler:=20v=5Fldexp=5Ff16=20keeps?= =?UTF-8?q?=20=C2=B10=20and=20=C2=B1inf=20for=20any=20exponent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recompiler: v_ldexp_f16 keeps ±0 and ±inf for any exponent (#658) (840e19aa): v_ldexp_f16 was emitted as HLSL ldexp(x, (float)n), which DXC computes as x * exp2(n). For |n| beyond the f32 exponent range exp2(n) is inf or 0, so ±0 with a large positive n and ±inf with a large negative n gave 0 * inf = NaN (0x7fff on an RTX 4070 Ti, 0xfe00 on an RDNA2 iGPU); the ISA keeps ±0 and ±inf. v_ldexp_f16 now uses the exact ldexp_f helper that v_ldexp_f32 already uses. Fixes #658 Direct DXIL: v_ldexp_f16 keeps ±0 and ±inf for any exponent (32bcaef6): The direct backend computed x * exp2(n) in f32, so 0 with an exponent that overflows exp2 gave 0 * inf = NaN, and inf with a very negative one gave inf * 0 = NaN (both 0x7fff after the f16 conversion). It now uses the exact ldexp_f helper that v_ldexp_f32 uses, like the HLSL path in the previous commit. gpu_ldexp_f16_zero_inf_and_large_exponents with XCL_DIRECT_DXIL=1: 6 of 11 cases wrong before, all pass after, on an RTX 4070 Ti and an RDNA2 iGPU. From xcl-dev/xcl#672 (merge b76563b9). Taken as is. (cherry picked from commit b76563b938dfca2956982281ddbfdc6bed83490c) Assisted-by: Claude Code (Claude Opus 5.5) --- crates/xcl/src/gpu/dxil/lower_wide.rs | 5 ++-- crates/xcl/src/gpu/recomp/emit.rs | 2 +- crates/xcl/src/gpu/recomp/tests.rs | 33 +++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index 7888467060..cbe3365238 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -557,11 +557,10 @@ impl Lw { fr(self, e) } "v_ldexp_f16" => { + // exact on the bits, like v_ldexp_f32: x * exp2(n) gives NaN for 0 * inf and inf * 0 let x = fh(self, 0); let n = si(self, 1); - let nf = self.sitof(n); - let p = self.un(op::EXP, nf); - let e = self.fmul(x, p); + let e = self.ldexp_f(x, n); fr(self, e) } "v_rcp_f16" => f1!(|s: &mut Self, x| { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index c12a11efe1..200cc90f9a 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3765,7 +3765,7 @@ impl Em { "v_fmac_f16" => fr(format!("mad({}, {}, f16tof32({curh}))", fh(0), fh(1))), "v_fmamk_f16" => fr(format!("mad({}, f16tof32({} & 0xFFFFu), {})", fh(0), u[1], fh(2))), "v_fmaak_f16" => fr(format!("mad({}, {}, f16tof32({} & 0xFFFFu))", fh(0), fh(1), u[2])), - "v_ldexp_f16" => fr(format!("ldexp({}, (float){})", fh(0), si(1))), + "v_ldexp_f16" => fr(format!("ldexp_f({}, {})", fh(0), si(1))), "v_rcp_f16" => fr(format!("rcp({})", fh(0))), "v_rsq_f16" => fr(format!("rsqrt({})", fh(0))), "v_sqrt_f16" => fr(format!("sqrt({})", fh(0))), diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index e6e4e8a18f..735ac31b5c 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3627,6 +3627,39 @@ fn gpu_images_a16_d16() { } } +/// v_ldexp_f16 at the edges: ±0 and ±inf keep their value for any exponent (no 0·inf NaN from a +/// 2^n that overflows f32), NaN stays NaN, underflow lands on 0 and exact scalings stay exact +/// (#658). Overflow of a finite value is left out: it depends on the f16 rounding mode (#111). +#[test] +fn gpu_ldexp_f16_zero_inf_and_large_exponents() { + for wave64 in gpu_waves() { + let p = prog(&[("V_LDEXP_F16", "ENC_VOP2", &[("VDST", 10), ("SRC0", V), ("VSRC1", 1)], None)]); + let (dxil, mem) = kernel_wave(&p, wave64); + // (x, n, want) + let cases: [(u16, i16, u16); 11] = [ + (0x0000, 200, 0x0000), (0x8000, 300, 0x8000), (0x0000, 32767, 0x0000), (0x8000, -32768, 0x8000), + (0x7C00, -200, 0x7C00), (0xFC00, -300, 0xFC00), (0x7C00, -32768, 0x7C00), (0x7E00, 5, 0x7E00), + (0x3C00, -30, 0x0000), (0x0001, 10, 0x0400), (0x3C00, 3, 0x4800), + ]; + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let (x, n, _) = cases[l % cases.len()]; + (r[0], r[1], r[10]) = (x as u32, n as u16 as u32, 0); + } + let r = runner::run(&dxil, &st, &mem).unwrap(); + let mut bad = Vec::new(); + for (l, (x, n, want)) in cases.iter().enumerate() { + let got = (r.vgpr[l][10] & 0xFFFF) as u16; + // any NaN encoding counts as NaN + let ok = got == *want || (*want & 0x7C00 == 0x7C00 && *want & 0x3FF != 0 && got & 0x7C00 == 0x7C00 && got & 0x3FF != 0); + if !ok { + bad.push(format!("ldexp_f16({x:#06x}, {n}) = {got:#06x}, want {want:#06x}")); + } + } + assert!(bad.is_empty(), "wave{}: {} of {} wrong\n{}", if wave64 { 64 } else { 32 }, bad.len(), cases.len(), bad.join("\n")); + } +} + /// f32 → IEEE half bits (exact for the small values used in tests). fn half_bits(x: f32) -> u32 { if x == 0.0 { From ce72ad9d8d8409620de84a64f680cc6881156f52 Mon Sep 17 00:00:00 2001 From: luckyteagirl <290248872+luckyteagirl@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:32:37 +0100 Subject: [PATCH 098/175] Direct DXIL: lower i64 min/max as compare/select From xcl-dev/xcl#1946 (merge 2be6c01b). Taken as is. (cherry picked from commit 2be6c01bb55f3a661be45f11da442313c04d52bd) --- crates/xcl/src/gpu/dxil/ops.rs | 12 +++++++++- crates/xcl/src/gpu/dxil/ops_tests.rs | 35 ++++++++++++++++++++++++---- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/ops.rs b/crates/xcl/src/gpu/dxil/ops.rs index 89c9ca0ec0..6a0a4aed75 100644 --- a/crates/xcl/src/gpu/dxil/ops.rs +++ b/crates/xcl/src/gpu/dxil/ops.rs @@ -29,7 +29,7 @@ //! hyperbolic / inverse trig ops, and float division (2.5 ULP). //! `FMad` may or may not be fused: do not rely on either rounding. -use super::module::{BinOp, CastOp, FnAttrs, RmwOp, Ty, Value}; +use super::module::{BinOp, CastOp, FnAttrs, Pred, RmwOp, Ty, Value}; use super::shader::{kind, Feature, RawUav, ResClass, Shader}; // ------------------------------------------------------------------ enums @@ -391,6 +391,16 @@ impl Shader { } if self.is_i64(a) { self.require(Feature::Int64Ops); + // i64 min/max intrinsics remove the RX 6800M device on driver 30.0.13002.13003. + let pred = match op { + Binary::IMax => Pred::SGt, + Binary::IMin => Pred::SLt, + Binary::UMax => Pred::UGt, + Binary::UMin => Pred::ULt, + _ => return self.op(op as u32, "binary", Some(t), t, &[a, b], FnAttrs::ReadNone), + }; + let take_a = self.m.cmp(pred, a, b); + return self.m.select(take_a, a, b); } self.op(op as u32, "binary", Some(t), t, &[a, b], FnAttrs::ReadNone) } diff --git a/crates/xcl/src/gpu/dxil/ops_tests.rs b/crates/xcl/src/gpu/dxil/ops_tests.rs index be6626c964..7589d20b9c 100644 --- a/crates/xcl/src/gpu/dxil/ops_tests.rs +++ b/crates/xcl/src/gpu/dxil/ops_tests.rs @@ -943,6 +943,7 @@ fn double_unary_legality_matches_dxil_tables() { #[test] fn int64_bit_ops_match_cpu() { + const MAX_INPUT: u64 = 0x8000_0000_8000_0000; let mut k = kernel(); let lo = k.input(0); let hi = k.input(1); @@ -959,23 +960,47 @@ fn int64_bit_ops_match_cpu() { } let rev = k.s.bfrev(v); outs.push(k.s.m.cast(CastOp::Trunc, rev, i32)); - let mx = k.s.binary(Binary::UMax, v, h64); - let mx = { let c = k.s.m.const_int(i64, 32); k.s.m.bin(BinOp::LShr, mx, c) }; - outs.push(k.s.m.cast(CastOp::Trunc, mx, i32)); + let signed_bound = k.s.m.const_int(i64, (-7_i64) as u64); + let unsigned_bound = k.s.m.const_int(i64, MAX_INPUT); + for (op, bound) in [ + (Binary::IMax, signed_bound), + (Binary::IMin, signed_bound), + (Binary::UMax, unsigned_bound), + (Binary::UMin, unsigned_bound), + ] { + let result = k.s.binary(op, v, bound); + outs.push(k.s.m.cast(CastOp::Trunc, result, i32)); + let high = k.s.m.bin(BinOp::LShr, result, sh); + outs.push(k.s.m.cast(CastOp::Trunc, high, i32)); + } for (i, &o) in outs.iter().enumerate() { k.out(i as u32, o); } let c = k.finish([32, 1, 1]); - let his: Vec = UVALS.iter().map(|v| v.rotate_right(9) & 0x00ff_ffff).collect(); + let mut his: Vec = UVALS.iter().map(|v| v.rotate_right(9)).collect(); + // Exercise both low-word orderings for equal high words (lanes 4 and 12). + his[4] = (MAX_INPUT >> 32) as u32; let Some(r) = gpu(&c, &mem_of(&[UVALS.to_vec(), his.clone()]), &[], &[]) else { return }; for l in 0..32 { let v = UVALS[l] as u64 | (his[l] as u64) << 32; + let signed = v as i64; + let signed_max = signed.max(-7) as u64; + let signed_min = signed.min(-7) as u64; + let unsigned_max = v.max(MAX_INPUT); + let unsigned_min = v.min(MAX_INPUT); let want = [ v.count_ones(), if v == 0 { u32::MAX } else { v.trailing_zeros() }, if v == 0 { u32::MAX } else { v.leading_zeros() }, v.reverse_bits() as u32, - his[l], + signed_max as u32, + (signed_max >> 32) as u32, + signed_min as u32, + (signed_min >> 32) as u32, + unsigned_max as u32, + (unsigned_max >> 32) as u32, + unsigned_min as u32, + (unsigned_min >> 32) as u32, ]; for (i, &w) in want.iter().enumerate() { assert_eq!(outv(&r, i)[l], w, "i64 op #{i} of {v:#x}"); From 3e6c71a038a4d46dff691b3ea0c9ad91eca21c06 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:33:23 +0100 Subject: [PATCH 099/175] Direct DXIL: reject invalid stage exports and graphics LDS ops Match the HLSL recompiler's stage guards in Lw::export and Lw::ds: - Reject ENC_EXP in compute (res is None) and geometry (geom is Some) entries with "export target" instead of panicking on self.res.expect("res") (compute, en != 0), silently returning Ok (en == 0), or writing kernel-export offsets into the geometry mesh record buffer. - Reject LDS ENC_DS operations in vertex and pixel entries (gfx is Some) with "LDS outside compute" after allowing wave-level ds_swizzle_b32 and ds_bpermute_b32 (and ds_nop), instead of emitting invalid addrspace(3) TGSM ops in graphics DXIL. Part of #1269 From xcl-dev/xcl#2102 (merge 848be4c4). Adapted: the tests' CsInterface / PsInterface take this tree's lds_dwords and early_depth fields, and geometry_export_rejected also accepts, for a split pass with an ES phase, this tree's earlier refusal of it (kernel::translate_geometry with the safe barrier: "split wave64 geometry: the ES phase exchanges at group barriers"), which comes before the export is lowered. The guards themselves as upstream. (cherry picked from commit 848be4c4f68c08ada16d0388b1052a3282183dfc) Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/lower_mem.rs | 135 +++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 736077f99a..fd837bd4ab 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2283,6 +2283,9 @@ impl Lw { } _ => {} } + if self.gfx.is_some() { + return err(d, "LDS outside compute"); + } if f("GDS") != 0 { return err(d, "GDS"); } @@ -2752,6 +2755,9 @@ impl Lw { if self.gfx.is_some() { return self.export_gfx(d, en, tgt, compr, &srcs); } + if self.res.is_none() || self.geom.is_some() { + return err(d, "export target"); + } let act = self.act(); let mut st = Vec::new(); for c in 0..4u64 { @@ -2790,3 +2796,132 @@ impl Lw { }) } } + +#[cfg(test)] +mod stage_guard_tests { + use super::super::kernel::{self, KernelOptions}; + use super::super::validate; + use crate::gpu::dxbc::SigElement; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::{CsInterface, GsInterface, PsInterface, VsInterface}; + + fn prog(list: &[(&str, &str, &[(&str, u64)])]) -> Vec { + let mut out = Vec::new(); + for (name, enc, fields) in list { + out.extend(encode(name, enc, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + out.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + out + } + + fn sig(name: &str, sv: u32, reg: u32) -> SigElement { + SigElement { name: name.into(), index: 0, system_value: sv, component_type: 3, register: reg, mask: 0xF, rw_mask: 0xF, stream: 0 } + } + + fn opts(wave64: bool, split: bool) -> KernelOptions { + KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 } + } + + fn cs_iface() -> CsInterface { + CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1, lds_dwords: 0 } + } + + fn gs_iface(gs_start: Option) -> GsInterface { + GsInterface { + es_inputs: vec![], + es_outputs: vec![sig("SV_Position", 1, 0)], + outputs: vec![sig("SV_Position", 1, 0)], + max_vertex_count: 5, + gs_start, + } + } + + fn vs_iface() -> VsInterface { + VsInterface { inputs: vec![sig("POSITION", 0, 0)], outputs: vec![sig("SV_Position", 1, 0)], attr_base: 4, params: None } + } + + fn ps_iface() -> PsInterface { + PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0x302, attrs: None, early_depth: false } + } + + #[test] + fn compute_export_rejected() { + let cs = cs_iface(); + for en in [0xFu64, 0] { + let code = prog(&[("EXP", "ENC_EXP", &[("TGT", 0), ("EN", en), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)])]); + for wave64 in [false, true] { + let err = kernel::translate_compute(&code, opts(wave64, false), &cs).err().unwrap_or_else(|| panic!("compute EXP en={en:#x} wave64={wave64} unexpectedly succeeded")); + assert!(err.contains("export target"), "compute EXP en={en:#x} wave64={wave64}: {err:?}"); + assert!(!err.contains("panicked"), "compute EXP en={en:#x} wave64={wave64} panicked: {err:?}"); + } + } + } + + #[test] + fn geometry_export_rejected() { + for en in [0xFu64, 0] { + let code = prog(&[("EXP", "ENC_EXP", &[("TGT", 0), ("EN", en), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)])]); + for gs_start in [Some(0), None] { + let gs = gs_iface(gs_start); + for split in [false, true] { + let err = kernel::translate_geometry(&code, opts(true, split), &gs) + .err() + .unwrap_or_else(|| panic!("geometry EXP en={en:#x} gs_start={gs_start:?} split={split} unexpectedly succeeded")); + // (this tree refuses a split pass with an ES phase before it is lowered: + // `kernel::translate_geometry`, with the safe barrier) + let es_refused = split && gs_start != Some(0) && err.contains("split wave64 geometry: the ES phase exchanges at group barriers"); + assert!(err.contains("export target") || es_refused, "geometry EXP en={en:#x} gs_start={gs_start:?} split={split}: {err:?}"); + } + } + } + } + + #[test] + fn graphics_lds_rejected() { + let vs = vs_iface(); + let ps = ps_iface(); + let cases: &[(&str, Vec)] = &[ + ("ds_read_b32", prog(&[("DS_READ_B32", "ENC_DS", &[("ADDR", 0), ("VDST", 1)])])), + ("ds_write_b32", prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)])])), + ("ds_read_b32_gds", prog(&[("DS_READ_B32", "ENC_DS", &[("ADDR", 0), ("VDST", 1), ("GDS", 1)])])), + ]; + for (label, code) in cases { + let vs_err = kernel::translate_vertex(code, opts(true, false), &vs).err().unwrap_or_else(|| panic!("VS {label} unexpectedly succeeded")); + assert!(vs_err.contains("LDS outside compute"), "VS {label}: {vs_err:?}"); + let ps_err = kernel::translate_pixel(code, opts(true, false), &ps).err().unwrap_or_else(|| panic!("PS {label} unexpectedly succeeded")); + assert!(ps_err.contains("LDS outside compute"), "PS {label}: {ps_err:?}"); + } + } + + #[test] + fn valid_stage_ops_still_translate_and_validate() { + let kernel_exp = prog(&[("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)])]); + let dxil = kernel::translate(&kernel_exp, opts(false, false)).expect("kernel EXP"); + validate::validate(&dxil).expect("kernel EXP validate"); + + let compute_lds = prog(&[ + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)]), + ("DS_READ_B32", "ENC_DS", &[("ADDR", 0), ("VDST", 2)]), + ]); + let cs = kernel::translate_compute(&compute_lds, opts(false, false), &cs_iface()).expect("compute LDS"); + validate::validate(&cs.dxil).expect("compute LDS validate"); + + let vs_wave_ds = prog(&[ + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 1), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("DATA0", 1)]), + ("DS_NOP", "ENC_DS", &[]), + ("EXP", "ENC_EXP", &[("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)]), + ]); + let vs = kernel::translate_vertex(&vs_wave_ds, opts(true, false), &vs_iface()).expect("VS wave DS"); + validate::validate(&vs.dxil).expect("VS wave DS validate"); + + let ps_wave_ds = prog(&[ + ("DS_SWIZZLE_B32", "ENC_DS", &[("VDST", 1), ("ADDR", 0), ("OFFSET0", 0x1F), ("OFFSET1", 0x04)]), + ("DS_BPERMUTE_B32", "ENC_DS", &[("VDST", 2), ("ADDR", 0), ("DATA0", 1)]), + ("DS_NOP", "ENC_DS", &[]), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1), ("VM", 1)]), + ]); + let ps = kernel::translate_pixel(&ps_wave_ds, opts(true, false), &ps_iface()).expect("PS wave DS"); + validate::validate(&ps.dxil).expect("PS wave DS validate"); + } +} From cc0f2a7c2c6804a796a572de5c4d0136c7fd655b Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:33:31 +0100 Subject: [PATCH 100/175] Direct DXIL: reload invalidation tracks VOPC SDWA SDST and cache barriers dxil: track VOPC SDWA SDST and buffer/GWS cache barriers in reload::changes (d423c902): reload::changes previously missed two classes of invalidations for cached s_load_dword* available-expression reuse: - VOPC SDWA with SD=1 writes SDST from its extension word (VOPC_VOP_SDWA_SDST_ENC) instead of VCC, which was invisible to d.enc (ENC_VOPC). When such a compare overwrote a cached load's base or offset SGPR, the next s_load_dword* stayed available and returned stale data. Check super::lower::ext_encoding(d) when d.variant == Variant::Sdwa and OR pair(r, 2) into regs whenever SD == 1 and SDST < 128 (excluding NULL = 125). - BUFFER_GL0_INV and BUFFER_GL1_INV use ENC_MUBUF (where writes is false) and DS_GWS_BARRIER was omitted from the barrier list, so none of them invalidated cached scalar loads. Match all cache-invalidation/barrier instructions alongside memory-writing encodings. Add unit tests covering VOPC SDWA SDST (base lo/hi, wave64 pair overlap, SOFFSET, SD=0 and SDST=NULL negative controls), BUFFER_GL0_INV / BUFFER_GL1_INV / DS_GWS_BARRIER (and S_ICACHE_INV control), and an end-to-end direct DXIL disassembly + wave32 GPU execution test. Part of #1401 Part of #1833 From xcl-dev/xcl#2479 (merge 65d33cdc). Taken as is. (cherry picked from commit 65d33cdc83548349aaaa92797eefef3119a67de9) Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/reload.rs | 82 +++++++++++++++++++++++++++++-- 1 file changed, 78 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/reload.rs b/crates/xcl/src/gpu/dxil/reload.rs index 96dfc2cdf1..eadb20f730 100644 --- a/crates/xcl/src/gpu/dxil/reload.rs +++ b/crates/xcl/src/gpu/dxil/reload.rs @@ -123,12 +123,20 @@ fn changes(d: &Decoded) -> (u128, bool) { regs |= pair(r, dwords); } } + // VOPC SDWA with SD=1 writes SDST from its extension word rather than VCC. + if d.variant == rdna2::Variant::Sdwa { + if let Some(e) = super::lower::ext_encoding(d) { + if rdna2::field_value(e, &d.words, "SD") == Some(1) { + if let Some(r) = rdna2::field_value(e, &d.words, "SDST").filter(|&r| r < 128 && r != 125) { + regs |= pair(r, 2); + } + } + } + } } let writes = name.contains("_STORE") || name.contains("_ATOMIC"); - let memory = match d.enc.name { - "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_MIMG" => writes, - _ => matches!(name, "S_BARRIER" | "S_DCACHE_INV" | "S_GL1_INV"), - }; + let memory = matches!(name, "S_BARRIER" | "S_DCACHE_INV" | "S_GL1_INV" | "BUFFER_GL0_INV" | "BUFFER_GL1_INV" | "DS_GWS_BARRIER") + || (writes && matches!(d.enc.name, "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_MIMG" | "ENC_SMEM")); (regs, memory) } @@ -414,4 +422,70 @@ mod tests { } } } + + #[test] + fn vopc_sdwa_sdst_invalidates_address_registers() { + let sdwa = |sd: u64, sdst: u64| -> Vec { + rdna2::encode("V_CMP_EQ_U32", "VOPC_VOP_SDWA_SDST_ENC", &[("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 1), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("SD", sd), ("SDST", sdst)], None).unwrap() + }; + let run = |ld: I, mid: Vec| { + let enc = |(n, e, f): I| rdna2::encode(n, e, f, None).unwrap(); + let code: Vec = [enc(ld), mid, enc(ld), enc(END)].concat(); + let r = analyze(&Cfg::build(&code).unwrap()); + let mut v: Vec<(usize, bool)> = r.at.iter().map(|(&(_, i), l)| (i, l.available)).collect(); + v.sort(); + v + }; + for sdst in [3, 4, 5] { + assert_eq!(run(LOAD, sdwa(1, sdst)), [(0, false), (2, false)], "base SDST=s{sdst}"); + } + let off: I = ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 12), ("SBASE", 2), ("OFFSET", 0), ("SOFFSET", 9)]); + for sdst in [8, 9] { + assert_eq!(run(off, sdwa(1, sdst)), [(0, false), (2, false)], "soffset SDST=s{sdst}"); + } + assert_eq!(run(LOAD, sdwa(0, 4)), [(0, false), (2, true)], "SD=0 writes VCC"); + assert_eq!(run(LOAD, sdwa(1, 125)), [(0, false), (2, true)], "SDST=NULL writes nothing"); + } + + #[test] + fn cache_invalidations_and_gws_barrier_end_available_loads() { + let gl0: I = ("BUFFER_GL0_INV", "ENC_MUBUF", &[]); + let gl1: I = ("BUFFER_GL1_INV", "ENC_MUBUF", &[]); + let gws: I = ("DS_GWS_BARRIER", "ENC_DS", &[("ADDR", 0)]); + for k in [gl0, gl1, gws] { + assert_eq!(loads(&[LOAD, k, LOAD, END]), [(0, false), (2, false)], "{}", k.0); + } + let icache: I = ("S_ICACHE_INV", "ENC_SOPP", &[]); + assert_eq!(loads(&[LOAD, icache, LOAD, END]), [(0, false), (2, true)], "S_ICACHE_INV"); + } + + #[test] + fn vopc_sdwa_sdst_reloads_updated_base_in_direct_dxil() { + use crate::gpu::recomp::runner::{self, KernelState}; + let enc = |(n, e, f): I| rdna2::encode(n, e, f, None).unwrap(); + let ld0: I = ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 12), ("SBASE", 2), ("OFFSET", 0), ("SOFFSET", 125)]); + let ld1: I = ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 13), ("SBASE", 2), ("OFFSET", 0), ("SOFFSET", 125)]); + let sdwa: I = ("V_CMP_EQ_U32", "VOPC_VOP_SDWA_SDST_ENC", &[("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 1), ("SRC0_SEL", 6), ("SRC1_SEL", 6), ("SD", 1), ("SDST", 4)]); + let raw_loads = |prog: &[I]| { + let code: Vec = prog.iter().flat_map(|&i| enc(i)).collect(); + let k = runner::direct_kernel_full(&code, false).expect("direct translation"); + super::super::validate::validate(&k.dxil).expect("valid DXIL"); + let dis = super::super::validate::disassemble(&k.dxil).expect("disassemble"); + (k, dis.lines().filter(|l| l.contains("@dx.op.rawBufferLoad") && l.contains(" = call ")).count()) + }; + let (_, one) = raw_loads(&[ld0, sdwa, END]); + let (k, two) = raw_loads(&[ld0, sdwa, ld1, END]); + assert_eq!(two, one + 1, "SDWA SDST=s4 must force a second rawBufferLoad"); + if runner::wave32_supported() != Ok(true) { + return runner::skip_test("no wave32"); + } + let mut st = KernelState::default(); + for l in 0..32 { + st.vgpr[l][0] = l as u32; + st.vgpr[l][1] = 4; + } + let mem = [0x1111_2222, 0, 0, 0, 0x3333_4444, 0, 0, 0]; + let r = runner::run_with(&k.dxil, &st, &mem, &[], &[]).expect("GPU run"); + assert_eq!((r.sgpr[4], r.sgpr[12], r.sgpr[13]), (0x10, mem[0], mem[4])); + } } From 94dbef89f5260fd9cc86d84df40228eee89a977b Mon Sep 17 00:00:00 2001 From: amazedturnip Date: Sun, 29 Nov 2026 15:33:37 +0100 Subject: [PATCH 101/175] Recompiler: use u128 dependency masks for reload invalidation From xcl-dev/xcl#2761 (merge 0296bed6). Taken as is. (cherry picked from commit 0296bed66f7b4ea1f7b09b8356c72f50516574cb) --- crates/xcl/src/gpu/dxil/reload.rs | 29 ++++++++- .../xcl/src/gpu/dxil/reload_dep_mask_tests.rs | 62 +++++++++++++++++++ 2 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/reload_dep_mask_tests.rs diff --git a/crates/xcl/src/gpu/dxil/reload.rs b/crates/xcl/src/gpu/dxil/reload.rs index eadb20f730..173c96cecb 100644 --- a/crates/xcl/src/gpu/dxil/reload.rs +++ b/crates/xcl/src/gpu/dxil/reload.rs @@ -86,6 +86,13 @@ fn reads(k: &Key, r: u64) -> bool { r == k.0 || r == k.0 + 1 || r == k.1 } +/// One tracked address as a bit-per-register mask: the base pair and the offset register. +/// For the offset sentinel (`125` = no offset register) the bit is still set, matching what +/// `reads` does for such a key. +fn dep_mask(k: &Key) -> u128 { + (1u128 << k.0) | (1u128 << (k.0 + 1)) | (1u128 << k.1) +} + /// What an instruction may change: the SGPRs it may write (a bit each), and whether it may /// write memory or let other threads' writes be seen. Wider than what it does write wherever /// that is not plain from its encoding. @@ -191,14 +198,16 @@ pub fn analyze(cfg: &Cfg) -> Reloads { by_slot[i] = *k; } let n = by_slot.len(); + // one bit per tracked register per address, precomputed once + let deps: Vec = by_slot.iter().map(dep_mask).collect(); // one instruction: kill what it changes, then its own load is there let step = |i: usize, s: &mut Set| { let (regs, memory) = changes(&cfg.insts[i]); if memory { *s = Set::new(n, false); } else if regs != 0 { - for (j, k) in by_slot.iter().enumerate() { - if (0..128).any(|r| regs >> r & 1 != 0 && reads(k, r)) { + for (j, m) in deps.iter().enumerate() { + if regs & m != 0 { s.set(j, false); } } @@ -262,6 +271,10 @@ pub fn analyze(cfg: &Cfg) -> Reloads { out } +#[cfg(test)] +#[path = "reload_dep_mask_tests.rs"] +mod reload_dep_mask_tests; + #[cfg(test)] mod tests { use super::*; @@ -297,6 +310,18 @@ mod tests { assert_eq!(loads(&[LOAD, OTHER, LOAD, OTHER, END]), [(0, false), (1, false), (2, true), (3, true)]); } + /// Two load slots with distinct bases: a write to one base kills only that slot's + /// availability; the other stays available. + #[test] + fn a_write_to_one_slot_base_invalidates_only_that_slot() { + let load_b: I = ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 10), ("OFFSET", 0x80), ("SOFFSET", 125)]); + let base_lo: I = ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 129)]); + assert_eq!( + loads(&[LOAD, load_b, base_lo, LOAD, load_b, END]), + [(0, false), (1, false), (3, false), (4, true)] + ); + } + #[test] fn a_write_to_the_address_registers_or_to_memory_ends_it() { let base_lo: I = ("S_MOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 129)]); diff --git a/crates/xcl/src/gpu/dxil/reload_dep_mask_tests.rs b/crates/xcl/src/gpu/dxil/reload_dep_mask_tests.rs new file mode 100644 index 0000000000..7455fdf7c1 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/reload_dep_mask_tests.rs @@ -0,0 +1,62 @@ +use super::*; + +/// The precomputed u128 dependency mask must agree with the per-register `reads` scan for +/// every tracked address shape, including the `SOFFSET = 125` sentinel (no offset register) +/// and the base pair low/high dwords. +#[test] +fn dep_mask_agrees_with_reads_for_all_tracked_address_shapes() { + let mut keys = Vec::new(); + for base in [0u64, 1, 2, 4, 122, 123] { + for soff in [0u64, 1, 9, 124, 125] { + keys.push((base, soff, 0x40u64, 4u64)); + } + } + for k in &keys { + let m = dep_mask(k); + for r in 0..128u64 { + let bit = (m >> r) & 1 != 0; + assert_eq!(bit, reads(k, r), "key {k:?} register {r}"); + } + if k.1 == 125 { + assert_ne!(m & (1u128 << 125), 0, "sentinel register bit must be set"); + } + } +} + +/// The mask-based invalidation decision must agree with the per-register scan for every +/// (key, changes-mask) pair the analyzer can produce: `regs & dep_mask != 0` iff +/// `(0..128).any(|r| regs >> r & 1 != 0 && reads(k, r))`. `u128::MAX` is included (MOVREL, +/// unknown operand types), as is `0` (no change). +#[test] +fn mask_intersection_matches_per_register_scan() { + let keys: Vec = { + let mut v = Vec::new(); + for base in [0u64, 1, 2, 3, 122, 123] { + for soff in [0u64, 9, 124, 125] { + v.push((base, soff, 0x40u64, 4u64)); + } + } + v + }; + let masks = [ + 0u128, + u128::MAX, + 1u128, + 1u128 << 4, + 1u128 << 5, + 1u128 << 9, + 1u128 << 125, + (1u128 << 4) | (1u128 << 5), + (1u128 << 9) | (1u128 << 10), + (1u128 << 125) ^ (1u128 << 1), + (1u128 << 118) | (1u128 << 119), + ]; + for k in &keys { + let m = dep_mask(k); + for ®s in &masks { + let masked = regs & m != 0; + let scanned = (0..128u64).any(|r| regs >> r & 1 != 0 && reads(k, r)); + assert_eq!(masked, scanned, "key {k:?} regs {regs:#x}"); + } + } +} From 73c0574a315b34e9747e783577de3b50b1667b4a Mon Sep 17 00:00:00 2001 From: luckyteagirl <290248872+luckyteagirl@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:33:52 +0100 Subject: [PATCH 102/175] Direct DXIL: include write address and control in signature dependencies Track each memory write's pointer, value, and control block when computing input-to-output dependencies for dx.viewIdState and PSV0. Preserve the fixed-point traversal merged in #1966. The direct-DXIL source hash from #1947 accounts for the changed output without a manual version bump. Refs #1892 From xcl-dev/xcl#2035 (merge 64eb282f). Taken as is. (cherry picked from commit 64eb282f2d40ec357d9251a9c13f9ed37bb0ffb0) --- crates/xcl/src/gpu/dxil/graphics.rs | 35 +++++----- crates/xcl/src/gpu/dxil/graphics_tests.rs | 80 ++++++++++++++++++++++- crates/xcl/src/gpu/dxil/module.rs | 8 ++- 3 files changed, 99 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/graphics.rs b/crates/xcl/src/gpu/dxil/graphics.rs index 5dcf2f1752..899a884cf9 100644 --- a/crates/xcl/src/gpu/dxil/graphics.rs +++ b/crates/xcl/src/gpu/dxil/graphics.rs @@ -751,22 +751,16 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac ctrl[v].push(a); } } - // Instruction → block. - let mut block_of: HashMap = HashMap::new(); - let mut root_stores: HashMap> = HashMap::new(); + // A load depends on every write to its root, including each write's address + // and the branch that controls whether it happens. + let mut root_stores: HashMap, usize)>> = HashMap::new(); for b in 0..nb { for &i in m.block_insts(Block(b as u32)) { - block_of.insert(i, b); if let InstInfo::Store(p, v) = m.inst_info(i) { - root_stores.entry(root(s, p)).or_default().push(v); + root_stores.entry(root(s, p)).or_default().push((vec![p, v], b)); } - if let InstInfo::Other(ops) = m.inst_info(i) { - // atomics write memory too - if ops.len() >= 2 { - if let Value::Global(_) = root(s, ops[0]) { - root_stores.entry(root(s, ops[0])).or_default().extend_from_slice(&ops[1..]); - } - } + if let InstInfo::Atomic(ops) = m.inst_info(i) { + root_stores.entry(root(s, ops[0])).or_default().push((ops, b)); } } } @@ -817,10 +811,9 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac struct Cx<'a> { s: &'a Shader, - block_of: &'a HashMap, ctrl: &'a Vec>, cond: &'a Vec>, - root_stores: &'a HashMap>, + root_stores: &'a HashMap, usize)>>, in_base: &'a [Option], inputs: &'a [Placed], } @@ -882,24 +875,26 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac } InstInfo::Load(p) => { d.extend(value_deps(cx, p, st)); - if let Some(vs) = cx.root_stores.get(&root(cx.s, p)) { - for &x in vs { - d.extend(value_deps(cx, x, st)); + if let Some(writes) = cx.root_stores.get(&root(cx.s, p)) { + for (operands, block) in writes { + for &x in operands { + d.extend(value_deps(cx, x, st)); + } + d.extend(block_deps(cx, *block, st)); } } } - InstInfo::Other(ops) => { + InstInfo::Atomic(ops) | InstInfo::Other(ops) => { for x in ops { d.extend(value_deps(cx, x, st)); } } InstInfo::Store(..) | InstInfo::Term(..) => {} } - let _ = cx.block_of; Sets::close(&mut st.values, v, d, st.pass, &mut st.grew) } - let cx = Cx { s, block_of: &block_of, ctrl: &ctrl, cond: &cond, root_stores: &root_stores, in_base: &in_base, inputs }; + let cx = Cx { s, ctrl: &ctrl, cond: &cond, root_stores: &root_stores, in_base: &in_base, inputs }; let mut out: HashMap<(u8, u32), BTreeSet> = HashMap::new(); let bases = |p: &[Placed]| -> Vec> { p.iter().map(|e| e.at.map(|(r, c)| r * 4 + c as u32)).collect() }; let (ob, pb) = (bases(outputs), bases(prims)); diff --git a/crates/xcl/src/gpu/dxil/graphics_tests.rs b/crates/xcl/src/gpu/dxil/graphics_tests.rs index 8228f179e2..72ba71ba36 100644 --- a/crates/xcl/src/gpu/dxil/graphics_tests.rs +++ b/crates/xcl/src/gpu/dxil/graphics_tests.rs @@ -3,7 +3,7 @@ //! validator on every emitted shader, and draws on the GPU. use super::*; -use crate::gpu::dxil::module::{BinOp, CastOp, Pred}; +use crate::gpu::dxil::module::{BinOp, CastOp, Pred, RmwOp}; use crate::gpu::dxil::validate; pub(super) fn part<'a>(c: &'a [u8], cc: &[u8; 4]) -> Option<&'a [u8]> { @@ -828,6 +828,84 @@ fn store_all(io: &mut GraphicsIo, s: &mut Shader, stores: &[(Sig, u8, Value)]) { } } +#[test] +fn store_dependency_includes_the_address_input() { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let input = io.input(SigElement::user("INDEX", 0, CompType::U32, 1)); + let output = io.output(SigElement::user("VALUE", 0, CompType::U32, 1)); + let index = io.load_input(&mut s, input, 0, 0); + let i32 = s.m.i32(); + let array = s.m.array(2, i32); + let storage = s.m.alloca(array, 4); + let zero = s.m.i32c(0); + let value = s.m.i32c(7); + let selected = s.m.gep(storage, &[zero, index]); + s.m.store(selected, value, 4); + let first = s.m.gep(storage, &[zero, zero]); + let loaded = s.m.load(first, 4); + io.store_output(&mut s, output, 0, 0, loaded); + + let deps = compute_deps(&s, &io.place(Dir::In), &io.place(Dir::Out), &[]); + assert!(deps.out[&(0, 0)].contains(&0), "output must depend on the store address input"); +} + +#[test] +fn store_dependency_includes_the_store_condition() { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let input = io.input(SigElement::user("CONDITION", 0, CompType::U32, 1)); + let output = io.output(SigElement::user("VALUE", 0, CompType::U32, 1)); + let flag = io.load_input(&mut s, input, 0, 0); + let i32 = s.m.i32(); + let storage = s.m.alloca(i32, 4); + let zero = s.m.i32c(0); + let one = s.m.i32c(1); + s.m.store(storage, zero, 4); + let condition = s.m.cmp(Pred::Eq, flag, one); + let (then_block, join) = (s.m.new_block(), s.m.new_block()); + s.m.cond_br(condition, then_block, join); + s.m.set_block(then_block); + s.m.store(storage, one, 4); + s.m.br(join); + s.m.set_block(join); + let loaded = s.m.load(storage, 4); + io.store_output(&mut s, output, 0, 0, loaded); + + let deps = compute_deps(&s, &io.place(Dir::In), &io.place(Dir::Out), &[]); + assert!(deps.out[&(0, 0)].contains(&0), "output must depend on the store condition input"); +} + +#[test] +fn atomic_dependency_includes_address_and_condition_inputs() { + let mut s = Shader::new(Stage::Vertex, (6, 6)); + let mut io = GraphicsIo::new(Stage::Vertex); + let input = io.input(SigElement::user("CONTROL", 0, CompType::U32, 2)); + let output = io.output(SigElement::user("VALUE", 0, CompType::U32, 1)); + let index = io.load_input(&mut s, input, 0, 0); + let gate = io.load_input(&mut s, input, 0, 1); + let i32 = s.m.i32(); + let array = s.m.array(2, i32); + let storage = s.m.global("scratch", array, 3, None, false, 4); + let zero = s.m.i32c(0); + let one = s.m.i32c(1); + let selected = s.m.gep(storage, &[zero, index]); + let condition = s.m.cmp(Pred::Eq, gate, one); + let (then_block, join) = (s.m.new_block(), s.m.new_block()); + s.m.cond_br(condition, then_block, join); + s.m.set_block(then_block); + s.m.atomic_rmw(RmwOp::Add, selected, one); + s.m.br(join); + s.m.set_block(join); + let first = s.m.gep(storage, &[zero, zero]); + let loaded = s.m.load(first, 4); + io.store_output(&mut s, output, 0, 0, loaded); + + let deps = compute_deps(&s, &io.place(Dir::In), &io.place(Dir::Out), &[]); + assert!(deps.out[&(0, 0)].contains(&0), "output must depend on the atomic address input"); + assert!(deps.out[&(0, 0)].contains(&1), "output must depend on the atomic condition input"); +} + /// `tests/data/dxil/dxc_vs_clip.hlsl`: clip and cull distances (two clip elements /// sharing a row), `SV_ViewportArrayIndex`. fn vs_clip() -> Vec { diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 2ca2350f8d..5ee96b0bc0 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -1531,6 +1531,8 @@ pub enum InstInfo<'a> { Phi(&'a [(Value, Block)]), Load(Value), Store(Value, Value), + /// An atomic write: pointer and value operands. + Atomic(Vec), /// Any other value-producing instruction with its value operands. Other(Vec), /// A terminator: condition operand (if any) and successors. @@ -1554,8 +1556,8 @@ impl Module { Op::Cast(_, v, _) | Op::Extract(v, _) => InstInfo::Other(vec![*v]), Op::Select(c, t, f) => InstInfo::Other(vec![*c, *t, *f]), Op::Gep(p, idx) => InstInfo::Other(std::iter::once(*p).chain(idx.iter().copied()).collect()), - Op::AtomicRmw(_, p, v) => InstInfo::Other(vec![*p, *v]), - Op::CmpXchg(p, c, n) => InstInfo::Other(vec![*p, *c, *n]), + Op::AtomicRmw(_, p, v) => InstInfo::Atomic(vec![*p, *v]), + Op::CmpXchg(p, c, n) => InstInfo::Atomic(vec![*p, *c, *n]), Op::Alloca(..) => InstInfo::Other(Vec::new()), Op::Br(b) => InstInfo::Term(None, vec![*b]), Op::CondBr(c, t, f) => InstInfo::Term(Some(*c), vec![*t, *f]), @@ -1596,7 +1598,7 @@ impl Module { InstInfo::Phi(l) => l.iter().map(|p| p.0).collect(), InstInfo::Load(p) => vec![p], InstInfo::Store(p, v) => vec![p, v], - InstInfo::Other(v) => v, + InstInfo::Atomic(v) | InstInfo::Other(v) => v, InstInfo::Term(c, _) => c.into_iter().collect(), }; ops.into_iter().any(|v| self.value_ty(v) == t) From 6c27cf1f4bec88be7beb58ea0d38b0f55bc3dc4d Mon Sep 17 00:00:00 2001 From: emirduran707 Date: Sun, 29 Nov 2026 15:34:38 +0100 Subject: [PATCH 103/175] Direct DXIL: sign-extend D16 image_store halves for SINT textures `image_store` with D16 unpacked each 16-bit half with `& 0xFFFF` and passed it unchanged to the `RWTexture` store for SINT formats, so a negative half such as -1 (0xFFFF) became 65535 and the R16 SINT store clamped it to 32767. Sign-extend the half when the T# format class is SINT, as the D16 `buffer_store_format_*` path in `lower_mem.rs` already does. From xcl-dev/xcl#1920 (merge a7dac488). It conflicted when applied alone to the stack; on top of the #1870 port it applies without changes. (cherry picked from commit a7dac4883dae4fcb03db316a94af30e75d5248e2) Assisted-by: Antigravity (Gemini 4 Neon, Claude Opus 5.5) --- crates/xcl/src/gpu/dxil/core_tests.rs | 33 ++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_image.rs | 6 ++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 76bf061906..62db824d04 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -752,6 +752,39 @@ fn v_cvt_f16_int_decodes_inline_float_constants_as_f32() { } } +/// `image_store` with D16 on a SINT texture sign-extends each half: -1 stays -1 instead of +/// becoming 65535 (clamped to 32767 by the R16 SINT store). +#[test] +fn gpu_direct_image_store_d16_sint_sign_extends() { + use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_SINT; + // T# s[16:23] (SRSRC 4): 2D 16_16_16_16_SINT (format 70); lane 0 stores texel (0, 0) + let code = prog(&[ + ("V_CMPX_EQ_U32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 0)], None), + ("IMAGE_STORE", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0xF), ("DIM", 1), ("UNORM", 1), ("D16", 1)], None), + ]); + let k = runner::direct_kernel_full(&code, true).unwrap_or_else(|e| panic!("direct translation: {e}")); + super::validate::validate(&k.dxil).unwrap_or_else(|e| panic!("validator: {e}")); + if runner::adapter().is_err() || runner::wave64_programs_supported() != Ok(true) || crate::gpu::recomp::dxc::location().is_err() { + runner::skip_test("no GPU / DXC / wave64"); + return; + } + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&[0, 70 << 20, 0, 9 << 28, 0, 0, 0, 0]); + let h = |v: i16| v as u16 as u32; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = l as u32; + r[1] = 0; + r[10] = h(-1) | h(-100) << 16; + r[11] = h(42) | h(-32768) << 16; + } + let tex = TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R16G16B16A16_SINT, width: 4, height: 4, depth: 1, texel_bytes: 8, data: vec![0; 128], uav: true }; + let res = runner::run_with_statics(&k.dxil, &st, &[], &[tex], &[], &k.static_samplers).expect("GPU run"); + let t: Vec = res.textures[0].chunks(2).map(|c| i16::from_le_bytes(c.try_into().unwrap())).collect(); + assert_eq!(&t[..4], &[-1, -100, 42, -32768], "texel (0, 0) after a D16 IMAGE_STORE on a SINT texture"); + assert!(t[4..].iter().all(|&v| v == 0), "only texel (0, 0) is written"); +} + /// Without a program-set `MODE[3:2]`, `v_cvt_f16_f32`, `v_mul_f16` and `v_pk_mul_f16` /// must round to nearest-even (matching RDNA2 and the HLSL path) rather than using /// `dx.op.legacyF32ToF16` (which rounds toward zero / flushes below the smallest f16 denormal). diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index fbdb618c7b..4dd98fc949 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -1686,8 +1686,12 @@ impl Lw { let hp = self.andc(hp, 0xFFFF); let fh = self.s.f16_to_f32(hp); let fb = self.bits(fh); + // SINT (cls 2) halves are signed 16-bit integers + let sx = self.sx16(hp); + let si = self.cmpc(Pred::Eq, cls, 2); + let iv = self.sel(si, sx, hp); let fl = self.cmpc(Pred::Eq, cls, 0); - self.sel(fl, fb, hp) + self.sel(fl, fb, iv) } else { self.vreg(vdata + k as u64) }; From 942072bcc0e444402df3c04d9ae2dc6884efa79b Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:38:10 +0100 Subject: [PATCH 104/175] Direct DXIL: pixel-shader lane-mask SCC tests count live lanes only dxil: prefer live lanes in PS v_readfirstlane and lane-mask SCC tests (de915b5a): Bring the direct DXIL pixel-shader lowering into parity with the HLSL recompiler's live-lane handling for helper lanes under s_wqm: - lanes.rs: add Lw::is_pixel (reused in ballot and rla) and Lw::live_lanes (WaveActiveBallot(true), selecting the active half in wave32-in-64 mode). Update Lw::first_lane so pixel shaders intersect EXEC with live lanes before firstbitlow when any live lane is set, falling back to the raw mask otherwise (parity with first_lane_live). - lower.rs: add Lw::ps_mask_live_scc and mask only the SCC zero-check (leaving the destination register unmasked) for pixel-shader ENC_SOP2 s_and_b32 / s_andn2_b32 / s_and_b64 / s_andn2_b64 instructions that reference VCC (106) or EXEC (126) (parity with mask_live, extended to 64-bit masks). - lanes.rs (ps_ballot_tests): add DXC-validated disassembly tests with non-mask and compute negative controls plus a two-triangle edge GPU test covering v_readfirstlane, helper-only s_andn2 SCC, unmasked destination preservation, and the 6-pass march loop shape. Part of #675 Part of #1401 Part of #1833 From xcl-dev/xcl#2501 (merge c18a3b8d). Adapted: the v_readfirstlane half is already in this tree (amd-dev 1dc3cf5e, Lw::first_lane_live), so first_lane is left as it is and the PR's Lw::live_lanes is not added; the SCC test of a pixel shader's s_and* / s_andn2* on VCC / EXEC (Lw::ps_mask_live_scc) takes its live lanes from the existing Lw::ballot_live (now pub(crate)). Lw::is_pixel is added for it; the PR's other uses of is_pixel (ballot, rla) are left out. The PR's tests are kept, the readfirstlane one checking 1dc3cf5e's form. In direct_ps_mask_and_scc_counts_live_lanes_only the instruction the branch skips is a V_MOV_B32 of an exported register and the select fold is off (module::NO_SELECT_FOLD) for its translation: this tree's optimizer folds an empty or if-converted block into its join, and the two identical live ballots then share a block and merge, so the count no longer told the cases apart. (cherry picked from commit c18a3b8ddb06c2013b783db0df591ec31920c671) Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/lanes.rs | 127 ++++++++++++++++++++++++++++++- crates/xcl/src/gpu/dxil/lower.rs | 25 +++++- 2 files changed, 150 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 51956911da..576116a43f 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -690,6 +690,11 @@ impl Lw { self.sel(same, own, other) } + /// Whether this shader is a pixel shader (has helper lanes under `s_wqm`). + pub fn is_pixel(&self) -> bool { + self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) + } + /// The program's ballot of `cond` → (lo, hi) mask words. pub fn ballot(&mut self, cond: Value) -> (Value, Value) { if self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) { @@ -958,7 +963,7 @@ impl Lw { } /// Hardware live-lane ballot (excludes pixel-shader helper lanes, unlike [`Lw::ballot`]). - fn ballot_live(&mut self, cond: Value) -> (Value, Value) { + pub(crate) fn ballot_live(&mut self, cond: Value) -> (Value, Value) { let w = self.s.wave_ballot(cond); if !self.wave64 { let z = self.c(0); @@ -1245,4 +1250,124 @@ mod ps_ballot_tests { ); } } + + #[test] + fn direct_ps_readfirstlane_filters_exec_by_live_lanes() { + let (psi, ins) = (ps_interface(), |n, e, f: &[(&str, u64)]| encode(n, e, f, None).unwrap()); + for wave64 in [false, true] { + let ps = [ + ins(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 2)]), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 4)]), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 3), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1), ("VM", 1)]), + ins("S_ENDPGM", "ENC_SOPP", &[]), + ].concat(); + let k = kernel::translate_pixel(&ps, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS"); + validate::validate(&k.dxil).expect("validate PS"); + let dis = validate::disassemble(&k.dxil).expect("disassemble PS"); + let sels: Vec<&str> = dis.lines().filter(|l| l.contains(" = select i1 ")).collect(); + let fbl_from_sel = dis.lines().any(|l| { + l.contains("@dx.op.unaryBits.i32(i32 32, i32 ") && sels.iter().any(|s| s.split('=').next().is_some_and(|v| l.contains(&format!(", i32 {})", v.trim())))) + }); + assert!(fbl_from_sel, "wave64 {wave64}: PS first_lane must select live-masked EXEC before firstbitlow:\n{dis}"); + } + let cs = [ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V)]), ins("S_ENDPGM", "ENC_SOPP", &[])].concat(); + let kc = runner::direct_kernel_full(&cs, false).expect("translate CS"); + validate::validate(&kc.dxil).expect("validate CS"); + assert!(!validate::disassemble(&kc.dxil).unwrap().contains("dx.op.waveActiveBallot(i32 116, i1 true)")); + } + + #[test] + fn direct_ps_mask_and_scc_counts_live_lanes_only() { + let (psi, ins) = (ps_interface(), |n, e, f: &[(&str, u64)]| encode(n, e, f, None).unwrap()); + let ballots = |dis: &str| dis.matches("dx.op.waveActiveBallot(i32 116, i1 true)").count(); + for (wave64, op, dst, s0, s1, want) in [ + (false, "S_ANDN2_B32", 10, 10, 106, 2), (false, "S_AND_B32", 10, 10, 126, 2), + (false, "S_AND_B32", 125, 10, 126, 2), (true, "S_ANDN2_B64", 10, 10, 106, 2), + (false, "S_AND_B32", 10, 10, 143, 1), // non-mask SGPR op: entry EXEC ballot only + ] { + let c = [ + ins(if wave64 { "S_MOV_B64" } else { "S_MOV_B32" }, "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)]), + ins(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), + ins("V_CMP_LT_F32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 2)]), + // Split basic block so block-local CSE keeps `op`'s live-lane ballot distinct from entry EXEC + // (the skipped write is exported and the select fold is off: the optimizer merges an + // empty or folded block into its join) + ins("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)]), + ins("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 242)]), + ins(op, "ENC_SOP2", &[("SDST", dst), ("SSRC0", s0), ("SSRC1", s1)]), + ins("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 129), ("SSRC1", 128)]), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 11)]), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 3), ("VSRC2", 2), ("VSRC3", 5), ("DONE", 1), ("VM", 1)]), + ins("S_ENDPGM", "ENC_SOPP", &[]), + ].concat(); + crate::gpu::dxil::module::NO_SELECT_FOLD.with(|c| c.set(true)); + let k = kernel::translate_pixel(&c, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi); + crate::gpu::dxil::module::NO_SELECT_FOLD.with(|c| c.set(false)); + let k = k.expect("translate PS"); + validate::validate(&k.dxil).expect("validate PS"); + let dis = validate::disassemble(&k.dxil).expect("disassemble PS"); + assert_eq!(ballots(&dis), want, "wave64 {wave64} {op} dst={dst} s1={s1}:\n{dis}"); + } + let cs = [ins("S_ANDN2_B32", "ENC_SOP2", &[("SDST", 10), ("SSRC0", 10), ("SSRC1", 106)]), ins("S_ENDPGM", "ENC_SOPP", &[])].concat(); + let kc = runner::direct_kernel_full(&cs, false).expect("translate CS"); + validate::validate(&kc.dxil).expect("validate CS"); + assert_eq!(ballots(&validate::disassemble(&kc.dxil).unwrap()), 0); + } + + #[test] + fn gpu_direct_ps_readfirstlane_and_mask_live_on_triangle_edges() { + match (runner::adapter(), runner::wave32_supported(), dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, w, d) => return runner::skip_test(if a.is_err() || w.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave32" }), + } + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + let (psi, ins) = (ps_interface(), |n, e, f: &[(&str, u64)], x| encode(n, e, f, x).unwrap()); + let (quad, layout) = ([-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0], [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]); + for &wave64 in if runner::wave64_programs_supported() == Ok(true) { &[false, true][..] } else { &[false][..] } { + let (mov, wqm, and, andn2, or, xor) = if wave64 { ("S_MOV_B64", "S_WQM_B64", "S_AND_B64", "S_ANDN2_B64", "S_OR_B64", "S_XOR_B64") } else { ("S_MOV_B32", "S_WQM_B32", "S_AND_B32", "S_ANDN2_B32", "S_OR_B32", "S_XOR_B32") }; + let march = [ + ins("V_ADD_F32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 242), ("VSRC1", 9)], None), + ins("S_ADD_U32", "ENC_SOP2", &[("SDST", 8), ("SSRC0", 8), ("SSRC1", 129)], None), + ins("V_CMP_LE_F32", "ENC_VOPC", &[("SRC0", 255), ("VSRC1", 9)], Some(0x40C0_0000)), + ins(andn2, "ENC_SOP2", &[("SDST", 14), ("SSRC0", 14), ("SSRC1", 106)], None), + ].concat(); + let back = (-((march.len() as i64 + 4) / 4)) as u16 as u64; + let c = [ + ins(mov, "ENC_SOP1", &[("SDST", 20), ("SSRC0", 126)], None), + ins(wqm, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 242)], None), // helpers = 1.0 + ins(mov, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 20)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 244)], None), // live = 2.0 + ins(wqm, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 20)], None), + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 4)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 4)], None), + // s[10:11] = EXEC & ~live (helper bits only): SCC must be 0, while dst preserves helper bits. + ins(andn2, "ENC_SOP2", &[("SDST", 10), ("SSRC0", 126), ("SSRC1", 20)], None), + ins("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 16), ("SSRC0", 129), ("SSRC1", 128)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 6), ("SRC0", 16)], None), + ins(or, "ENC_SOP2", &[("SDST", 12), ("SSRC0", 10), ("SSRC1", 20)], None), + ins(xor, "ENC_SOP2", &[("SDST", 12), ("SSRC0", 12), ("SSRC1", 126)], None), + ins("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 17), ("SSRC0", 128), ("SSRC1", 129)], None), + ins(and, "ENC_SOP2", &[("SDST", 14), ("SSRC0", 20), ("SSRC1", 126)], None), + ins("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 18), ("SSRC0", 17), ("SSRC1", 128)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 18)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 128)], None), + ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 128)], None), + ins(mov, "ENC_SOP1", &[("SDST", 14), ("SSRC0", 126)], None), + march, + ins("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", back)], None), + ins(mov, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 20)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 8)], None), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 5), ("VSRC1", 6), ("VSRC2", 7), ("VSRC3", 8), ("DONE", 1), ("VM", 1)], None), + ins("S_ENDPGM", "ENC_SOPP", &[], None), + ].concat(); + let ps = kernel::translate_pixel(&c, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS"); + let px = runner::draw(&vs, &ps.dxil, &layout, &quad, 8, &[], &[], 32, [9.0; 4]).unwrap(); + let bad: Vec<(usize, usize, [f32; 4])> = (0..1024).filter(|&i| px[i] != [2.0, 0.0, 1.0, 6.0]).map(|i| (i % 32, i / 32, px[i])).collect(); + assert!(bad.is_empty(), "wave64 {wave64}: {} of 1024 pixels wrong, first {:?}", bad.len(), &bad[..bad.len().min(6)]); + } + } } diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 0dd2a1dd76..620cf3ff06 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -1630,7 +1630,14 @@ impl Lw { match scc { Scc::No => {} Scc::Nz => { - let c = self.nz(res); + let v = if self.ps_mask_live_scc(d, name) { + let t = self.s.m.i1c(true); + let (lv, _) = self.ballot_live(t); + self.and(res, lv) + } else { + res + }; + let c = self.nz(v); self.set_scc(c); } Scc::Is(c) => self.set_scc(c), @@ -1639,6 +1646,15 @@ impl Lw { Ok(()) } + /// Whether a pixel-shader `s_and*` / `s_andn2*` operates on a lane mask (`VCC` / `EXEC`), + /// so its `SCC` should test live lanes only (parity with HLSL `mask_live` in `recomp/emit.rs`). + fn ps_mask_live_scc(&self, d: &Decoded, name: &str) -> bool { + self.is_pixel() + && d.enc.name == "ENC_SOP2" + && matches!(name, "s_and_b32" | "s_andn2_b32" | "s_and_b64" | "s_andn2_b64") + && ["SSRC0", "SSRC1", "SDST"].iter().any(|f| matches!(Self::field(d, f), 106 | 126)) + } + fn smovrel(&mut self, d: &Decoded, name: &str) -> LResult<()> { let dst = Self::field(d, "SDST"); let src = Self::field(d, "SSRC0"); @@ -1872,6 +1888,13 @@ impl Lw { if nz { let c = if one_word { self.nz(lo) + } else if self.ps_mask_live_scc(d, name) { + let t = self.s.m.i1c(true); + let (lv_lo, lv_hi) = self.ballot_live(t); + let ml = self.and(lo, lv_lo); + let mh = self.and(hi, lv_hi); + let o = self.or(ml, mh); + self.nz(o) } else { let o = self.or(lo, hi); self.nz(o) From 6f954bcb6ea43bf1138de25796f9d59cc0b90218 Mon Sep 17 00:00:00 2001 From: nathan Date: Sun, 29 Nov 2026 15:45:38 +0100 Subject: [PATCH 105/175] D3D12.X: remap superseded targets bound through descriptor tables A target superseded by a newer overlapping placement (5d00b390) had its tiles unmapped (D3D12_TILE_RANGE_FLAG_NULL) and was only remapped by placements::note_use on ResourceBarrier or Copy* calls. Compute and graphics passes that bind a UAV/SRV texture through descriptor tables without a per-resource barrier (e.g. global UAV barriers) left the target unmapped, silently dropping UAV writes and returning zeros on reads. Also avoid superseding a live target when a newer placement at the exact same VA has the same texels (e.g. an R9G9B9E5 sampled alias over an R32_UINT UAV target whose owned page range differs by a trailing page). In bind_abi, scan descriptor table slots and call placements::note_use only when placements::any_superseded() is true (single relaxed atomic load on the fast path). From xcl-dev/xcl#3179 (merge b0b61696). Adapted: bind.rs conflicted (this tree's bind_abi is not split into bind_abi_with_root_resolved, and XCL_TRACE_SLOT's trace_table_slot sits where the new function went). note_superseded_in_tables is added beside it and called in bind_abi right after want_root_views, as upstream calls it there; a table outside the committed window is read with title_textures::copy_readable (pub(super) here; upstream's read_committed_into is private in this tree). placements.rs applied as is. (cherry picked from commit b0b6169685f747c5c924572914db56b0cb8c66ea) Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/hle/d3d12x/bind.rs | 36 ++++++++++++++++ crates/xcl/src/hle/d3d12x/placements.rs | 55 ++++++++++++++++++++++++- 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index bf1c9eba20..606bc2adfe 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -547,6 +547,39 @@ pub(super) fn bound_pso(this: *mut c_void) -> usize { with(this, |s| s.pso) } +/// Remap any superseded targets named in the first 256 slots of each descriptor table in `layout` +/// / `args`. Only called when `placements::any_superseded()` is true. +unsafe fn note_superseded_in_tables(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8]) { + let Some(layout) = layout else { return }; + const TABLE_SLOTS: usize = 256; + let mut table = [0u8; TABLE_SLOTS * 32]; + for p in &layout.params { + let Param::Table { at } = *p else { continue }; + let at = at as usize; + let Some(word) = args.get(at..at + 4) else { continue }; + let offset = u32::from_le_bytes(word.try_into().unwrap()) as usize; + if offset == 0 { + continue; + } + let addr = u.base() + offset; + if u.in_committed_window(addr, table.len()) { + std::ptr::copy_nonoverlapping(addr as *const u8, table.as_mut_ptr(), table.len()); + } else { + super::title_textures::copy_readable(addr, &mut table); + } + for slot in table.chunks_exact(32) { + let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); + if slot[15] >> 4 < 8 || index == 0 { + continue; + } + let res = super::console_heap::named_by_index(index); + if res != 0 && res != super::console_heap::GONE { + super::placements::note_use(res); + } + } + } +} + /// `XCL_TRACE_SLOT=`: the image views at that place of the descriptor tables of graphics /// draws – each resource once (the first 64), with its description and the view's words. Places /// that hold no image view (another table's layout) are passed over. @@ -4512,6 +4545,9 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi if gfx { trace_table_slot(u, layout.as_deref(), &args, pso); } + if super::placements::any_superseded() { + note_superseded_in_tables(u, layout.as_deref(), &args); + } // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) let copy = |bytes: &[u8]| -> Result { let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or_else(|| { diff --git a/crates/xcl/src/hle/d3d12x/placements.rs b/crates/xcl/src/hle/d3d12x/placements.rs index 696e9dcfe5..5dda38c2d4 100644 --- a/crates/xcl/src/hle/d3d12x/placements.rs +++ b/crates/xcl/src/hle/d3d12x/placements.rs @@ -61,6 +61,16 @@ impl Desc { pub(super) fn of(d: &D3D12_RESOURCE_DESC) -> Desc { Desc { width: d.Width, height: d.Height, depth: d.DepthOrArraySize, mips: d.MipLevels, format: d.Format.0, flags: d.Flags.0 } } + + /// Whether a reserved texture of this description has the texels of one of `other`'s on the + /// same tiles: the same size and levels and a texel of the same size (e.g. R9G9B9E5 sampled + /// over an R32_UINT UAV target). + pub(super) fn same_texels(&self, other: &Desc) -> bool { + let plain = |f: i32| !matches!(f, 0 | 5..=8 | 66 | 68..=84 | 94..=99) && f < 100; + let texel = |f: i32| super::targets::texel_bytes(windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f)); + (self.width, self.height, self.depth, self.mips) == (other.width, other.height, other.depth, other.mips) + && (self.format == other.format || (plain(self.format) && plain(other.format) && texel(self.format) == texel(other.format))) + } } impl std::fmt::Display for Desc { @@ -225,7 +235,8 @@ impl Registry { let mut out = Placed { seq: self.seq, remap, ..Default::default() }; for &(o, overlap) in &found { let Some(old) = self.live.get_mut(&o) else { continue }; - let retired = retire && supersedes(overlap, old.kind, old.backing, old.released, old.mapped); + let same_view = p.desc.format != 0 && p.va == old.va && p.desc.same_texels(&old.desc); + let retired = retire && !same_view && supersedes(overlap, old.kind, old.backing, old.released, old.mapped); if look { out.cases.push(Case { old: o, @@ -527,7 +538,12 @@ pub(super) unsafe fn unmap_if_superseded(res: &ID3D12Resource) { } } -/// The title uses `res` (a barrier, a copy): a superseded target goes back on the shared pages – +/// Whether any live target is currently superseded (`SUPERSEDED != 0`). +pub(super) fn any_superseded() -> bool { + SUPERSEDED.load(Ordering::Relaxed) != 0 +} + +/// The title uses `res` (a barrier, a copy, or a descriptor table): a superseded target goes back on the shared pages – /// on the console the title may use both over one memory when it knows they share it. Logged /// once for each pair (the first 64). The work recorded now waits for the mapping /// (`vram::before_execute` at its submit). @@ -778,4 +794,39 @@ mod tests { assert!(r.use_again(1).is_empty(), "released"); assert!(r.remove(3).unwrap().is_empty()); } + + /// A sampled alias at the same address with the same texels (e.g. R9G9B9E5 over an R32_UINT + /// UAV target) must not supersede the target even when their owned page ranges differ by a + /// trailing page. + #[test] + fn same_address_same_texels_alias_pair_does_not_supersede() { + let mut r = Registry::default(); + let at = 0x10_7720_7400usize; + let p0 = at.next_multiple_of(K64); + let d = |format: i32, flags: i32| Desc { width: 640, height: 360, depth: 1, mips: 1, format, flags }; + let out_uav = r.place(1, at, (p0, p0 + 14 * K64), Backing::Pages(1), Kind::Target, d(42, 4), Instant::now(), false, true); + assert!(out_uav.victims.is_empty()); + let out_srv = r.place(2, at, (p0, p0 + 15 * K64), Backing::Pages(1), Kind::Sampled, d(67, 0), Instant::now(), false, true); + assert!(out_srv.victims.is_empty(), "same-VA same-texels alias must not supersede its UAV target"); + assert!(!r.superseded(1)); + assert_eq!(r.unmapped, 0); + } + + /// A target superseded by a newer overlapping placement at another address is remapped when + /// used again (e.g. via descriptor-table binding). + #[test] + fn superseded_target_remaps_on_use_again() { + let mut r = Registry::default(); + let at = 0x10_b69b_c200usize; + let p0 = at.next_multiple_of(K64); + let d = |format: i32| Desc { width: 480, height: 272, depth: 1, mips: 1, format, flags: 4 }; + r.place(10, at, (p0, p0 + 7 * K64), Backing::Pages(1), Kind::Target, d(24), Instant::now(), false, true); + let out = r.place(11, at - 0x7_f800, (p0 - 7 * K64, p0 + K64), Backing::Pages(1), Kind::Target, d(42), Instant::now(), false, true); + assert_eq!(out.victims, vec![10]); + assert!(r.superseded(10)); + assert_eq!(r.unmapped, 1); + assert_eq!(r.use_again(10), vec![11]); + assert!(!r.superseded(10)); + assert_eq!(r.unmapped, 0); + } } From a94353a3f80fd1f00e2b3512bed0d8c413359a16 Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:46:19 +0100 Subject: [PATCH 106/175] D3D12.X: the same root signature set again keeps the root arguments SetComputeRootSignature / SetGraphicsRootSignature zeroed the root arguments on every call. In D3D12 a redundant set of the same root signature leaves the existing bindings valid; only a different one makes them stale. A title that sets the same signature again and then binds only some parameters left the others at address 0 in the translated shader's argument table. The arguments are now cleared only when the layout is not the one already set (compared as the same layout object, so a signature made at a freed one's address still clears). The console list replay does the same. Reset and ClearState still clear everything. From xcl-dev/xcl#2504 (merge 94134c73). Adapted: bind.rs conflicted around the test (upstream tests this tree does not have); the two root-signature setters are changed as upstream and the test goes after reset_and_clear_state_track_initial_pso_and_clear_root_args. console_list.rs applied as is. (cherry picked from commit 94134c73797dfa9d73cd24f013305e44eb6dca01) --- crates/xcl/src/hle/d3d12x/bind.rs | 54 ++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/console_list.rs | 17 ++++++- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 606bc2adfe..8e2750dad6 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -856,7 +856,11 @@ pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_vo let _c = super::capture::op(this, || Some(super::capture::Op::RootSig { gfx: true, rs: rs as usize })); let layout = console_list::layout_of(rs as usize); with(this, |s| { - s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + // the same root signature again keeps the bound arguments (D3D12: only a different + // one invalidates them) + if !console_list::same_layout(&s.layout_gfx, &layout) { + s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + } s.layout_gfx = layout; s.rs_gfx = rs as usize; }); @@ -3937,7 +3941,9 @@ pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_voi let _c = super::capture::op(this, || Some(super::capture::Op::RootSig { gfx: false, rs: rs as usize })); let layout = console_list::layout_of(rs as usize); with(this, |s| { - s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + if !console_list::same_layout(&s.layout, &layout) { + s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + } s.layout = layout; }); } @@ -4939,6 +4945,50 @@ void main(uint t : SV_GroupIndex) { forget(list); } + #[test] + fn the_same_root_signature_again_keeps_the_root_arguments() { + let list = 0x7100_0301usize as *mut c_void; + let (rs_a, rs_b) = (0x7100_0310usize, 0x7100_0320usize); + console_list::note_root_signature(rs_a, &test_rts0_blob()); + console_list::note_root_signature(rs_b, &test_rts0_blob()); + let set = |gfx: bool, rs: usize| unsafe { + if gfx { set_graphics_root_signature(list, rs as *mut c_void) } else { set_compute_root_signature(list, rs as *mut c_void) } + }; + let args = |gfx: bool| with(list, |s| if gfx { s.args_gfx.clone() } else { s.args.clone() }); + reset(list, 0x7100_0330, 0); + set(false, rs_a); + set(true, rs_a); + unsafe { set_compute_root_constant(list, 0, 0xABCD, 0) }; + assert!(args(false).iter().any(|b| *b != 0)); + assert!(args(true).iter().all(|b| *b == 0), "compute and graphics arguments are separate"); + // the same signature again: the arguments stay + set(false, rs_a); + assert_eq!(&args(false)[..4], &0xABCDu32.to_le_bytes()); + // graphics is independent: a different one there leaves compute alone + unsafe { set_graphics_root_constant(list, 0, 0x1234, 0) }; + set(true, rs_b); + assert!(args(true).iter().all(|b| *b == 0)); + assert_eq!(&args(false)[..4], &0xABCDu32.to_le_bytes()); + // a different signature clears + set(false, rs_b); + assert!(args(false).iter().all(|b| *b == 0)); + // a signature re-made at the same address is a different one + unsafe { set_compute_root_constant(list, 0, 0xABCD, 0) }; + console_list::note_root_signature(rs_b, &test_rts0_blob()); + set(false, rs_b); + assert!(args(false).iter().all(|b| *b == 0)); + // Reset and ClearState clear, so the signature set again afterwards starts empty + unsafe { set_compute_root_constant(list, 0, 0xABCD, 0) }; + clear_state(list, 0); + set(false, rs_b); + assert!(args(false).iter().all(|b| *b == 0)); + unsafe { set_compute_root_constant(list, 0, 0xABCD, 0) }; + reset(list, 0x7100_0330, 0); + set(false, rs_b); + assert!(args(false).iter().all(|b| *b == 0)); + forget(list); + } + #[repr(C)] struct FakeAdoptedList { vt: *const usize, diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index ce65563b16..30895a9b7e 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -287,6 +287,16 @@ pub(super) fn layout_of(rs: usize) -> Option> { LAYOUTS.lock().unwrap().as_ref()?.get(&rs).cloned() } +/// Both are the layout of the same root signature object (not merely of one at the same +/// address: a signature made at a freed one's address has a layout of its own). +pub(super) fn same_layout(a: &Option>, b: &Option>) -> bool { + match (a, b) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + } +} + // --------------------------------------------------------------------------------------- // pipeline states // --------------------------------------------------------------------------------------- @@ -918,8 +928,11 @@ pub unsafe fn close(obj: *mut c_void) -> Result { at += 7; } else if w0 == RS_MARKER { let r = get(2) as usize | (get(3) as usize) << 32; - layout = layout_of(r); - table = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + let new = layout_of(r); + if !same_layout(&layout, &new) { + table = vec![0u8; new.as_ref().map_or(0, |l| l.size as usize)]; + } + layout = new; at += 4; } else if w0 == HEAPS_MARKER { let n = get(1) as usize; From cd4db0992523c629b27aff09b02507fc22887046 Mon Sep 17 00:00:00 2001 From: nathan Date: Sun, 29 Nov 2026 15:48:13 +0100 Subject: [PATCH 107/175] D3D12.X: check lazy array and 3-D texture levels without detiling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D3D12.X: check lazy texture level texels without detiling (da008306): With XCL_TEXTURE_LEVEL_PAGES=1, title_textures::upload_all called map_levels_with_texels(&d.res, &subresources_in(...)), allocating and single-threadedly detiling every mip level of every uploaded texture solely to check !all_zero(&s.data), then discarding the detiled buffers before texture_upload::submit detiled them again. Add Chain::level_has_nonzero and Chain::volume_has_nonzero in gpu::tiling and use them from map_levels_with_texels_in so empty levels exit on a word-at-a-time zero scan, full-block standalone levels return immediately on the first non-zero word, and mip-tail/odd-sized levels scan in place with zero allocations. Measured on a retail title (2c508222, XCL_TEXTURE_LEVEL_PAGES=1): texture upload look time dropped by ~48% (19.7 s -> 10.3 s over 48 s of 3D world; submit cost textures 16.23 -> 11.00 ms/submit) and sustained 3D FPS rose from 1.48 -> 2.27 FPS. From xcl-dev/xcl#3255 (merge 64a0027e). Adapted: this tree already checks a lazy texture's levels without detiling for one-slice 2-D textures (amd-dev a68f609f, levels_with_texels_where with range_any_nonzero, which also skips levels not written since they were zeros), so upstream's map_levels_with_texels_in / map_levels_from_present are not taken. What is taken: Chain::level_has_nonzero / volume_has_nonzero and their tests (all_zero_bytes moved above the Chain doc comment it had split), used for the case this tree still detiled – arrays and 3-D textures – in levels_with_texels_where. New test: levels_with_texels_in_of_arrays_and_volumes_match_detiled_subresources. (cherry picked from commit 64a0027ec3b3d7079c10e58d9c11bf3d4ec22246) Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/tiling.rs | 143 ++++++++++++++++++++ crates/xcl/src/hle/d3d12x/title_textures.rs | 58 +++++++- 2 files changed, 198 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index de370cc695..58912eb9be 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -524,6 +524,13 @@ pub struct MipLevel { pub tail: Option, } +/// Whether every byte of `b` is zero (word-at-a-time scan). +#[inline] +fn all_zero_bytes(b: &[u8]) -> bool { + let mut words = b.chunks_exact(8); + words.all(|w| u64::from_ne_bytes(w.try_into().unwrap()) == 0) && words.remainder().iter().all(|&x| x == 0) +} + /// The mip chain of a tiled surface (addrlib Gfx10Lib::ComputeSurfaceInfoMacroTiled / /// MicroTiled / HwlComputeSurfaceInfoLinear). Per slice: first the mip tail – one block shared /// by the smallest levels (64 KB / 4 KB blocks only) – then the other levels from the smallest @@ -690,6 +697,62 @@ impl Chain { out } + /// Whether `detile_volume(mem, i)` contains any non-zero byte, without allocating or detiling. + pub fn volume_has_nonzero(&self, mem: &[u8], i: usize) -> bool { + let l = self.levels[i]; + if l.width == 0 || l.height == 0 || l.depth == 0 || all_zero_bytes(mem) { + return false; + } + let e = 1usize << self.layout.elem_log2; + for z in 0..l.depth { + for y in 0..l.height { + for x in 0..l.width { + let o = self.element_at_z(&l, x, y, z); + if mem.get(o..o + e).is_some_and(|s| s.iter().any(|&b| b != 0)) { + return true; + } + } + } + } + false + } + + /// Whether `detile_level(src, i, slice)` contains any non-zero byte, without allocating or + /// detiling the whole subresource. + pub fn level_has_nonzero(&self, src: &[u8], i: usize, slice: usize) -> bool { + let l = self.levels[i]; + if l.width == 0 || l.height == 0 { + return false; + } + let r = self.level_bytes(i); + let raw = &src[r.start.min(src.len())..r.end.min(src.len())]; + if all_zero_bytes(raw) { + return false; + } + let e = 1usize << self.layout.elem_log2; + if l.tail.is_none() + && l.origin == (0, 0) + && self.layout.block_d == 1 + && l.width == l.pitch + && l.width.is_multiple_of(self.layout.block_w) + && l.height.is_multiple_of(self.layout.block_h) + && r.end <= src.len() + && r.len() == l.width * l.height * e + { + // Every byte in `raw` maps 1:1 to a texel of this level (no padding or shared tail). + return true; + } + for y in 0..l.height { + for x in 0..l.width { + let offset = l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch); + if src.get(offset..offset + e).is_some_and(|s| s.iter().any(|&b| b != 0)) { + return true; + } + } + } + false + } + /// The first level in the mip tail (the number of levels when there is none). pub fn first_tail(&self) -> usize { self.levels.iter().position(|l| l.tail.is_some()).unwrap_or(self.levels.len()) @@ -1440,5 +1503,85 @@ mod tests { } } } + + #[test] + fn level_has_nonzero_matches_detile_across_mips_tails_and_padding() { + let cfg = configs()[0]; + // Swizzled power-of-two mip chain with standalone levels and a shared mip tail. + for (mode, e) in [(9u32, 4u32), (10, 2), (0, 2)] { + let es = 1usize << e; + let layout = Layout::new(mode, e, cfg).unwrap(); + let chain = Chain::new(layout, 256, 256, 1, 9); + let mut tiled = vec![0u8; chain.slice_bytes]; + + // All-zero texture: every level reports false. + for i in 0..chain.levels.len() { + assert!(!chain.level_has_nonzero(&tiled, i, 0)); + assert!(all_zero_bytes(&chain.detile_level(&tiled, i, 0))); + } + + // Populate only mip 0 (full-block standalone level) and one mip-tail level. + let tail = chain.first_tail(); + let mut active = vec![0usize]; + if tail < chain.levels.len() { + active.push(tail); + } + for &lvl in &active { + let l = chain.levels[lvl]; + let mut lin = vec![0u8; l.width * l.height * es]; + lin[(l.width * l.height - 1) * es] = 0x5A; + chain.tile_level(&mut tiled, lvl, 0, &lin); + } + for i in 0..chain.levels.len() { + let want = !all_zero_bytes(&chain.detile_level(&tiled, i, 0)); + assert_eq!(chain.level_has_nonzero(&tiled, i, 0), want, "mode {mode} e {e} level {i}"); + assert_eq!(want, active.contains(&i), "mode {mode} e {e} level {i}"); + } + } + + // Odd-sized texture: non-zero bytes strictly in padding must NOT trigger a false positive. + for (mode, e) in [(9u32, 2u32), (0, 2)] { + let es = 1usize << e; + let layout = Layout::new(mode, e, cfg).unwrap(); + let chain = Chain::new(layout, 77, 45, 1, 1); + let l = chain.levels[0]; + let mut tiled = vec![0xFFu8; chain.slice_bytes]; + let zeros = vec![0u8; l.width * l.height * es]; + chain.tile_level(&mut tiled, 0, 0, &zeros); + assert!(all_zero_bytes(&chain.detile_level(&tiled, 0, 0))); + assert!(!chain.level_has_nonzero(&tiled, 0, 0), "padding-only bytes must report false (mode {mode})"); + + let mut one = zeros; + one[(l.width * l.height - 1) * es] = 0x7F; + chain.tile_level(&mut tiled, 0, 0, &one); + assert!(chain.level_has_nonzero(&tiled, 0, 0), "active texel must report true (mode {mode})"); + } + } + + #[test] + fn volume_has_nonzero_matches_detile_volume() { + let cfg = configs()[0]; + for (mode, e) in [(9u32, 2u32), (10, 2)] { + let es = 1usize << e; + let layout = Layout::new(mode, e, cfg).unwrap(); + let chain = Chain::new_3d(layout, 32, 32, 16, 1, 4); + let layers = 16usize.div_ceil(layout.block_d); + let mut tiled = vec![0u8; layers * chain.slice_bytes]; + + for i in 0..chain.levels.len() { + assert!(!chain.volume_has_nonzero(&tiled, i)); + } + let l1 = chain.levels[1]; + let mut lin = vec![0u8; l1.width * l1.height * l1.depth * es]; + lin[(l1.width * l1.height * (l1.depth - 1)) * es] = 0xC3; + chain.tile_volume(&mut tiled, 1, &lin); + + for i in 0..chain.levels.len() { + let want = !all_zero_bytes(&chain.detile_volume(&tiled, i)); + assert_eq!(chain.volume_has_nonzero(&tiled, i), want, "3D mode {mode} level {i}"); + assert_eq!(want, i == 1); + } + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 1481e8f3d2..470f8b58b4 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2953,9 +2953,30 @@ unsafe fn levels_with_texels_where(va: usize, tex: &xg::Texture, pages: Option<& return (Vec::new(), Vec::new()); }; if t.depth > 0 || t.array != 1 { - let subs = subresources_in(va, tex, pages); - let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); - let zero: Vec = (0..subs.len() as u32).filter(|l| !present.contains(l)).collect(); + // each level's tiled bytes checked in place (`Chain::volume_has_nonzero` / + // `level_has_nonzero`), in `subresources_in`'s order, without detiling them + let c = &t.chain; + let mips = c.levels.len(); + let bytes = |at: usize, len: usize| match pages { + Some(m) => { + let mut v = vec![0u8; len]; + m.copy(at, &mut v); + std::borrow::Cow::Owned(v) + } + None => title_bytes(at, len), + }; + let (count, present) = if t.depth > 0 { + let mem = bytes(va, t.size() as usize); + (mips, (0..mips).filter(|&i| c.volume_has_nonzero(&mem, i)).map(|i| i as u32).collect::>()) + } else { + let mut present = Vec::new(); + for s in 0..t.array as usize { + let slice = bytes(va + s * c.slice_bytes, c.slice_bytes); + present.extend((0..mips).filter(|&i| c.level_has_nonzero(&slice, i, s)).map(|i| (s * mips + i) as u32)); + } + (t.array as usize * mips, present) + }; + let zero: Vec = (0..count as u32).filter(|l| !present.contains(l)).collect(); return (present, zero); } let c = &t.chain; @@ -6052,6 +6073,37 @@ pub(super) mod tests { } } + /// An array's and a volume's levels with texels, checked in place, are those of their + /// detiled subresources (in `subresources_in`'s order). + #[test] + fn levels_with_texels_in_of_arrays_and_volumes_match_detiled_subresources() { + unsafe { + for (what, desc) in [ + // three slices of 256x256 R8G8B8A8, 9 mips, 64 KiB tiled (a packed tail each) + ("array", console_desc(3, 256, 256, 3, 9, 87, 0x109)), + // 64x64x16 R8G8B8A8, 4 mips + ("volume", console_desc(4, 64, 64, 16, 4, 87, 0x109)), + ] { + let tex = xg::Texture::new(&desc).unwrap_or_else(|e| panic!("{what}: {e:?}")); + let t = tex.texels().unwrap(); + let c = &t.chain; + let size = tex.size() as usize; + let mut buf = vec![0u8; size]; + let at = |s: usize| s * c.slice_bytes; + let last = size / c.slice_bytes - 1; + // slice (layer) 1's mip 0 (a volume of one layer: its own) and the last slice's + // first bytes (the tail, if any) + buf[at(last.min(1)) + c.levels[0].offset + 64] = 0x5A; + buf[at(last) + 3] = 0xA5; + let subs = subresources_in(buf.as_ptr() as usize, &tex, None); + let want: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + let zero: Vec = (0..subs.len() as u32).filter(|l| !want.contains(l)).collect(); + assert!(!want.is_empty() && !zero.is_empty(), "{what}: the test texture must have levels of both kinds: {want:?}"); + assert_eq!(levels_with_texels_in(buf.as_ptr() as usize, &tex, None), (want, zero), "{what}"); + } + } + } + /// `read_committed` copies committed pages and leaves uncommitted gaps zeroed, including /// unaligned start/end offsets. #[test] From 19996da6d3c8a4c45a95d3a01ac6c2ad008cc68e Mon Sep 17 00:00:00 2001 From: gefydev <71671650+gefydev@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:49:01 +0100 Subject: [PATCH 108/175] D3D12.X: let independent submits bypass a busy copy pool AI use: Codex (gpt-6.2-sol) From xcl-dev/xcl#3226 (merge e5786baa). Adapted: only the imports conflicted (this tree does not use AtomicBool there); the rest applied as is. (cherry picked from commit e5786baa534285ecd8aa2f219a46fc7417a05e62) --- crates/xcl/src/hle/d3d12x/worker_pool.rs | 40 +++++++++++++++++++++--- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/worker_pool.rs b/crates/xcl/src/hle/d3d12x/worker_pool.rs index 72eef80faa..1024750d55 100644 --- a/crates/xcl/src/hle/d3d12x/worker_pool.rs +++ b/crates/xcl/src/hle/d3d12x/worker_pool.rs @@ -3,7 +3,7 @@ //! and waits for the workers, so nothing of the submit is left running when `run` returns. use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, TryLockError}; use std::time::{Duration, Instant}; /// What one `run` shares: the function and how many calls it makes (one per item). @@ -49,6 +49,9 @@ struct Pool { shared: Arc, } +// The shared workers help one caller at a time. +static ONE: Mutex<()> = Mutex::new(()); + fn worker(s: Arc) { let mut seen = 0u64; loop { @@ -120,9 +123,15 @@ pub(super) fn run(items: usize, f: &(dyn Fn(usize) + Sync)) -> Shares { (0..items).for_each(f); return Shares { by_caller: items, ..Shares::default() }; }; - // one job at a time - static ONE: Mutex<()> = Mutex::new(()); - let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); + // A busy pool must not keep another submitting thread from sending its own work to the GPU. + let _one = match ONE.try_lock() { + Ok(guard) => guard, + Err(TryLockError::Poisoned(err)) => err.into_inner(), + Err(TryLockError::WouldBlock) => { + (0..items).for_each(f); + return Shares { by_caller: items, ..Shares::default() }; + } + }; // SAFETY: the pointer outlives the workers' use of it (`run` waits for them below) let erased: *const (dyn Fn(usize) + Sync) = unsafe { std::mem::transmute::<&(dyn Fn(usize) + Sync), &'static (dyn Fn(usize) + Sync)>(f) }; { @@ -156,6 +165,29 @@ pub(super) fn run(items: usize, f: &(dyn Fn(usize) + Sync)) -> Shares { mod tests { use super::*; + #[test] + fn busy_pool_does_not_delay_an_independent_caller() { + if pool().is_none() { + return; + } + let lease = ONE.lock().unwrap_or_else(|err| err.into_inner()); + let (sent, received) = std::sync::mpsc::channel(); + let caller = std::thread::spawn(move || { + let expected_thread = std::thread::current().id(); + let hits = AtomicUsize::new(0); + let shares = run(10, &|_| { + if std::thread::current().id() == expected_thread { + hits.fetch_add(1, Ordering::Relaxed); + } + }); + sent.send((hits.into_inner(), shares.by_caller)).unwrap(); + }); + let result = received.recv_timeout(Duration::from_secs(2)); + drop(lease); + caller.join().unwrap(); + assert_eq!(result.unwrap(), (10, 10)); + } + #[test] fn every_item_runs_once() { for items in [0usize, 1, 2, 7, 64, 1000] { From d5d437a7661fb4534b8c0c9abf8fa8b18b619b72 Mon Sep 17 00:00:00 2001 From: b3IKK <278540256+b3IKK@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:49:26 +0100 Subject: [PATCH 109/175] Shaders: reset branch targets per FSSM program and do not merge across data blocks Shaders: reset branch targets per FSSM program and avoid merging across data blocks (0344d91c): In gpu/xbox.rs, FSSM segment grouping accumulated `targets` across every program without resetting when a new program started, and merged subsequent segments into `f.programs.last_mut()` without checking for an intervening data block: - A stale branch target from Program 0 pointing to Segment 2 caused Segment 2 to be merged into an unrelated Program 1. - Merging Segment 2 into Program 0 across an intervening constant data block extended Program 0's `len` over the data block while also keeping it in `f.data_blocks`. Reset `targets = own` whenever a new program is pushed onto `f.programs`, and disallow merging a segment into the preceding program across an intervening data block. From xcl-dev/xcl#1507 (merge 59fd4dde). Taken as is. (cherry picked from commit 59fd4dde320d3d54eb4eed23d43f66979959fecb) Assisted-by: OpenCode (Gemini 4 Neon) --- crates/xcl/src/gpu/xbox.rs | 64 +++++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/xbox.rs b/crates/xcl/src/gpu/xbox.rs index 68cd51cd71..91afa7f952 100644 --- a/crates/xcl/src/gpu/xbox.rs +++ b/crates/xcl/src/gpu/xbox.rs @@ -350,8 +350,11 @@ fn analyze_fssm(f: &mut Fssm) { let seg = &code[p.offset..p.offset + p.len]; let own = branch_targets(seg, p.offset as u64); let range = p.offset as u64..(p.offset + p.len) as u64; - let reached = targets.iter().any(|t| range.contains(t)); - let jumps_back = f.programs.last().is_some_and(|last| { + let has_intervening_data = f.programs.last().is_some_and(|last| { + f.data_blocks.last().is_some_and(|d| d.offset >= last.offset + last.len) + }); + let reached = !has_intervening_data && targets.iter().any(|t| range.contains(t)); + let jumps_back = !has_intervening_data && f.programs.last().is_some_and(|last| { let r = (last.offset - o) as u64..(last.offset - o + last.len) as u64; own.iter().any(|t| r.contains(t)) }); @@ -362,10 +365,15 @@ fn analyze_fssm(f: &mut Fssm) { f.data_blocks.push(Program { offset: o + p.offset, len: p.len }); continue; } - targets.extend(own); match f.programs.last_mut() { - Some(last) if reached || jumps_back => last.len = o + p.offset + p.len - last.offset, - _ => f.programs.push(Program { offset: o + p.offset, len: p.len }), + Some(last) if reached || jumps_back => { + last.len = o + p.offset + p.len - last.offset; + targets.extend(own); + } + _ => { + f.programs.push(Program { offset: o + p.offset, len: p.len }); + targets = own; + } } } } @@ -856,6 +864,52 @@ pub(crate) mod tests { assert_eq!(parse(&sample(0, &[fssm(&code3, &[(5, 1)])])).unwrap().fssm[0].programs, vec![Program { offset: 0x308, len: 20 }]); } + #[test] + fn branch_target_from_earlier_program_does_not_merge_into_later_program_or_across_data() { + // Seg 0 (0..8): s_branch +3 (target = 4 + 12 = 16, start of Seg 2) ; s_endpgm + // Seg 1 (8..16): s_mov_b32 s0, s1 ; s_endpgm (separate Program 1) + // Seg 2 (16..24): s_mov_b32 s0, s1 ; s_endpgm + let mut code = Vec::new(); + for w in [ + 0xBF82_0003u32, // s_branch → 16 + S_ENDPGM, + 0xBE80_0301, // s_mov_b32 s0, s1 + S_ENDPGM, + 0xBE80_0301, // s_mov_b32 s0, s1 + S_ENDPGM, + ] { + code.extend_from_slice(&w.to_le_bytes()); + } + let f = &parse(&sample(0, &[fssm(&code, &[(5, 1)])])).unwrap().fssm[0]; + assert_eq!(f.programs.len(), 3, "stale target from Program 0 must not merge Seg 2 into Program 1: {:?}", f.programs); + + // Seg 0 (0..8): s_branch +5 (target = 4 + 20 = 24, start of Seg 2) ; s_endpgm + // Guard + counted data (8..24): s_endpgm ; count=1 ; 0x3f800000 ; s_endpgm + // Seg 2 (24..32): s_mov_b32 s0, s1 ; s_endpgm + let mut with_data = Vec::new(); + for w in [ + 0xBF82_0005u32, // s_branch → 24 + S_ENDPGM, + S_ENDPGM, // guard before counted data block + 1, + 0x3f80_0000, + S_ENDPGM, + 0xBE80_0301, + S_ENDPGM, + ] { + with_data.extend_from_slice(&w.to_le_bytes()); + } + let f2 = &parse(&sample(0, &[fssm(&with_data, &[(5, 1)])])).unwrap().fssm[0]; + assert_eq!(f2.data_blocks.len(), 1); + let db = f2.data_blocks[0]; + for prog in &f2.programs { + assert!( + prog.offset + prog.len <= db.offset || prog.offset >= db.offset + db.len, + "program {prog:?} must not swallow intervening data block {db:?}" + ); + } + } + #[test] fn counted_data_may_contain_endpgm_words() { let mut code = CODE.to_vec(); From edd291db382cbfd8ea38f93444c2a138f42d804b Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:50:29 +0100 Subject: [PATCH 110/175] D3D12.X: keep logic ops on pipelines whose render targets are all UINT sanitize_integer_rt_blend cleared LogicOpEnable together with BlendEnable on every integer render target. PC D3D12 forbids blending on UINT/SINT targets, but logic ops are the opposite case: they are valid only on UINT targets, need BlendEnable FALSE and IndependentBlendEnable FALSE (slot 0's state then applies to every bound target), and need D3D12_OPTIONS.OutputMergerLogicOp. A console pipeline that ORs or XORs bit masks into a UINT target therefore wrote plain overwrites on PC. With IndependentBlendEnable FALSE, slot 0 now keeps its logic op when every bound target is UINT and the device reports OutputMergerLogicOp (probed at device creation; without it the logic op is cleared as before and a warning is logged once). BlendEnable is still cleared. Any non-UINT target in the set (SINT, float, UNORM, UNKNOWN) drops the logic op, now also when no integer target is bound: such a pipeline is invalid on PC. The independent-blend path is unchanged. Tests: logic_op_stays_on_uint_render_targets (fails without the fix), logic_op_dropped_without_output_merger_logic_op (fails without the capability gate) and logic_op_dropped_unless_every_target_is_uint; the all-integer case of the existing sanitization test now uses a SINT target. From xcl-dev/xcl#2856 (merge b5b5800c). Adapted: real.rs conflicted where upstream has code this tree does not (pipeline_library::activate next to the device probes, rewrite_graphics_stream); probe_logic_op goes after probe_dynamic_depth_bias, and the four sanitize_integer_rt_blend call sites this tree has pass logic_op_supported(). The function, the probe and the tests as upstream. (cherry picked from commit b5b5800cb66500a95b310337b4cf3aad7561a9e5) --- crates/xcl/src/hle/d3d12x/real.rs | 158 +++++++++++++++++++++++++++--- 1 file changed, 143 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index cbbaa9e693..04a574e416 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -714,6 +714,7 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result= std::mem::size_of::() { let mut blend: D3D12_BLEND_DESC = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_BLEND_DESC); - sanitize_integer_rt_blend(&mut blend, rt_count, &rt_formats); + sanitize_integer_rt_blend(&mut blend, rt_count, &rt_formats, logic_op_supported()); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend); continue; } @@ -9061,7 +9062,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE } let dsv = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_view_format(d.DSVFormat.0 as u32) as i32); let mut blend = d.BlendState; - sanitize_integer_rt_blend(&mut blend, rt.NumRenderTargets, &rt.RTFormats); + sanitize_integer_rt_blend(&mut blend, rt.NumRenderTargets, &rt.RTFormats, logic_op_supported()); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, &blend); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &d.SampleMask); out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &d.RasterizerState); @@ -9151,7 +9152,7 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec, [usize; 2])> { 25 => put(&mut buf, &dm?.0), 8 if psize >= std::mem::size_of::() => { let mut blend: D3D12_BLEND_DESC = std::ptr::read_unaligned(buf[at..].as_ptr() as *const D3D12_BLEND_DESC); - sanitize_integer_rt_blend(&mut blend, rt_count, &rt_formats); + sanitize_integer_rt_blend(&mut blend, rt_count, &rt_formats, logic_op_supported()); let bytes = std::slice::from_raw_parts(&blend as *const D3D12_BLEND_DESC as *const u8, std::mem::size_of::()); buf[at..at + bytes.len()].copy_from_slice(bytes); } @@ -9254,11 +9255,14 @@ fn is_integer_dxgi_format(f: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT /// When `IndependentBlendEnable` is false and a mix of integer and non-integer RTs has blending /// enabled on slot 0, promote to `IndependentBlendEnable = TRUE` so non-integer slots keep /// blending while integer slots have it cleared (clearing `LogicOpEnable` on all slots as D3D12 -/// requires when independent blend is enabled). +/// requires when independent blend is enabled). With `IndependentBlendEnable` false, slot 0's +/// logic op is kept only when every bound target is `*_UINT` and `logic_op_supported` (the +/// device's `OutputMergerLogicOp`), the only case PC D3D12 accepts; its `BlendEnable` is cleared. fn sanitize_integer_rt_blend( blend: &mut D3D12_BLEND_DESC, num_render_targets: u32, rt_formats: &[windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; 8], + logic_op_supported: bool, ) { let n = (num_render_targets as usize).min(8); if n == 0 { @@ -9273,17 +9277,22 @@ fn sanitize_integer_rt_blend( } return; } - let any_int = (0..n).any(|i| is_integer_dxgi_format(rt_formats[i])); - if !any_int { - return; + let all_uint = (0..n).all(|i| is_uint_dxgi_format(rt_formats[i])); + if blend.RenderTarget[0].LogicOpEnable.as_bool() && !(all_uint && logic_op_supported) { + blend.RenderTarget[0].LogicOpEnable = false.into(); + if all_uint { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| { + crate::xlog_warn!("D3D12.X: the device has no OutputMergerLogicOp; logic ops on UINT render targets are dropped"); + }); + } } - let rt0_blend = blend.RenderTarget[0].BlendEnable.as_bool(); - let rt0_logic = blend.RenderTarget[0].LogicOpEnable.as_bool(); - if !rt0_blend && !rt0_logic { + let any_int = (0..n).any(|i| is_integer_dxgi_format(rt_formats[i])); + if !any_int || !blend.RenderTarget[0].BlendEnable.as_bool() { return; } let any_non_int = (0..n).any(|i| !is_integer_dxgi_format(rt_formats[i])); - if rt0_blend && any_non_int { + if any_non_int { let mut base = blend.RenderTarget[0]; base.LogicOpEnable = false.into(); blend.IndependentBlendEnable = true.into(); @@ -9298,10 +9307,46 @@ fn sanitize_integer_rt_blend( } } else { blend.RenderTarget[0].BlendEnable = false.into(); - blend.RenderTarget[0].LogicOpEnable = false.into(); } } +/// Cached `D3D12_FEATURE_DATA_D3D12_OPTIONS.OutputMergerLogicOp` of the device: -1 = not yet +/// probed, 0 = unsupported, 1 = supported. +static LOGIC_OP: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1); + +/// Query `D3D12_FEATURE_D3D12_OPTIONS` for output-merger logic op support and cache it. +fn probe_logic_op(dev: &ID3D12Device) { + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + let ok = unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32) }.is_ok() + && o.OutputMergerLogicOp.as_bool(); + LOGIC_OP.store(ok as i8, Ordering::Release); +} + +/// Whether the device supports logic ops; false until the device is probed (logic ops cleared). +fn logic_op_supported() -> bool { + LOGIC_OP.load(Ordering::Acquire) == 1 +} + +/// Whether `f` is one of `is_integer_dxgi_format`'s `*_UINT` formats, the only render target +/// formats on which PC D3D12 accepts `LogicOpEnable = TRUE`. +fn is_uint_dxgi_format(f: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> bool { + use windows::Win32::Graphics::Dxgi::Common::*; + matches!( + f, + DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32_UINT + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R10G10B10A2_UINT + | DXGI_FORMAT_R8G8B8A8_UINT + | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R32_UINT + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R8_UINT + ) +} + /// A topology type the PC has: the console's for rect lists (19, with draws of topology 17 – /// `list_x::RECT_LIST`) is TRIANGLE, as those draws become triangle lists (the rects' fourth /// corners come from `pso::rect_list_gs`, added by `translated_graphics_pso`); UNDEFINED (a stream @@ -9312,7 +9357,7 @@ fn pc_topology_type(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) { for f in g.RTVFormats.iter_mut() { *f = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_target_format(f.0 as u32) as i32); } - sanitize_integer_rt_blend(&mut g.BlendState, g.NumRenderTargets, &g.RTVFormats); + sanitize_integer_rt_blend(&mut g.BlendState, g.NumRenderTargets, &g.RTVFormats, logic_op_supported()); if !(1..=4).contains(&g.PrimitiveTopologyType.0) { g.PrimitiveTopologyType = if g.HS.pShaderBytecode.is_null() { D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE } else { D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH }; } @@ -9371,10 +9416,11 @@ mod pso_blend_and_tsharp_tests { assert!(!m.BlendState.RenderTarget[1].LogicOpEnable.as_bool()); assert_eq!(m.BlendState.RenderTarget[1].SrcBlend, D3D12_BLEND_SRC_ALPHA); - // Case 3: IndependentBlendEnable=FALSE with all-integer RTs -> clears slot 0 without enabling independent blend. + // Case 3: IndependentBlendEnable=FALSE with all-integer RTs -> clears blend on slot 0 without + // enabling independent blend; a logic op stays only when every target is UINT. let mut a: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { std::mem::zeroed() }; a.NumRenderTargets = 1; - a.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UINT; + a.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_SINT; a.BlendState.IndependentBlendEnable = false.into(); a.BlendState.RenderTarget[0].BlendEnable = true.into(); a.BlendState.RenderTarget[0].LogicOpEnable = true.into(); @@ -9384,6 +9430,88 @@ mod pso_blend_and_tsharp_tests { assert!(!a.BlendState.RenderTarget[0].LogicOpEnable.as_bool()); } + fn logic_op_pso(formats: &[DXGI_FORMAT], blend: bool) -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + let mut g: D3D12_GRAPHICS_PIPELINE_STATE_DESC = unsafe { std::mem::zeroed() }; + g.NumRenderTargets = formats.len() as u32; + g.RTVFormats[..formats.len()].copy_from_slice(formats); + g.BlendState.IndependentBlendEnable = false.into(); + g.BlendState.RenderTarget[0].BlendEnable = blend.into(); + g.BlendState.RenderTarget[0].LogicOpEnable = true.into(); + g.BlendState.RenderTarget[0].LogicOp = D3D12_LOGIC_OP_OR; + g.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xF; + g + } + + fn sanitize(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, logic_op_supported: bool) { + sanitize_integer_rt_blend(&mut g.BlendState, g.NumRenderTargets, &g.RTVFormats, logic_op_supported); + } + + #[test] + fn logic_op_dropped_without_output_merger_logic_op() { + let mut g = logic_op_pso(&[DXGI_FORMAT_R32_UINT], false); + sanitize(&mut g, false); + assert!(!g.BlendState.RenderTarget[0].LogicOpEnable.as_bool()); + assert!(!g.BlendState.RenderTarget[0].BlendEnable.as_bool()); + let mut k = logic_op_pso(&[DXGI_FORMAT_R32_UINT], false); + sanitize(&mut k, true); + assert!(k.BlendState.RenderTarget[0].LogicOpEnable.as_bool()); + } + + #[test] + fn logic_op_stays_on_uint_render_targets() { + for blend in [false, true] { + let mut g = logic_op_pso(&[DXGI_FORMAT_R32_UINT], blend); + sanitize(&mut g, true); + let rt = g.BlendState.RenderTarget[0]; + assert!(rt.LogicOpEnable.as_bool(), "blend={blend}"); + assert_eq!(rt.LogicOp, D3D12_LOGIC_OP_OR); + assert!(!rt.BlendEnable.as_bool()); + assert!(!g.BlendState.IndependentBlendEnable.as_bool()); + } + // Several UINT targets share slot 0's logic op. + let mut m = logic_op_pso(&[DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R16G16_UINT], false); + sanitize(&mut m, true); + assert!(m.BlendState.RenderTarget[0].LogicOpEnable.as_bool()); + assert!(!m.BlendState.IndependentBlendEnable.as_bool()); + } + + #[test] + fn logic_op_dropped_unless_every_target_is_uint() { + // SINT alone, or UINT next to SINT: logic op is invalid on PC, drop it. + for formats in [&[DXGI_FORMAT_R32_SINT][..], &[DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R8_SINT][..]] { + let mut g = logic_op_pso(formats, false); + sanitize(&mut g, true); + assert!(!g.BlendState.RenderTarget[0].LogicOpEnable.as_bool(), "{formats:?}"); + assert!(!g.BlendState.RenderTarget[0].BlendEnable.as_bool()); + } + // UINT next to a float target with blending: promoted to independent blend, no logic op. + let mut f = logic_op_pso(&[DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32_UINT], true); + sanitize(&mut f, true); + assert!(f.BlendState.IndependentBlendEnable.as_bool()); + assert!(f.BlendState.RenderTarget[0].BlendEnable.as_bool()); + for i in 0..2 { + assert!(!f.BlendState.RenderTarget[i].LogicOpEnable.as_bool()); + } + // IndependentBlendEnable=TRUE: integer slots lose blend and logic op, as before. + let mut ind = logic_op_pso(&[DXGI_FORMAT_R32_UINT], true); + ind.BlendState.IndependentBlendEnable = true.into(); + sanitize(&mut ind, true); + assert!(!ind.BlendState.RenderTarget[0].LogicOpEnable.as_bool()); + assert!(!ind.BlendState.RenderTarget[0].BlendEnable.as_bool()); + // Float-only target set: logic ops need UINT targets, so it is dropped; blending stays. + let mut fl = logic_op_pso(&[DXGI_FORMAT_R8G8B8A8_UNORM], false); + sanitize(&mut fl, true); + assert!(!fl.BlendState.RenderTarget[0].LogicOpEnable.as_bool()); + let mut fb = logic_op_pso(&[DXGI_FORMAT_R8G8B8A8_UNORM], true); + sanitize(&mut fb, true); + assert!(!fb.BlendState.RenderTarget[0].LogicOpEnable.as_bool()); + assert!(fb.BlendState.RenderTarget[0].BlendEnable.as_bool()); + // An UNKNOWN slot inside NumRenderTargets is not UINT. + let mut u = logic_op_pso(&[DXGI_FORMAT_R32_UINT, DXGI_FORMAT_UNKNOWN], false); + sanitize(&mut u, true); + assert!(!u.BlendState.RenderTarget[0].LogicOpEnable.as_bool()); + } + #[test] fn rt_format_array_layout_matches_stream_parsing() { assert_eq!(std::mem::offset_of!(D3D12_RT_FORMAT_ARRAY, RTFormats), 0); From 2789e60d26314c6297ca7eb236a3f8ac40f9117e Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:53:23 +0100 Subject: [PATCH 111/175] D3D12.X: copy texture regions with unaligned footprints through scratch PC D3D12 requires a placed footprint's Offset to be a multiple of D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT (512) and its RowPitch a multiple of D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (256), unless the device reports OPTIONS13.UnrestrictedBufferTextureCopyPitchSupported, in which case both only need to be multiples of the format's unit size. CopyTextureRegion with an invalid footprint is undefined behaviour (incorrect rendering, no copy, or device removal). Console footprints can be packed tighter. copy_texture_region_x noticed this only under XCL_TRACE_FRAME and still passed the footprint to the PC. footprint_plan (pure) decides between passing the call through and copying through the list's copy scratch at offset 0 with the pitch rounded up to 256. It passes the call through when the footprint is aligned, or when the device has the unrestricted capability (probed once; a failed query counts as unsupported) and offset and pitch are whole units. For buffer->texture only the rows and slices of the source box are copied: one buffer copy when only the offset is off, one per row of blocks otherwise, clamped to the end of the source buffer. For texture->buffer only the bytes the copy writes are copied back, so bytes between rows and outside the box keep their contents. With no scratch large enough the call goes as before, with a warning. From xcl-dev/xcl#2873 (merge 3f0875cf). Adapted: list_x.rs conflicted only by position (upstream code around it this tree does not have). The planner, the realigned copy and the tests as upstream; in copy_texture_region_x the realigned copy is tried before this tree's format_alias::try_copy_texture_region (which takes only texture-to-texture copies, so the two never both apply). (cherry picked from commit 3f0875cfc747341ee257248a2ac4c2860517b8bb) Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/list_x.rs | 308 ++++++++++++++++++++++++++++ 1 file changed, 308 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 373fd85054..58795d9583 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5411,6 +5411,310 @@ unsafe fn trace_watched_copy(what: &str, dst: usize, src: usize) { ); } +/// One buffer copy between a title buffer and the copy scratch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct RowCopy { + buffer: u64, + scratch: u64, + bytes: u64, +} + +/// Which side of a CopyTextureRegion is the placed footprint, with what the plan needs to know. +#[derive(Debug, Clone, PartialEq, Eq)] +enum FootprintSide { + /// buffer -> texture: the rows (in blocks) and slices the source box covers, read up to the + /// end of the buffer (`buffer_bytes`) + Source { buffer_bytes: u64, rows: std::ops::Range, slices: std::ops::Range }, + /// texture -> buffer: only the bytes the copy writes go back, so the bytes between rows and + /// outside the box stay as they are. Rows and slices in blocks, bytes within a row. + Destination { rows: std::ops::Range, slices: std::ops::Range, bytes: std::ops::Range }, +} + +#[derive(Debug, PartialEq, Eq)] +enum FootprintPlan { + /// PC D3D12 takes the footprint as it is + PassThrough, + /// copy through a scratch buffer at offset 0 with `row_pitch` (a multiple of 256) + ViaScratch { row_pitch: u32, scratch_bytes: u64, copies: Vec }, +} + +/// rows of blocks of a DXGI format (block-compressed formats: 4 texels high) +fn block_height(format: u32) -> u32 { + match format { + 70..=84 | 94..=99 => 4, + _ => 1, + } +} + +/// How to issue a CopyTextureRegion whose placed footprint is at `offset` with `row_pitch`. +/// PC D3D12 requires `Offset` % 512 (D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) and `RowPitch` % +/// 256 (D3D12_TEXTURE_DATA_PITCH_ALIGNMENT), in both directions; console footprints may be packed +/// tighter. With `OPTIONS13.UnrestrictedBufferTextureCopyPitchSupported`, both only need to be +/// multiples of the format's unit (texel or block) size: `unrestricted_unit` is that size when the +/// device reports it. Rows are rows of blocks; `height` is in texels. +fn footprint_plan(offset: u64, row_pitch: u32, format: u32, height: u32, depth: u32, unrestricted_unit: Option, side: &FootprintSide) -> FootprintPlan { + let align = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as u64; + if offset.is_multiple_of(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64) && (row_pitch as u64).is_multiple_of(align) { + return FootprintPlan::PassThrough; + } + if unrestricted_unit.is_some_and(|u| u > 0 && offset.is_multiple_of(u) && (row_pitch as u64).is_multiple_of(u)) { + return FootprintPlan::PassThrough; + } + if row_pitch == 0 || height == 0 || depth == 0 { + return FootprintPlan::PassThrough; + } + let (p, q) = (row_pitch as u64, (row_pitch as u64).next_multiple_of(align)); + let rows = height.div_ceil(block_height(format)) as u64; + let scratch_bytes = rows * depth as u64 * q; + let mut copies = Vec::new(); + match side { + FootprintSide::Source { buffer_bytes, rows: ys, slices: zs } => { + let (ys, zs) = (ys.start..ys.end.min(rows as u32), zs.start..zs.end.min(depth)); + if ys.is_empty() || zs.is_empty() { + return FootprintPlan::ViaScratch { row_pitch: q as u32, scratch_bytes, copies }; + } + if p == q { + // only the offset is off: from the box's first row to its last in one copy + let (r0, r1) = (zs.start as u64 * rows + ys.start as u64, (zs.end - 1) as u64 * rows + ys.end as u64); + let at = offset + r0 * p; + let span = ((r1 - r0) * p).min(buffer_bytes.saturating_sub(at)); + if span > 0 { + copies.push(RowCopy { buffer: at, scratch: r0 * q, bytes: span }); + } + } else { + 'rows: for z in zs { + for y in ys.clone() { + let r = z as u64 * rows + y as u64; + let at = offset + r * p; + let bytes = p.min(buffer_bytes.saturating_sub(at)); + if bytes == 0 { + break 'rows; + } + copies.push(RowCopy { buffer: at, scratch: r * q, bytes }); + } + } + } + } + FootprintSide::Destination { rows: ys, slices: zs, bytes: xs } => { + let n = xs.end.saturating_sub(xs.start).min(p.saturating_sub(xs.start)); + if n > 0 { + for z in zs.clone() { + for y in ys.clone() { + let r = z as u64 * rows + y as u64; + copies.push(RowCopy { buffer: offset + r * p + xs.start, scratch: r * q + xs.start, bytes: n }); + } + } + } + } + } + FootprintPlan::ViaScratch { row_pitch: q as u32, scratch_bytes, copies } +} + +/// `OPTIONS13.UnrestrictedBufferTextureCopyPitchSupported`, probed once (-1: not yet; a failed +/// query counts as unsupported) +static UNRESTRICTED_COPY_PITCH: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1); + +unsafe fn unrestricted_copy_pitch(dev: &ID3D12Device) -> bool { + match UNRESTRICTED_COPY_PITCH.load(Ordering::Acquire) { + -1 => {} + v => return v == 1, + } + let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS13::default(); + let yes = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS13, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.UnrestrictedBufferTextureCopyPitchSupported.as_bool(); + UNRESTRICTED_COPY_PITCH.store(yes as i8, Ordering::Release); + crate::xlog_info!("D3D12.X: unrestricted buffer-texture copy pitch (OPTIONS13): {yes}"); + yes +} + +/// A CopyTextureRegion with a placed footprint PC D3D12 does not take, through an aligned copy +/// scratch of the list. `false`: not such a copy, or no scratch (the call goes as it is). +unsafe fn copy_texture_region_realigned(this: *mut c_void, d: &D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, s: &D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) -> bool { + let placed = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + let to_texture = s.Type == placed; + if to_texture == (d.Type == placed) { + return false; + } + let loc = if to_texture { s } else { d }; + let f = loc.Anonymous.PlacedFootprint; + let fp = f.Footprint; + if f.Offset.is_multiple_of(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64) && fp.RowPitch.is_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT) { + return false; + } + static N: AtomicU64 = AtomicU64::new(0); + const W: &str = "CopyTextureRegion through an aligned scratch"; + let Some(buffer) = loc.pResource.as_ref() else { return false }; + let buf = buffer.as_raw() as usize; + let Some(dev) = device_of(this) else { return false }; + let bw = block_height(fp.Format.0 as u32); + // the texture side's subresource as the PC lays it out, and its bytes per block + let tex_loc = if to_texture { d } else { s }; + let unit = || { + let tex = tex_loc.pResource.as_ref()?; + let (mut rows, mut row_size) = (0u32, 0u64); + let mut sub = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + dev.GetCopyableFootprints(&tex.GetDesc(), tex_loc.Anonymous.SubresourceIndex, 1, 0, Some(&mut sub), Some(&mut rows), Some(&mut row_size), None); + Some((row_size / sub.Footprint.Width.div_ceil(bw).max(1) as u64, sub.Footprint)) + }; + let unrestricted = if unrestricted_copy_pitch(&dev) { unit().map(|(u, _)| u) } else { None }; + let side = if to_texture { + let (rows, slices) = match bx.as_ref() { + Some(b) => (b.top / bw..b.bottom.div_ceil(bw), b.front..b.back), + None => (0..fp.Height.div_ceil(bw), 0..fp.Depth), + }; + FootprintSide::Source { buffer_bytes: buffer.GetDesc().Width, rows, slices } + } else { + let Some((per_block, sub)) = unit() else { return false }; + // the extent written into the footprint: the box, or the whole subresource + let (w, h, dz) = match bx.as_ref() { + Some(b) => (b.right.saturating_sub(b.left), b.bottom.saturating_sub(b.top), b.back.saturating_sub(b.front)), + None => (sub.Width, sub.Height, sub.Depth), + }; + let bx0 = (x / bw) as u64 * per_block; + FootprintSide::Destination { + rows: y / bw..(y + h).div_ceil(bw), + slices: z..z + dz, + bytes: bx0..bx0 + w.div_ceil(bw) as u64 * per_block, + } + }; + let FootprintPlan::ViaScratch { row_pitch, scratch_bytes, copies } = footprint_plan(f.Offset, fp.RowPitch, fp.Format.0 as u32, fp.Height, fp.Depth, unrestricted, &side) else { + return false; + }; + // a scratch already used in this recording keeps its size: too small -> the call as it is + let Some((t, _)) = copy_scratch(this, scratch_bytes).filter(|&(_, c)| c >= scratch_bytes) else { + warn(&N, W, format_args!("no scratch of {scratch_bytes:#x} bytes for a footprint at {:#x} with row pitch {}", f.Offset, fp.RowPitch)); + return false; + }; + let mut scratch: D3D12_TEXTURE_COPY_LOCATION = std::ptr::read(loc); + std::ptr::write(&mut scratch.pResource as *mut _ as *mut usize, t); + scratch.Anonymous.PlacedFootprint.Offset = 0; + scratch.Anonymous.PlacedFootprint.Footprint.RowPitch = row_pitch; + let copy = |dl: &D3D12_TEXTURE_COPY_LOCATION, sl: &D3D12_TEXTURE_COPY_LOCATION| { + pc::(this, PC_COPY_TEXTURE_REGION)(this, dl, x, y, z, sl, bx) + }; + if to_texture { + as_copy_dest(this, t, || copies.iter().for_each(|c| copy_buffer_region(this, t, c.scratch, buf, c.buffer, c.bytes))); + transition(this, t, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy(d, &scratch); + } else { + as_copy_dest(this, t, || copy(&scratch, s)); + transition(this, t, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + copies.iter().for_each(|c| copy_buffer_region(this, buf, c.buffer, t, c.scratch, c.bytes)); + } + transition(this, t, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + std::mem::forget(scratch); // borrowed resource pointers + static DONE: AtomicU64 = AtomicU64::new(0); + let k = DONE.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_info!("D3D12.X: {W}: {k} copies (last: offset {:#x}, row pitch {} -> {row_pitch}, {} buffer copies)", f.Offset, fp.RowPitch, copies.len()); + } + true +} + +#[cfg(test)] +mod footprint_plan_tests { + use super::*; + + fn via(p: FootprintPlan) -> (u32, u64, Vec) { + match p { + FootprintPlan::ViaScratch { row_pitch, scratch_bytes, copies } => (row_pitch, scratch_bytes, copies), + FootprintPlan::PassThrough => panic!("expected a scratch copy"), + } + } + + /// buffer -> texture with no box (the planner clamps the ranges to the footprint) + fn src(buffer_bytes: u64) -> FootprintSide { + FootprintSide::Source { buffer_bytes, rows: 0..u32::MAX, slices: 0..u32::MAX } + } + + #[test] + fn unrestricted_copy_pitch_takes_unit_aligned_footprints() { + // R8G8B8A8 (4-byte texels): pitch 64 and offset 0x104 are whole texels + assert_eq!(footprint_plan(0x104, 64, 28, 4, 1, Some(4), &src(0x400)), FootprintPlan::PassThrough); + // without the capability the same footprint needs the scratch + assert!(matches!(footprint_plan(0x104, 64, 28, 4, 1, None, &src(0x400)), FootprintPlan::ViaScratch { .. })); + // with it, an offset that is not a whole texel still does + assert!(matches!(footprint_plan(0x102, 64, 28, 4, 1, Some(4), &src(0x400)), FootprintPlan::ViaScratch { .. })); + // BC1 (8-byte blocks): pitch 36 is not whole blocks + assert!(matches!(footprint_plan(0, 36, 71, 8, 1, Some(8), &src(0x400)), FootprintPlan::ViaScratch { .. })); + } + + #[test] + fn a_source_box_copies_only_its_rows_and_slices() { + // pitch 64, 4 rows x 3 slices; the box covers rows 1..3 of slices 1..2 + let side = FootprintSide::Source { buffer_bytes: 12 * 64, rows: 1..3, slices: 1..2 }; + let (_, bytes, copies) = via(footprint_plan(0, 64, 28, 4, 3, None, &side)); + assert_eq!(bytes, 12 * 256); + assert_eq!(copies, vec![ + RowCopy { buffer: 5 * 64, scratch: 5 * 256, bytes: 64 }, + RowCopy { buffer: 6 * 64, scratch: 6 * 256, bytes: 64 }, + ]); + // aligned pitch, odd offset: one copy from the first row of the box to its last + let side = FootprintSide::Source { buffer_bytes: 1 << 16, rows: 1..3, slices: 0..2 }; + let (_, _, copies) = via(footprint_plan(0x40, 256, 28, 4, 2, None, &side)); + assert_eq!(copies, vec![RowCopy { buffer: 0x40 + 256, scratch: 256, bytes: 6 * 256 }]); + } + + #[test] + fn an_aligned_footprint_goes_as_it_is() { + let side = src(1 << 20); + assert_eq!(footprint_plan(0x400, 256, 28, 16, 1, None, &side), FootprintPlan::PassThrough); + assert_eq!(footprint_plan(0, 512, 71, 64, 1, None, &side), FootprintPlan::PassThrough); + } + + #[test] + fn an_odd_pitch_copies_each_row_to_a_256_byte_pitch() { + // R8G8B8A8 16x4, rows of 64 bytes packed + let (pitch, bytes, copies) = via(footprint_plan(0x200, 64, 28, 4, 1, None, &src(0x300))); + assert_eq!((pitch, bytes), (256, 4 * 256)); + assert_eq!(copies, (0..4).map(|r| RowCopy { buffer: 0x200 + r * 64, scratch: r * 256, bytes: 64 }).collect::>()); + } + + #[test] + fn an_odd_offset_with_an_aligned_pitch_is_one_copy() { + let (pitch, bytes, copies) = via(footprint_plan(0x100, 256, 28, 8, 1, None, &src(0x100 + 8 * 256))); + assert_eq!((pitch, bytes), (256, 8 * 256)); + assert_eq!(copies, vec![RowCopy { buffer: 0x100, scratch: 0, bytes: 8 * 256 }]); + } + + #[test] + fn an_odd_offset_and_pitch_stop_at_the_end_of_the_buffer() { + // the last row is only as long as the buffer has bytes + let (pitch, _, copies) = via(footprint_plan(0x10, 100, 28, 3, 1, None, &src(0x10 + 2 * 100 + 40))); + assert_eq!(pitch, 256); + assert_eq!(copies[2], RowCopy { buffer: 0x10 + 200, scratch: 512, bytes: 40 }); + assert_eq!(copies.len(), 3); + } + + #[test] + fn block_compressed_rows_are_rows_of_blocks() { + // BC1 (71) 16x16: 4 rows of 4 blocks x 8 bytes, pitch 32 + let (pitch, bytes, copies) = via(footprint_plan(0, 32, 71, 16, 1, None, &src(128))); + assert_eq!((pitch, bytes, copies.len()), (256, 4 * 256, 4)); + assert_eq!(copies[3], RowCopy { buffer: 96, scratch: 768, bytes: 32 }); + } + + #[test] + fn depth_slices_follow_one_another() { + // 3D, 2 rows per slice, 3 slices, pitch 64 + let (_, bytes, copies) = via(footprint_plan(0, 64, 28, 2, 3, None, &src(6 * 64))); + assert_eq!((bytes, copies.len()), (6 * 256, 6)); + assert_eq!(copies[5], RowCopy { buffer: 5 * 64, scratch: 5 * 256, bytes: 64 }); + } + + #[test] + fn texture_to_buffer_writes_back_only_the_copied_bytes() { + // into a packed 2-slice footprint (pitch 64, 4 rows/slice): rows 1..3, slice 1, bytes 8..24 + let side = FootprintSide::Destination { rows: 1..3, slices: 1..2, bytes: 8..24 }; + let (pitch, bytes, copies) = via(footprint_plan(0x40, 64, 28, 4, 2, None, &side)); + assert_eq!((pitch, bytes), (256, 8 * 256)); + assert_eq!(copies, vec![ + RowCopy { buffer: 0x40 + 5 * 64 + 8, scratch: 5 * 256 + 8, bytes: 16 }, + RowCopy { buffer: 0x40 + 6 * 64 + 8, scratch: 6 * 256 + 8, bytes: 16 }, + ]); + assert_eq!(footprint_plan(0x200, 256, 28, 4, 2, None, &side), FootprintPlan::PassThrough); + } +} + /// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12) pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { let _c = super::capture::op(this, || { @@ -5513,6 +5817,10 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds note_copy_into(this as usize, transmute_copy::<_, usize>(&l.pResource), f.Offset, n); } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; + if copy_texture_region_realigned(this, &d, x, y, z, &s, bx) { + std::mem::forget((d, s)); // borrowed resource pointers + return; + } if !super::format_alias::try_copy_texture_region(this, &d, x, y, z, &s, bx) { pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); } From 7cb4b38cc25989dac203e91e974b984b98ded1c7 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:42:34 -0500 Subject: [PATCH 112/175] D3D12.X: stencil, topology and scissor sets go into deferred two-pass runs With XCL_TWO_PASS_BATCH=2 a run of deferred two-pass draws was recorded before every title call except the root signature / argument sets, SetPipelineState to a two-pass pipeline, ExecuteIndirect and DispatchMesh. On the retail title we run, OMSetStencilRef ended most runs, then IASetPrimitiveTopology, the console's stub method #142 and RSSetScissorRects (run ends at 533 s: 470,956 / 90,177 / 69,975 / 32,433 of 1,048,576), so runs were 12.7 draws long. OMSetStencilRef, IASetPrimitiveTopology and RSSetScissorRects now go into the run (RunItem / Step / Cmd StencilRef, Topology, Scissors) and are set among the mesh passes where the title made them, so each mesh pass draws with the state of its draw; a run with no draws applies them as they came. The newer layout's #142, which XCL stubs (it records nothing), no longer ends a run. Runs are then 24.3 draws long. Measured on the title (RTX 5070 Ti, timed 480 s runs, one each, same build and env with XCL_TWO_PASS_BATCH=2): 10.2-10.3 fps with runs ended as before, 11.1-11.2 fps with this. Tests: the kept slots, and runs with stencil / topology / scissor sets between draws give each mesh pass the state and order the unbatched path gives it. Upstream PR #3036 (6f3ad70c on origin/main), cherry-picked: the deferred runs of XCL_TWO_PASS_BATCH=2 go on across these sets on the title run here too. No change to translated shaders. (cherry picked from commit 6f3ad70ccc22acb777205cdea1d512bf24421299) Co-Authored-By: Antigravity (Gemini 4 Neon) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 133 +++++++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/list_x.rs | 40 ++++++++- 2 files changed, 158 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8e2750dad6..73e19bc2c5 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1329,13 +1329,19 @@ struct DrawSnap { enum RunItem { Draw(DeferredDraw), Bind { pso: usize, _held: Option }, + StencilRef(u32), + Topology(u32), + Scissors(Vec<[i32; 4]>), } /// A run item as `batch_commands` takes it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] enum Step { Draw(DrawSnap), Bind(usize), + StencilRef(u32), + Topology(u32), + Scissors(Vec<[i32; 4]>), } impl RunItem { @@ -1343,6 +1349,9 @@ impl RunItem { match self { RunItem::Draw(d) => Step::Draw(d.snap), RunItem::Bind { pso, .. } => Step::Bind(*pso), + RunItem::StencilRef(r) => Step::StencilRef(*r), + RunItem::Topology(t) => Step::Topology(*t), + RunItem::Scissors(r) => Step::Scissors(r.clone()), } } } @@ -1416,7 +1425,7 @@ fn batch_region_bytes(need: u64) -> u64 { /// the console's own methods – records the run first. fn keeps_two_pass_batch(slot: usize, newer_layout: bool) -> bool { let (ei, dm) = if newer_layout { (61, 129) } else { (59, 127) }; - matches!(slot, 0..=8 | 25 | 33..=46) || slot == ei || slot == dm + matches!(slot, 0..=8 | 20 | 22 | 24 | 25 | 33..=46) || slot == ei || slot == dm || (newer_layout && slot == 142) } /// Whether a list call through `slot` records the list's deferred draws first. @@ -1551,6 +1560,12 @@ enum Cmd { Indirect(usize, usize, u64), /// the title's SetPipelineState to the pipeline `p`, as without a run (`real::bind_pipeline`) Bind(usize), + /// the title's OMSetStencilRef between deferred draws, replayed before subsequent mesh passes + StencilRef(u32), + /// the title's IASetPrimitiveTopology between deferred draws, replayed before subsequent mesh passes + Topology(u32), + /// the title's RSSetScissorRects between deferred draws, replayed before subsequent mesh passes + Scissors(Vec<[i32; 4]>), /// an `XCL_GPU_TIMES` span: the rewrites and compute passes (None), the mesh pass of draw `d` TimesBegin(Option), TimesEnd, @@ -1620,6 +1635,18 @@ fn batch_commands(steps: &[Step], records: usize, open: bool) -> Vec { pso = 0; continue; } + Step::StencilRef(r) => { + v.push(Cmd::StencilRef(*r)); + continue; + } + Step::Topology(t) => { + v.push(Cmd::Topology(*t)); + continue; + } + Step::Scissors(r) => { + v.push(Cmd::Scissors(r.clone())); + continue; + } Step::Draw(d) => d, }; v.push(Cmd::TimesBegin(Some(i))); @@ -1677,6 +1704,9 @@ unsafe fn emit_commands(this: *mut c_void, list: &ID3D12GraphicsCommandList, cmd Cmd::DispatchMesh(n) => pc_dm(this, *n, 1, 1), Cmd::Indirect(sig, buf, at) => pc_ei(this, *sig, 1, *buf, *at, 0, 0), Cmd::Bind(p) => super::real::bind_pipeline(this, *p as *mut c_void), + Cmd::StencilRef(r) => super::list_x::apply_stencil_ref(this, *r), + Cmd::Topology(t) => super::list_x::apply_topology(this, *t), + Cmd::Scissors(r) => super::list_x::apply_scissors(this, r), Cmd::TimesBegin(None) => super::gpu_times::before(this, 0, super::gpu_times::Kind::MeshBatch, [draws.len() as u32, 0, 0], false), Cmd::TimesBegin(Some(d)) => { let d = &draws[*d]; @@ -1698,10 +1728,14 @@ pub(super) unsafe fn flush_two_pass(this: *mut c_void, why: RunEnd) { let (items, records, open) = with(this, |s| (std::mem::take(&mut s.deferred), s.batch_buf.as_ref().map(|b| b.res.clone()), s.batch_open)); let draws: Vec<&DeferredDraw> = items.iter().filter_map(|i| if let RunItem::Draw(d) = i { Some(d) } else { None }).collect(); if draws.is_empty() { - // (pipeline sets only: as they would have gone) + // (queued state sets only: as they would have gone) for i in &items { - if let RunItem::Bind { pso: p, .. } = i { - super::real::bind_pipeline(this, *p as *mut c_void); + match i { + RunItem::Bind { pso: p, .. } => super::real::bind_pipeline(this, *p as *mut c_void), + RunItem::StencilRef(r) => super::list_x::apply_stencil_ref(this, *r), + RunItem::Topology(t) => super::list_x::apply_topology(this, *t), + RunItem::Scissors(r) => super::list_x::apply_scissors(this, r), + RunItem::Draw(_) => {} } } return; @@ -1764,6 +1798,36 @@ unsafe fn batch_region(this: *mut c_void, region: u64) -> Result { va.map(|va| va + at).ok_or_else(|| "no batch record buffer".into()) } +/// Queue `OMSetStencilRef` into the list's deferred two-pass run when deferring, so it replays +/// in title order between mesh passes instead of flushing the batch. +pub(super) unsafe fn queue_stencil_ref(this: *mut c_void, r: u32) -> bool { + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 || !DEFERRING.contains(this as usize) { + return false; + } + with(this, |s| s.deferred.push(RunItem::StencilRef(r))); + true +} + +/// Queue `IASetPrimitiveTopology` into the list's deferred two-pass run when deferring, so it +/// replays in title order between mesh passes instead of flushing the batch. +pub(super) unsafe fn queue_topology(this: *mut c_void, t: u32) -> bool { + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 || !DEFERRING.contains(this as usize) { + return false; + } + with(this, |s| s.deferred.push(RunItem::Topology(t))); + true +} + +/// Queue `RSSetScissorRects` into the list's deferred two-pass run when deferring, so it +/// replays in title order between mesh passes instead of flushing the batch. +pub(super) unsafe fn queue_scissors(this: *mut c_void, rects: Vec<[i32; 4]>) -> bool { + if DEFERRING_LISTS.load(Ordering::Relaxed) == 0 || !DEFERRING.contains(this as usize) { + return false; + } + with(this, |s| s.deferred.push(RunItem::Scissors(rects))); + true +} + /// `draw` deferred on `this`; the run is recorded when it has `batch_most` draws. unsafe fn push_deferred(this: *mut c_void, draw: DeferredDraw) { let n = with(this, |s| { @@ -6291,31 +6355,36 @@ void main(uint t : SV_GroupIndex) { let (mut cv, mut gv) = (BTreeMap::new(), BTreeMap::new()); let mut out = Vec::new(); for c in cmds { - match *c { + match c { Cmd::ComputeRs(r) => { + let r = *r; if r != crs { cv.clear(); } crs = r; } Cmd::GraphicsRs(r) => { + let r = *r; if r != grs { gv.clear(); } grs = r; } - Cmd::Pso(p) => pso = p, + Cmd::Pso(p) => pso = *p, Cmd::ComputeView(s, va) => { - cv.insert(s, va); + cv.insert(*s, *va); } Cmd::GraphicsView(s, va) => { - gv.insert(s, va); + gv.insert(*s, *va); } Cmd::Dispatch(_) | Cmd::Indirect(0xD0, ..) => out.push(Call { call: c.clone(), pso, rs: crs, views: cv.clone() }), Cmd::DispatchMesh(_) | Cmd::Indirect(..) => out.push(Call { call: c.clone(), pso, rs: grs, views: gv.clone() }), // (the title's pipeline set, with what it sets: as a call of its own, in order) Cmd::Bind(p) => { - pso = p; + pso = *p; + out.push(Call { call: c.clone(), pso, rs: 0, views: BTreeMap::new() }); + } + Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_) => { out.push(Call { call: c.clone(), pso, rs: 0, views: BTreeMap::new() }); } Cmd::Barriers { .. } | Cmd::TimesBegin(_) | Cmd::TimesEnd => {} @@ -6360,6 +6429,9 @@ void main(uint t : SV_GroupIndex) { for s in &run { match s { Step::Bind(p) => alone.push(calls(&[Cmd::Bind(*p)])[0].clone()), + Step::StencilRef(r) => alone.push(calls(&[Cmd::StencilRef(*r)])[0].clone()), + Step::Topology(t) => alone.push(calls(&[Cmd::Topology(*t)])[0].clone()), + Step::Scissors(r) => alone.push(calls(&[Cmd::Scissors(r.clone())])[0].clone()), Step::Draw(d) => alone.extend(calls(&unbatched_commands(d))), } } @@ -6386,6 +6458,40 @@ void main(uint t : SV_GroupIndex) { assert_eq!(cmds.iter().filter(|c| matches!(c, Cmd::Barriers { .. })).count(), 3, "still three ResourceBarrier calls"); } + /// A run with the title's stencil reference, topology and scissor sets between its draws: the + /// sets come among the mesh passes where the title made them (each mesh pass draws with the + /// state of its draw, as the unbatched path gives it), none among the compute passes. + #[test] + fn state_sets_in_a_run_come_between_the_mesh_passes_in_the_titles_order() { + let run = vec![ + Step::Draw(snap(0, None)), + Step::StencilRef(3), + Step::Draw(snap(1, Some(0xB1))), + Step::Scissors(vec![[0, 0, 640, 360]]), + Step::Topology(4), + Step::Draw(snap(2, None)), + Step::Scissors(Vec::new()), + Step::Draw(snap(3, None)), + ]; + let cmds = batch_commands(&run, 0x900, false); + let mut alone = Vec::new(); + for s in &run { + match s { + Step::StencilRef(r) => alone.push(Cmd::StencilRef(*r)), + Step::Topology(t) => alone.push(Cmd::Topology(*t)), + Step::Scissors(r) => alone.push(Cmd::Scissors(r.clone())), + Step::Draw(d) => alone.extend(unbatched_commands(d)), + Step::Bind(p) => alone.push(Cmd::Bind(*p)), + } + } + let mesh_side = |c: &[Cmd]| -> Vec { + c.iter().filter(|x| matches!(x, Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_) | Cmd::DispatchMesh(_) | Cmd::Indirect(0xD1, ..))).cloned().collect() + }; + assert_eq!(mesh_side(&cmds), mesh_side(&alone)); + let first_mesh = cmds.iter().position(|c| matches!(c, Cmd::TimesBegin(Some(_)))).unwrap(); + assert!(!cmds[..first_mesh].iter().any(|c| matches!(c, Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_))), "no state set among the compute passes"); + } + /// SetPipelineState with no deferred draws binds as it always did; with them a two-pass /// pipeline goes into the run and any other pipeline records the run first. Into the run, it /// becomes the pipeline the next draws resolve, and nothing is recorded yet. @@ -6529,11 +6635,14 @@ void main(uint t : SV_GroupIndex) { for newer in [false, true] { let kept: Vec = (0..600).filter(|&s| keeps_two_pass_batch(s, newer)).collect(); let (ei, dm) = if newer { (61, 129) } else { (59, 127) }; - let want: Vec = (0..=8).chain([25]).chain(33..=46).chain([ei, dm]).collect(); + let mut want: Vec = (0..=8).chain([20, 22, 24, 25]).chain(33..=46).chain([ei, dm]).collect(); + if newer { + want.push(142); + } assert_eq!(kept, want, "newer layout: {newer}"); // pipelines, barriers, draws, dispatches, copies, clears, IA / RS / OM state, heaps, // queries, predication, bundles, markers, Close, Reset, the console's own methods - for slot in [26, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 27, 28, 29, 30, 31, 32, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 9, 10, 11, 60, 67, 78, 81, 85, 93, 104, 105, 106, 124, 125, 139, 146, 148] { + for slot in [26, 12, 13, 14, 15, 16, 17, 18, 19, 21, 23, 27, 28, 29, 30, 31, 32, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 9, 10, 11, 60, 67, 78, 81, 85, 93, 104, 105, 106, 124, 125, 139, 146, 148] { assert!(flush_wanted(slot, newer, true, true), "slot {slot}, newer layout: {newer}"); } // the other layout's DispatchMesh / ExecuteIndirect slots are other methods there diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 58795d9583..6ee560428b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -666,6 +666,13 @@ pub(super) unsafe extern "system" fn ia_set_topology_x(this: *mut c_void, t: u32 crate::xlog_warn!("D3D12.X: IASetPrimitiveTopology({t}) – a console topology the PC does not have{}", if t == RECT_LIST { ": rect lists are drawn as triangle lists, completed by a GS in rect list pipelines" } else { "" }); } } + if super::bind::queue_topology(this, t) { + return; + } + apply_topology(this, t); +} + +pub(super) unsafe fn apply_topology(this: *mut c_void, t: u32) { let rect = t == RECT_LIST; let t = if t == RECT_LIST { windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32 } else { t }; with_bindings(this, |b| { @@ -694,13 +701,33 @@ pub(super) unsafe extern "system" fn rs_set_scissors_x(this: *mut c_void, n: u32 let rs = if r.is_null() { &[][..] } else { std::slice::from_raw_parts(r, n as usize) }; Some(super::capture::Op::Scissors(rs.iter().map(|r| [r.left, r.top, r.right, r.bottom]).collect())) }); - if !r.is_null() { - let rs = std::slice::from_raw_parts(r, n as usize).to_vec(); - with_bindings(this, |b| b.scissors = rs); + if !r.is_null() && n > 0 { + let rs = std::slice::from_raw_parts(r, n as usize); + let rects: Vec<[i32; 4]> = rs.iter().map(|r| [r.left, r.top, r.right, r.bottom]).collect(); + if super::bind::queue_scissors(this, rects) { + return; + } + with_bindings(this, |b| b.scissors = rs.to_vec()); + } else if r.is_null() || n == 0 { + if super::bind::queue_scissors(this, Vec::new()) { + return; + } } pc::(this, PC_RS_SET_SCISSOR_RECTS)(this, n, r) } +pub(super) unsafe fn apply_scissors(this: *mut c_void, rects: &[[i32; 4]]) { + let rs: Vec = rects + .iter() + .map(|&[left, top, right, bottom]| windows::Win32::Foundation::RECT { left, top, right, bottom }) + .collect(); + if !rs.is_empty() { + with_bindings(this, |b| b.scissors = rs.clone()); + } + let ptr = if rs.is_empty() { std::ptr::null() } else { rs.as_ptr() }; + pc::(this, PC_RS_SET_SCISSOR_RECTS)(this, rs.len() as u32, ptr) +} + /// console #23 OMSetBlendFactor (PC #23) pub(super) unsafe extern "system" fn om_set_blend_factor_x(this: *mut c_void, f: *const [f32; 4]) { let v = f.as_ref().copied(); @@ -710,6 +737,13 @@ pub(super) unsafe extern "system" fn om_set_blend_factor_x(this: *mut c_void, f: /// console #24 OMSetStencilRef (PC #24) pub(super) unsafe extern "system" fn om_set_stencil_ref_x(this: *mut c_void, r: u32) { + if super::bind::queue_stencil_ref(this, r) { + return; + } + apply_stencil_ref(this, r); +} + +pub(super) unsafe fn apply_stencil_ref(this: *mut c_void, r: u32) { with_bindings(this, |b| b.stencil = Some(r)); pc::(this, PC_OM_SET_STENCIL_REF)(this, r) } From c7388f3d27739a300ae71f12131d972ec64d57d9 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:06:36 +0100 Subject: [PATCH 113/175] D3D12.X: deferred two-pass runs of all lists share one record buffer With XCL_TWO_PASS_BATCH=2 each list took a batch record buffer of its own (XCL_TWO_PASS_BATCH_MB, 128 MiB) at its first deferred draw and held it until its allocator was reset, and a new one was made only while the two-pass buffers alive left half of XCL_TWO_PASS_MB: four lists at a time at the defaults. The retail title run here records well over a hundred lists with two-pass draws a frame on six threads (about 7,000 two-pass draws a second), so nearly every draw would have gone at once, unbatched. XCL_TWO_PASS_BATCH_SHARED (default on; =0 keeps a buffer of each list) gives every list of a device one shared batch record buffer of XCL_TWO_PASS_BATCH_MB, as the draws that go at once already share SHARED_RECORDS. Each recording takes its regions from the start of it. A queue runs its lists in order and each recording's first run now starts with a UAV barrier on the buffer (batch_open), as every later run of a recording already did after the last one's mesh passes, so no run writes records that another recording's mesh passes may still read. The lists that use it are counted by note_records_queue: when two-pass lists go to a second queue the lists take buffers of their own again. Measured offline on the RX 9070 XT (a scratch harness that records the sequences of two_pass_plan and batch_commands with XCL's argument rewrite, 64 one-command ExecuteIndirect draws, a wave64 compute pass of 128 threads and a mesh pass drawing its record): GPU time a draw 85 % of the draws with no groups (as the title's culled draws): unbatched 4.58 us, XCL_TWO_PASS_BATCH=1 3.59 us, deferred runs of 4 1.19 us, of 12 0.70 us, of 24 0.52 us, of 64 0.42 us every draw 2 groups: 12.24 / 9.88 / 0.67 us (runs of 64) half the draws with a 4,000-step dependent loop: 40.7 / 35.8 us, runs of 4 9.2 us, of 12 4.6 us, of 24 2.5 us The game's own mesh draws cost 9-80 us a call in a retail run's GPU times (23 programs, 41.5 ms a frame over 1,835 calls). No change to translated shaders. Test: two recordings take their regions from the start of the shared buffer, each starting with a barrier; one that is reset lets it go and starts so again; with the switch off a list takes a buffer of its own. --- crates/xcl/src/hle/d3d12x/bind.rs | 144 ++++++++++++++++++++++++++++-- 1 file changed, 136 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 73e19bc2c5..91309bc2d4 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -62,6 +62,9 @@ struct State { batch_buf: Option, batch_used: u64, batch_open: bool, + /// the device's batch record buffer (`XCL_TWO_PASS_BATCH_SHARED`), and its bytes, when this + /// recording's deferred draws take their regions there instead of in `batch_buf` + batch_shared: Option<(ID3D12Resource, u64)>, /// the next dispatch's thread limits (`IO_THREAD_LIMIT`; a `DispatchX` with thread /// dimensions), taken by its `bind_abi` limits: [u32; 3], @@ -477,9 +480,16 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { impl State { /// The deferred draws of a recording that ends without them (a Reset without a Close, a /// list let go): dropped, and the buffer of their records for the caller to hold. + /// The buffer this recording's deferred draws take their regions in (the device's shared + /// one or its own), and its bytes. + fn batch_records(&self) -> Option<(&ID3D12Resource, u64)> { + self.batch_shared.as_ref().map(|(r, b)| (r, *b)).or_else(|| self.batch_buf.as_ref().map(|b| (&b.res, b.bytes))) + } + fn end_batch(&mut self) -> Option { self.deferred.clear(); (self.batch_used, self.batch_open) = (0, false); + self.batch_shared = None; self.batch_buf.take() } } @@ -1280,13 +1290,59 @@ fn batch_most() -> usize { *MOST.get_or_init(|| std::env::var("XCL_TWO_PASS_BATCH_MOST").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(64).max(1)) } -/// Bytes of a list's batch record buffer (`XCL_TWO_PASS_BATCH_MB`, 128 MiB by default; read -/// once). An ExecuteIndirect's region is what its draw would have had alone, up to 32 MiB. +/// Bytes of a list's batch record buffer, or of the device's shared one (`XCL_TWO_PASS_BATCH_MB`, +/// 128 MiB by default; read once). An ExecuteIndirect's region is what its draw would have had +/// alone, up to 32 MiB. fn batch_records_bytes() -> u64 { static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); *BYTES.get_or_init(|| std::env::var("XCL_TWO_PASS_BATCH_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(128).clamp(1, 1024) << 20) } +/// `XCL_TWO_PASS_BATCH_SHARED` (default on; `=0`: a buffer of each list; read once): the deferred +/// draws of every list of a device take their regions in one batch record buffer +/// (`SHARED_BATCH`), as the draws that go at once share `SHARED_RECORDS`, while all the lists +/// that use them go to one queue (`note_records_queue`). +/// +/// A list's own buffer is held from its first deferred draw until its allocator is reset, and a +/// new one is made only while the two-pass buffers alive leave half of `XCL_TWO_PASS_MB`: at the +/// defaults four lists at a time. A retail title's world frame records more than a hundred lists +/// with two-pass draws, on several threads at once, so nearly all of them went at once. A queue +/// runs its lists in order, and every run of a recording that uses the shared buffer starts with +/// a UAV barrier on it (the first: `batch_open`; the others after the last run's mesh passes, as +/// with a buffer of its own), so no run writes records another recording's mesh passes may still +/// read. +fn shared_batch_on() -> bool { + #[cfg(test)] + if let Some(on) = SHARED_BATCH_FOR_TEST.with(|c| c.get()) { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TWO_PASS_BATCH_SHARED").map_or(true, |v| v.trim() != "0")) +} + +#[cfg(test)] +thread_local! { + /// `shared_batch_on` for this test thread + static SHARED_BATCH_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The batch record buffer the deferred draws of all lists of a device share (buffer, bytes, +/// device), made at the first deferred draw (`shared_batch_on`). +static SHARED_BATCH: Mutex> = Mutex::new(Vec::new()); + +/// The shared batch record buffer of `dev` (`bytes` when it is made now) and its bytes. +unsafe fn shared_batch_buffer(dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let key = dev.as_raw() as usize; + let mut all = SHARED_BATCH.lock().unwrap(); + if let Some((buf, cap, _)) = all.iter().find(|(_, _, d)| *d == key) { + return Ok((buf.clone(), *cap)); + } + let buf = default_uav_buffer(dev, bytes, "shared two-pass batch records")?; + crate::xlog_info!("D3D12.X: deferred two-pass draws: the records of every list's runs in one buffer of {} MiB (XCL_TWO_PASS_BATCH_SHARED, XCL_TWO_PASS_BATCH_MB)", bytes >> 20); + all.push((buf.clone(), bytes, key)); + Ok((buf, bytes)) +} + /// Lists with deferred draws, and how many (the hook in front of every list call looks at the /// count first). static DEFERRING: super::sharded::Sharded = super::sharded::Sharded::new(); @@ -1725,7 +1781,7 @@ pub(super) unsafe fn flush_two_pass(this: *mut c_void, why: RunEnd) { return; } unmark_deferring(this); - let (items, records, open) = with(this, |s| (std::mem::take(&mut s.deferred), s.batch_buf.as_ref().map(|b| b.res.clone()), s.batch_open)); + let (items, records, open) = with(this, |s| (std::mem::take(&mut s.deferred), s.batch_records().map(|(r, _)| r.clone()), s.batch_open)); let draws: Vec<&DeferredDraw> = items.iter().filter_map(|i| if let RunItem::Draw(d) = i { Some(d) } else { None }).collect(); if draws.is_empty() { // (queued state sets only: as they would have gone) @@ -1769,7 +1825,16 @@ pub(super) unsafe fn flush_two_pass(this: *mut c_void, why: RunEnd) { /// (the run so far is recorded first when it does not fit): its GPU address. unsafe fn batch_region(this: *mut c_void, region: u64) -> Result { let bytes = batch_records_bytes(); - if with(this, |s| s.batch_buf.is_none()) { + if with(this, |s| s.batch_records().is_none()) { + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + if shared_batch_on() && !RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed) { + let shared = shared_batch_buffer(&dev, bytes)?; + // (another recording's mesh passes may still read it: the first run starts with a + // barrier on it) + with(this, |s| (s.batch_shared, s.batch_used, s.batch_open) = (Some(shared), 0, true)); + } + } + if with(this, |s| s.batch_records().is_none()) { let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; let buf = match take_free(dev.as_raw() as usize, bytes, bytes) { Some(b) => b, @@ -1780,7 +1845,7 @@ unsafe fn batch_region(this: *mut c_void, region: u64) -> Result { }; with(this, |s| (s.batch_buf, s.batch_used, s.batch_open) = (Some(buf), 0, false)); } - let (used, cap) = with(this, |s| (s.batch_used, s.batch_buf.as_ref().map_or(0, |b| b.bytes))); + let (used, cap) = with(this, |s| (s.batch_used, s.batch_records().map_or(0, |(_, b)| b))); let at = match batch_place(used, region, cap) { Some(at) => at, None => { @@ -1793,7 +1858,7 @@ unsafe fn batch_region(this: *mut c_void, region: u64) -> Result { } let va = with(this, |s| { s.batch_used = at + region; - s.batch_buf.as_ref().map(|b| b.res.GetGPUVirtualAddress()) + s.batch_records().map(|(r, _)| r.GetGPUVirtualAddress()) }); va.map(|va| va + at).ok_or_else(|| "no batch record buffer".into()) } @@ -1949,12 +2014,12 @@ static RECORDS_QUEUE: std::sync::atomic::AtomicUsize = std::sync::atomic::Atomic static RECORDS_QUEUES_DIFFER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// `lists` go to `queue` now (`present::note_execute`): the ones that used the shared record -/// buffer must all go to one queue. +/// buffer (or the shared batch record buffer) must all go to one queue. pub(super) fn note_records_queue(queue: usize, lists: &[*mut c_void]) { if RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed) { return; } - let used = lists.iter().any(|&l| STATES.contains(l as usize) && with(l, |s| s.shared_records)); + let used = lists.iter().any(|&l| STATES.contains(l as usize) && with(l, |s| s.shared_records || s.batch_shared.is_some())); if used && !same_records_queue(&RECORDS_QUEUE, queue) { RECORDS_QUEUES_DIFFER.store(true, Ordering::Relaxed); crate::xlog_warn!("D3D12.X: two-pass draws go to a second queue ({queue:#x}): the record buffers are the lists' own from here"); @@ -6730,6 +6795,69 @@ void main(uint t : SV_GroupIndex) { assert!(DEFERRING_LISTS.load(Ordering::Relaxed) <= before + 1); } + /// With `XCL_TWO_PASS_BATCH_SHARED` the deferred draws of every recording of a device take + /// their regions in one buffer, each recording's from its start, and a recording's first run + /// starts with a barrier on it (another recording's mesh passes may still read it); one that + /// ends lets it go and starts so again. Without it a list has a buffer of its own, which + /// nothing else reads before its first run. + #[test] + fn gpu_deferred_draws_of_all_lists_share_one_batch_buffer() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + static DEV: AtomicU64 = AtomicU64::new(0); + #[repr(C)] + struct FakeList { + vt: *const usize, + } + unsafe extern "system" fn get_device(_this: *mut c_void, _riid: *const windows::core::GUID, ppv: *mut *mut c_void) -> windows::core::HRESULT { + let raw = DEV.load(Ordering::Relaxed) as *mut c_void; + let dev = ID3D12Device::from_raw_borrowed(&raw).cloned().unwrap(); + *ppv = dev.into_raw(); + windows::core::HRESULT(0) + } + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + if RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed) { + crate::gpu::recomp::runner::skip_test("two-pass draws went to a second queue in this process"); + return; + } + let dev = dev.unwrap(); + DEV.store(dev.as_raw() as u64, Ordering::Relaxed); + let mut orig_vt = [0usize; 16]; + orig_vt[7] = get_device as usize; + let mut ext_vt = vec![0usize; 17]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let lists: Vec> = (0..3).map(|_| Box::new(FakeList { vt: unsafe { ext_vt.as_ptr().add(1) } })).collect(); + let [a, b, c] = [0, 1, 2].map(|k| &*lists[k] as *const FakeList as *mut c_void); + unsafe { + SHARED_BATCH_FOR_TEST.with(|s| s.set(Some(true))); + let a1 = batch_region(a, 4096).unwrap(); + let a2 = batch_region(a, 4096).unwrap(); + let b1 = batch_region(b, 4096).unwrap(); + assert_eq!(a2, a1 + 4096, "a recording's regions one after the other"); + assert_eq!(b1, a1, "every recording's from the shared buffer's start"); + for l in [a, b] { + assert!(with(l, |s| s.batch_shared.is_some() && s.batch_buf.is_none() && s.batch_open), "a barrier before the first run"); + } + reset(a, 0, 0); + assert!(with(a, |s| s.batch_shared.is_none() && !s.batch_open)); + assert_eq!(batch_region(a, 4096).unwrap(), a1); + assert!(with(a, |s| s.batch_open), "the next recording's first run too"); + SHARED_BATCH_FOR_TEST.with(|s| s.set(Some(false))); + let c1 = batch_region(c, 4096).unwrap(); + assert_ne!(c1, a1); + assert!(with(c, |s| s.batch_shared.is_none() && s.batch_buf.is_some() && !s.batch_open), "a buffer of its own"); + SHARED_BATCH_FOR_TEST.with(|s| s.set(None)); + for l in [a, b, c] { + forget(l); + } + } + drop(lists); + } + #[test] fn gpu_two_pass_argument_scratch_is_shared_and_capped() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; From 34e95e7b309f81059a0bafd53f5cbdc30bae2156 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:13:16 +0100 Subject: [PATCH 114/175] D3D12.X: deferred two-pass ExecuteIndirects take smaller record regions An ExecuteIndirect's groups are known on the GPU only, so a deferred one (XCL_TWO_PASS_BATCH=2) took a region of its batch record buffer the size the draw would have alone: up to XCL_TWO_PASS_LIST_MB (32 MiB), 5,028 groups of the 6,672 B records of the title's skinned depth programs. Four of them filled a 128 MiB buffer and ended the run ("the batch record buffer full"), while most of these draws have no groups at all (earlier XCL_TRACE_ARGS runs: 10,246 of 12,032 draws of one program read back empty, the rest mostly a few groups). XCL_TWO_PASS_DEFER_MB (4 by default; 0 = the region of the draw alone) limits a deferred ExecuteIndirect's region to that, never more than the draw alone: 628 groups of 6,672 B, 32 draws in a 128 MiB buffer. A command that asks for more groups than its region holds keeps what fits, as one past 32 MiB alone always did, and the argument rewrite marks its pipeline: SCALE_ARGS_HLSL gets a fifth root view (u5, the marks; the constants when none are named, so every declared view has an address) and writes dword 9 - 1 of it when a command's groups pass `cap`. The marks are 4,096 dwords of a custom-heap buffer in system memory, mapped for good, one slot per pipeline (its compute pass's object, hashed); a marked pipeline's later deferred draws take the region of the draw alone, so a draw larger than the limit can lose its groups past it for a frame or so, until its rewrite has run and the CPU sees the mark. A log line names each pipeline seen marked. No change to translated shaders (the rewrite is XCL's own compute pass, one small pipeline built again). Tests: on the GPU, commands over `cap` in X or in X*Y*Z set the named mark and keep `cap` groups; ones within it, with no groups or past the count leave it, and with no mark named nothing is written; the region a deferred draw asks for with and without the limit and a mark; slots stay inside the marks and spread over them. --- crates/xcl/src/hle/d3d12x/bind.rs | 234 ++++++++++++++++++++++++++---- 1 file changed, 203 insertions(+), 31 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 91309bc2d4..6b952d9e27 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1951,7 +1951,18 @@ unsafe fn defer_dispatch_mesh(this: *mut c_void, tp: &Arc, pso: usize, raw_pso: usize, sig: usize, msig: DispatchMeshSig, max: u32, src: usize, count: Option) -> bool { let record_bytes = tp.record.record_dwords() as u64 * 4; - let region = batch_region_bytes(indirect_record_need(record_bytes, tp.mesh_groups_per_record)); + let alone = indirect_record_need(record_bytes, tp.mesh_groups_per_record); + // (`XCL_TWO_PASS_DEFER_MB`: a smaller region, unless the pipeline's draws were seen to need more) + let defer = defer_region_mb() << 20; + let marks = if defer != 0 { super::real::list_device(this).and_then(|d| defer_marks(&d)) } else { None }; + let slot = mark_slot(tp.compute); + let marked = marks.is_some_and(|(_, p)| std::ptr::read_volatile((p as *const u32).add(slot as usize)) != 0); + if marked { + note_marked(slot, pso, tp.kind, alone); + } + let need = if marks.is_some() { deferred_indirect_need(alone, defer, marked) } else { alone }; + let mark = marks.filter(|_| need < alone).map(|(va, _)| (va, slot)); + let region = batch_region_bytes(need); let ty = super::list_x::tracked_list_type(this); if defer_check(true, ty, super::capture::on(), max, region, batch_records_bytes()).is_err() { return false; @@ -1964,7 +1975,7 @@ unsafe fn defer_execute_indirect(this: *mut c_void, tp: &Arc u64 { + static MB: std::sync::OnceLock = std::sync::OnceLock::new(); + *MB.get_or_init(|| std::env::var("XCL_TWO_PASS_DEFER_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(4).min(1024)) +} + +/// The record bytes a deferred ExecuteIndirect asks for: what it would have `alone`, at most +/// `defer` (0: no limit) unless its pipeline is `marked`. +fn deferred_indirect_need(alone: u64, defer: u64, marked: bool) -> u64 { + if defer == 0 || marked { + alone + } else { + alone.min(defer) + } +} + +/// Dwords of the marks (`defer_marks`). +const MARK_SLOTS: u32 = 4096; + +/// The marks of a device (buffer, GPU address, CPU mapping, device): one dword a slot +/// (`mark_slot`), set by the argument rewrite of a deferred ExecuteIndirect whose command asked +/// for more groups than its region held (`SCALE_ARGS_HLSL`), read by the CPU when the pipeline +/// draws again. A buffer the CPU reads where it is (a custom heap in system memory), mapped for +/// good: a mark is seen once the GPU has run the rewrite, a frame or so later. +static DEFER_MARKS: Mutex> = Mutex::new(Vec::new()); + +/// The marks of `dev` (made at the first call): their GPU address and CPU mapping. +unsafe fn defer_marks(dev: &ID3D12Device) -> Option<(u64, usize)> { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + let key = dev.as_raw() as usize; + let mut all = DEFER_MARKS.lock().unwrap(); + if let Some(&(_, va, p, _)) = all.iter().find(|e| e.3 == key) { + return Some((va, p)); + } + let bytes = 4 * MARK_SLOTS as u64; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: 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, ..Default::default() }; + let mut res: Option = None; + if let Err(e) = dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res) { + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| crate::xlog_warn!("D3D12.X: the marks of deferred two-pass draws: {e}; their regions are the draws' alone")); + return None; + } + let res = res?; + let mut p = std::ptr::null_mut(); + res.Map(0, None, Some(&mut p)).ok()?; + std::ptr::write_bytes(p as *mut u8, 0, bytes as usize); + let _ = res.SetName(&windows::core::HSTRING::from("xcl deferred two-pass marks")); + let va = res.GetGPUVirtualAddress(); + all.push((res, va, p as usize, key)); + Some((va, p as usize)) +} + +/// The marks' slot of a two-pass pipeline (by its compute pass's object): pipelines that share +/// one only take larger regions. +fn mark_slot(key: usize) -> u32 { + // (MurmurHash3's 64-bit finalizer: objects lie at regular steps) + let mut x = key as u64; + x ^= x >> 33; + x = x.wrapping_mul(0xff51_afd7_ed55_8ccd); + x ^= x >> 33; + x = x.wrapping_mul(0xc4ce_b9fe_1a85_ec53); + x ^= x >> 33; + (x % MARK_SLOTS as u64) as u32 +} + +/// The first deferred draw of a pipeline after its mark was set, for the log. +fn note_marked(slot: u32, pso: usize, kind: &str, alone: u64) { + static SEEN: Mutex>> = Mutex::new(None); + if !SEEN.lock().unwrap().get_or_insert_with(Default::default).insert(slot) { + return; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: deferred two-pass ExecuteIndirect: a draw of {kind} pipeline {pso:#x} asked for more groups than {} MiB of records hold (XCL_TWO_PASS_DEFER_MB): its draws take {} MiB from here ({n} pipelines so far)", + defer_region_mb(), + alone >> 20 + ); + } +} + /// A reference to the pipeline `pso` for as long as a deferred draw names it. unsafe fn held_pso(pso: usize) -> Option { let p = pso as *mut c_void; @@ -2213,11 +2325,13 @@ unsafe fn prepare_two_pass_stage(this: *mut c_void, real_mesh_pso: usize, tp: &s /// pass and then (at `count · stride`) for the mesh pass, with at most `cap` groups, all in X: /// both passes find a group's record by `gid.x` alone. With a count buffer (u0 dword 7 set: the /// count at dword 8's byte offset in u4), the commands past its count get no groups: they are run -/// one by one (`two_pass_steps`), so without one. +/// one by one (`two_pass_steps`), so without one. With u0 dword 9 set, a command that asks for more +/// groups than `cap` marks dword 9 − 1 of u5 (`defer_marks`). pub(super) const SCALE_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); RWByteAddressBuffer src : register(u2); RWByteAddressBuffer dst : register(u3); RWByteAddressBuffer cnt : register(u4); +RWByteAddressBuffer marks : register(u5); [numthreads(64, 1, 1)] void main(uint tid : SV_DispatchThreadID) { uint count = io.Load(0), stride = io.Load(4), offset = io.Load(8), split = io.Load(12), cap = io.Load(16); @@ -2234,11 +2348,18 @@ void main(uint tid : SV_DispatchThreadID) { } uint3 g = src.Load3(s + offset); uint n = 0u; + bool over = false; if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { n = min(g.x, cap); + over = g.x > cap || g.y > cap / n; n = g.y > cap / n ? cap : n * g.y; + over = over || g.z > cap / n; n = g.z > cap / n ? cap : n * g.z; } + uint mark = io.Load(36); + if (over && mark != 0u) { + marks.Store((mark - 1u) * 4u, 1u); + } dst.Store3(d + offset, uint3(n, 1u, 1u)); dst.Store3(m + offset, uint3(n * split, 1u, 1u)); } @@ -2270,10 +2391,10 @@ fn validate_scale_args_layout(max: u32, stride: u32, mesh_offset: u32) -> Result Ok(commands) } -/// Minimal compute root signature for `SCALE_ARGS_HLSL`: only the 4 root UAVs (`u0, u2, u3, u4`) -/// and no heap flags, so every root parameter is unconditionally bound before Dispatch. +/// Minimal compute root signature for `SCALE_ARGS_HLSL`: only the 5 root UAVs (`u0, u2, u3, u4, +/// u5`) and no heap flags, so every root parameter is unconditionally bound before Dispatch. unsafe fn scale_args_root_signature(dev: &ID3D12Device) -> Result { - let params: Vec = [0u32, 2, 3, 4] + let params: Vec = [0u32, 2, 3, 4, 5] .iter() .map(|®| D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, @@ -2372,9 +2493,10 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res /// test: a load at GPU address 0, which an NVIDIA GPU answers with a fault and a device removal /// (0x887A0006, the first operation not done in the list: this pass's Dispatch – a retail /// title's world, three times, each at the first such draw of a list). Without a count buffer -/// u4 names the constants, which are always there. -fn scale_views(consts: u64, src: u64, dst: u64, count: Option) -> [(u32, u64); 4] { - [(0, consts), (1, src), (2, dst), (3, count.unwrap_or(consts))] +/// u4 names the constants, which are always there; so does u5 without the marks of deferred +/// draws (`defer_marks`), which the program writes only when the constants name a mark. +fn scale_views(consts: u64, src: u64, dst: u64, count: Option, marks: Option) -> [(u32, u64); 5] { + [(0, consts), (1, src), (2, dst), (3, count.unwrap_or(consts)), (4, marks.unwrap_or(consts))] } /// The arguments of `max` commands at UMA address `src`, rewritten for the two passes @@ -2387,7 +2509,7 @@ fn scale_views(consts: u64, src: u64, dst: u64, count: Option) -> [(u32, u6 /// count (`count`: its UMA address, when the title gave a count buffer). #[allow(clippy::too_many_arguments)] unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, count: Option, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32, batch: bool) -> Result<(ID3D12Resource, u64), String> { - let (rewrite, dst, dst_off) = prepare_scaled_args(this, src, count, max, stride, mesh_offset, split, cap)?; + let (rewrite, dst, dst_off) = prepare_scaled_args(this, src, count, max, stride, mesh_offset, split, cap, None)?; // the title's writes of the arguments before this (`fresh_indirect_arguments`) if batch { let before = scratch_state(with(this, |s| s.scratch_in_args)); @@ -2417,14 +2539,15 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman struct Rewrite { rs: usize, pso: usize, - views: [(u32, u64); 4], + views: [(u32, u64); 5], groups: u32, } /// `make_scaled_args_buffer` up to what it records: the rewrite's constants in unified memory, -/// its place in a scratch block, the block and the offset. +/// its place in a scratch block, the block and the offset. `mark`: the marks' address and the +/// slot a command with more groups than `cap` marks (`defer_marks`). #[allow(clippy::too_many_arguments)] -unsafe fn prepare_scaled_args(this: *mut c_void, src: usize, count: Option, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result<(Rewrite, ID3D12Resource, u64), String> { +unsafe fn prepare_scaled_args(this: *mut c_void, src: usize, count: Option, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32, mark: Option<(u64, u32)>) -> Result<(Rewrite, ID3D12Resource, u64), String> { if super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) { return Err("command bundles cannot record indirect argument barriers".into()); } @@ -2450,14 +2573,14 @@ unsafe fn prepare_scaled_args(this: *mut c_void, src: usize, count: Option None, }; let (dst, dst_off) = scratch_args(this, &dev, commands.saturating_mul(2))?; - let consts: Vec = [max, stride, mesh_offset, split, cap, src_off, 0, count_bound.is_some() as u32, count_bound.map_or(0, |(_, off)| off)] + let consts: Vec = [max, stride, mesh_offset, split, cap, src_off, 0, count_bound.is_some() as u32, count_bound.map_or(0, |(_, off)| off), mark.map_or(0, |(_, slot)| slot + 1)] .iter() .flat_map(|w| w.to_le_bytes()) .collect(); let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; - let views = scale_views(consts_va, src_base, dst.GetGPUVirtualAddress() + dst_off, count_bound.map(|(base, _)| base)); + let views = scale_views(consts_va, src_base, dst.GetGPUVirtualAddress() + dst_off, count_bound.map(|(base, _)| base), mark.map(|(va, _)| va)); // (the pair is the device's for good: `scale_indirect_pipeline` keeps it) Ok((Rewrite { rs: rs.as_raw() as usize, pso: pso.as_raw() as usize, views, groups: max.div_ceil(64) }, dst, dst_off)) } @@ -6064,19 +6187,19 @@ void main(uint t : SV_GroupIndex) { assert_eq!(record_groups(1 << 20, 2 << 20, 1), 0); } - /// Every root view the argument pass's program declares (u0, u2, u3, u4) gets an address, - /// also without a count buffer: u4 then names the constants. (A slot left out after the root - /// signature is set holds nothing, and a load from it is a load at GPU address 0.) + /// Every root view the argument pass's program declares (u0, u2, u3, u4, u5) gets an address, + /// also without a count buffer or marks: u4 and u5 then name the constants. (A slot left out + /// after the root signature is set holds nothing, and a load from it is a load at GPU address 0.) #[test] fn the_argument_pass_names_a_buffer_in_every_view_it_declares() { - for register in ["u0", "u2", "u3", "u4"] { + for register in ["u0", "u2", "u3", "u4", "u5"] { assert!(SCALE_ARGS_HLSL.contains(&format!("register({register})")), "{register}"); } - assert!(!SCALE_ARGS_HLSL.contains("register(u1)") && !SCALE_ARGS_HLSL.contains("register(u5)")); - let with_count = scale_views(0x1000, 0x2000, 0x3000, Some(0x4000)); - assert_eq!(with_count, [(0, 0x1000), (1, 0x2000), (2, 0x3000), (3, 0x4000)]); - let without = scale_views(0x1000, 0x2000, 0x3000, None); - assert_eq!(without, [(0, 0x1000), (1, 0x2000), (2, 0x3000), (3, 0x1000)]); + assert!(!SCALE_ARGS_HLSL.contains("register(u1)") && !SCALE_ARGS_HLSL.contains("register(u6)")); + let with_count = scale_views(0x1000, 0x2000, 0x3000, Some(0x4000), Some(0x5000)); + assert_eq!(with_count, [(0, 0x1000), (1, 0x2000), (2, 0x3000), (3, 0x4000), (4, 0x5000)]); + let without = scale_views(0x1000, 0x2000, 0x3000, None, None); + assert_eq!(without, [(0, 0x1000), (1, 0x2000), (2, 0x3000), (3, 0x1000), (4, 0x1000)]); assert!(without.iter().all(|&(_, va)| va != 0)); assert_eq!(align_root_uav(0x1_0000_000c).unwrap(), (0x1_0000_0000, 12)); assert!(align_root_uav(0x1_0000_0002).is_err()); @@ -6092,6 +6215,16 @@ void main(uint t : SV_GroupIndex) { /// `scale_args` with a count buffer holding `count` fn scale_args_counted(commands: &[[u32; 4]], split: u32, cap: u32, count: Option) -> Option<(Vec<[u32; 4]>, Vec<[u32; 4]>)> { + let out = scale_args_memory(commands, split, cap, count, None)?; + let n = commands.len(); + let cmd = |k: usize| [out[64 + 4 * k], out[65 + 4 * k], out[66 + 4 * k], out[67 + 4 * k]]; + Some(((0..n).map(cmd).collect(), (n..2 * n).map(cmd).collect())) + } + + /// The memory after `SCALE_ARGS_HLSL` on `commands`: them at dword 0, the rewritten ones at + /// 64, the count at 60, and with `mark` (a slot), the marks from dword 48 (u4 and u5 are the + /// same memory in the runner). + fn scale_args_memory(commands: &[[u32; 4]], split: u32, cap: u32, count: Option, mark: Option) -> Option> { use crate::gpu::recomp::runner; if runner::adapter().is_err() { runner::skip_test("no GPU"); @@ -6102,13 +6235,52 @@ void main(uint t : SV_GroupIndex) { let (src, dst) = (0u32, 256u32); let mut mem: Vec = commands.iter().flatten().copied().collect(); mem.resize(64 + 2 * 4 * n, 0xDEAD); - // the count at dword 60 (u4 is the same memory in the runner) - assert!(4 * n <= 60); + assert!(4 * n <= 48); + mem[48..60].fill(0); mem[60] = count.unwrap_or(0); - let io = [n as u32, 16, 4, split, cap, src, dst, count.is_some() as u32, 240]; - let out = runner::dispatch(&dxil, [(n as u32).div_ceil(64), 1, 1], &io, &mem).unwrap(); - let cmd = |k: usize| [out[64 + 4 * k], out[65 + 4 * k], out[66 + 4 * k], out[67 + 4 * k]]; - Some(((0..n).map(cmd).collect(), (n..2 * n).map(cmd).collect())) + let io = [n as u32, 16, 4, split, cap, src, dst, count.is_some() as u32, 240, mark.map_or(0, |m| 48 + m + 1)]; + Some(runner::dispatch(&dxil, [(n as u32).div_ceil(64), 1, 1], &io, &mem).unwrap()) + } + + /// With a mark named, a command that asks for more groups than `cap` – in X, or in X·Y·Z – + /// sets it (and keeps `cap` groups, as without); commands within `cap`, with no groups, or + /// past the count leave it. With no mark named, nothing is written there. + #[test] + fn gpu_indirect_two_pass_commands_over_their_records_mark_their_pipeline() { + let mark = |commands: &[[u32; 4]], count: Option| scale_args_memory(commands, 2, 10, count, Some(3)).map(|m| m[48..60].to_vec()); + let Some(within) = mark(&[[1, 10, 1, 1], [2, 5, 2, 1], [3, 0, 900, 1], [4, 1, 1, 1]], None) else { return }; + assert!(within.iter().all(|&w| w == 0), "{within:?}"); + for over in [[1, 11, 1, 1], [1, 4, 3, 1], [1, 2, 2, 3], [1, 70_000, 70_000, 70_000]] { + let m = mark(&[[9, 1, 1, 1], over], None).unwrap(); + let set: Vec<(usize, u32)> = m.iter().copied().enumerate().filter(|e| e.1 != 0).collect(); + assert_eq!(set, [(3, 1)], "{over:?}"); + } + let past_count = mark(&[[9, 1, 1, 1], [1, 99, 1, 1]], Some(1)).unwrap(); + assert!(past_count.iter().all(|&w| w == 0), "a command past the count asks for nothing"); + let unnamed = scale_args_memory(&[[1, 99, 1, 1]], 2, 10, None, None).unwrap(); + assert!(unnamed[48..60].iter().all(|&w| w == 0)); + let (compute, _) = scale_args(&[[1, 99, 1, 1]], 2, 10).unwrap(); + assert_eq!(compute, [[1, 10, 1, 1]], "the command keeps what fits"); + } + + /// A deferred ExecuteIndirect takes at most `XCL_TWO_PASS_DEFER_MB` of records unless its + /// pipeline was marked (or the limit is off), never more than the draw alone; the marks' + /// slots stay inside the marks. + #[test] + fn deferred_indirect_draws_take_smaller_regions_until_their_pipeline_is_marked() { + let mib = 1u64 << 20; + assert_eq!(deferred_indirect_need(32 * mib, 4 * mib, false), 4 * mib); + assert_eq!(deferred_indirect_need(32 * mib, 4 * mib, true), 32 * mib); + assert_eq!(deferred_indirect_need(32 * mib, 0, false), 32 * mib); + assert_eq!(deferred_indirect_need(mib, 4 * mib, false), mib); + // 6,672 B records (the title's skinned depth programs): 628 groups in 4 MiB, 32 draws in + // a 128 MiB run + let region = batch_region_bytes(deferred_indirect_need(indirect_record_need(6672, 1), 4 * mib, false)); + assert_eq!(record_groups(region, 6672, 1), 628); + assert_eq!((128 * mib) / region, 32); + let slots: std::collections::HashSet = (0..10_000usize).map(|k| mark_slot(0x1_0000_0000 + 0x1c0 * k)).collect(); + assert!(slots.iter().all(|&s| s < MARK_SLOTS)); + assert!(slots.len() > 3000, "pipelines spread over the slots: {}", slots.len()); } #[test] @@ -6363,7 +6535,7 @@ void main(uint t : SV_GroupIndex) { let work = match indirect { None => DeferredWork::Mesh { groups: 3 + k as u32, mesh_groups: 2 * (3 + k as u32) }, Some(block) => DeferredWork::Indirect { - rewrite: Rewrite { rs: 0xE0, pso: 0xE1, views: [(0, 0x4100_0000 + k * 0x100), (2, 0x4200_0000 + k * 16), (3, 0x7000 + k * 32), (4, 0x4100_0000 + k * 0x100)], groups: 1 }, + rewrite: Rewrite { rs: 0xE0, pso: 0xE1, views: [(0, 0x4100_0000 + k * 0x100), (2, 0x4200_0000 + k * 16), (3, 0x7000 + k * 32), (4, 0x4100_0000 + k * 0x100), (5, 0x4100_0000 + k * 0x100)], groups: 1 }, block, before: D3D12_RESOURCE_STATE_COMMON, companion: 0xD0, From 0bad17b7e07da6f3d8f12808e060953c9e1e6fc1 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:16:46 +0100 Subject: [PATCH 115/175] Tests: deferred two-pass runs read their own records on the GPU The runs of XCL_TWO_PASS_BATCH=2 had their command order tested on the CPU only (batch_commands), and on NVIDIA GPUs in a retail title. This records batch_commands of ten draws on a direct list with XCL's argument rewrite and stand-ins for the two passes (a compute pass writing each group's record with its draw's number, a mesh shader copying the records it reads out): one recording's DispatchMesh and one-command ExecuteIndirect draws, some with no groups, in two runs whose regions start again at the start of the buffer, then a second recording's run in the same regions (the shared batch buffer, with the barrier before a recording's first run), both lists in one submit. Every mesh pass reads its own draw's records. Passes on the RX 9070 XT. --- crates/xcl/src/hle/d3d12x/bind.rs | 218 ++++++++++++++++++++++++++++++ 1 file changed, 218 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 6b952d9e27..e9907845da 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -7201,6 +7201,224 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) } } + /// Deferred runs (`batch_commands`) on the GPU with stand-ins for the two passes and XCL's + /// argument rewrite: the "compute pass" writes each group's record (from the start of its + /// region) with its draw's number, the "mesh pass" (a mesh shader) copies the records it reads + /// out by draw. One recording's draws (DispatchMesh and one-command ExecuteIndirect, some + /// with no groups) in two runs whose regions start again at the start of the buffer, then + /// another recording's run in the same regions of the same buffer (the shared batch buffer: + /// `batch_open` before its first run), both lists in one submit: every mesh pass reads its + /// own draw's records. + #[test] + fn gpu_deferred_runs_read_their_own_records() { + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + #[repr(C, align(8))] + struct Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, + v: T, + } + #[repr(C)] + struct Stream { + rs: Sub<*mut c_void>, + ms: Sub, + mask: Sub, + rast: Sub, + depth: Sub, + rtv: Sub, + samples: Sub, + } + let src = r#" +#define RS "UAV(u0), UAV(u1), UAV(u2), UAV(u3), UAV(u4), UAV(u5)" +RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer rec : register(u1); +RWByteAddressBuffer o : register(u2); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void cs(uint3 g : SV_GroupID) { rec.Store(g.x * 4u, io.Load(0)); } +struct V { float4 p : SV_Position; }; +[RootSignature(RS)] +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void ms(uint3 g : SV_GroupID, out vertices V v[3], out indices uint3 t[1]) { + SetMeshOutputCounts(0, 0); + // (never: io dword 1 is 0; the validator wants the outputs written) + if (io.Load(4) != 0u) { v[0].p = float4(0.0f, 0.0f, 0.0f, 1.0f); t[0] = uint3(0u, 0u, 0u); } + o.Store((io.Load(0) * 16u + g.x) * 4u, rec.Load(g.x * 4u)); +} +"#; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + skip_test("no GPU"); + return; + } + if !crate::gpu::recomp::runner::mesh_shaders_supported().unwrap_or(false) { + skip_test("no mesh shaders"); + return; + } + let dev = dev.unwrap(); + // (recording, run, draw number, groups, ExecuteIndirect) + let draws: [(usize, usize, u32, u32, bool); 10] = + [(0, 0, 1, 3, false), (0, 0, 2, 0, true), (0, 0, 3, 4, true), (0, 1, 4, 1, false), (0, 1, 5, 2, true), (0, 1, 6, 4, true), (1, 0, 7, 2, true), (1, 0, 8, 4, false), (1, 0, 9, 0, true), (1, 0, 10, 3, true)]; + unsafe { + let cs = crate::gpu::recomp::dxc::compile(src, "cs", "cs_6_6", &[]).unwrap(); + let msb = crate::gpu::recomp::dxc::compile(src, "ms", "ms_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &cs).unwrap(); + let cpso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }, + ..Default::default() + }) + .unwrap(); + let mut stream = Stream { + rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, v: rs.as_raw() }, + ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, v: D3D12_SHADER_BYTECODE { pShaderBytecode: msb.as_ptr() as _, BytecodeLength: msb.len() } }, + mask: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, v: u32::MAX }, + rast: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, v: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() } }, + depth: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, v: D3D12_DEPTH_STENCIL_DESC::default() }, + rtv: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, v: D3D12_RT_FORMAT_ARRAY::default() }, + samples: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, v: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 } }, + }; + let dev2: ID3D12Device2 = dev.cast().unwrap(); + let mpso: ID3D12PipelineState = dev2 + .CreatePipelineState(&D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: std::mem::size_of::(), pPipelineStateSubobjectStream: &mut stream as *mut Stream as *mut c_void }) + .unwrap(); + let sig_of = |ty: D3D12_INDIRECT_ARGUMENT_TYPE| -> ID3D12CommandSignature { + let a = [D3D12_INDIRECT_ARGUMENT_DESC { Type: ty, ..Default::default() }]; + let mut s: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: a.as_ptr(), NodeMask: 0 }, None, &mut s).unwrap(); + s.unwrap() + }; + let (dsig, msig) = (sig_of(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH), sig_of(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH)); + let (rw_rs, rw_pso) = scale_indirect_pipeline(&dev).unwrap(); + let buffer = |bytes: u64, cpu: bool| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = if cpu { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + // one block of 256 B a draw: [the commands at 32-byte steps (the title's), io, rewrite constants] + let (mem, records, out) = (buffer(3 * 256 * 16, true), buffer(256 * 4, false), buffer(256 * 16 * 4, true)); + let scratch = [buffer(256 * 16, false), buffer(256 * 16, false)]; + let map = |b: &ID3D12Resource| -> *mut u32 { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + p as *mut u32 + }; + let (m, o) = (map(&mem), map(&out)); + std::ptr::write_bytes(o, 0, 256 * 16); + let mem_va = mem.GetGPUVirtualAddress(); + let (args_at, io_at, consts_at) = (0u64, 256 * 16, 2 * 256 * 16); + let mut steps: [Vec>; 2] = [vec![Vec::new(), Vec::new()], vec![Vec::new()]]; + let mut slot = [0u64; 2]; + for &(list, run, d, groups, indirect) in &draws { + let k = d as u64; + std::ptr::copy_nonoverlapping([groups, 1, 1].as_ptr(), m.add((args_at / 4 + 8 * k) as usize), 3); + *m.add(((io_at + 256 * k) / 4) as usize) = d; + // its region: from the start of the buffer in each run (`batch_region` after a flush) + let at = steps[list][run].len() as u64; + let region = records.GetGPUVirtualAddress() + 256 * at; + let io = mem_va + io_at + 256 * k; + let views = [io, region, out.GetGPUVirtualAddress(), io, io, io]; + let work = if indirect { + let (base, off) = align_root_uav(mem_va + args_at + 32 * k).unwrap(); + let c = [1u32, 12, 0, 1, 4, off, 0, 0, 0, 0]; + std::ptr::copy_nonoverlapping(c.as_ptr(), m.add(((consts_at + 256 * k) / 4) as usize), c.len()); + let dst = slot[list] * 256; + slot[list] += 1; + let rewrite = Rewrite { rs: rw_rs.as_raw() as usize, pso: rw_pso.as_raw() as usize, views: scale_views(mem_va + consts_at + 256 * k, base, scratch[list].GetGPUVirtualAddress() + dst, None, None), groups: 1 }; + // (a later run of the recording finds its block in INDIRECT_ARGUMENT) + let before = if run == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; + DeferredWork::Indirect { rewrite, block: scratch[list].as_raw() as usize, before, companion: dsig.as_raw() as usize, sig: msig.as_raw() as usize, compute_at: dst, mesh_at: dst + 12 } + } else { + DeferredWork::Mesh { groups, mesh_groups: groups } + }; + let stage = |pso: &ID3D12PipelineState| StageBind { rs: rs.as_raw() as usize, pso: pso.as_raw() as usize, views }; + steps[list][run].push(Step::Draw(DrawSnap { compute: stage(&cpso), mesh: stage(&mpso), work })); + } + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut lists = Vec::new(); + for (list, runs) in steps.iter().enumerate() { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let l6: ID3D12GraphicsCommandList6 = l.cast().unwrap(); + for (run, run_steps) in runs.iter().enumerate() { + // the second recording's first run: the shared buffer's (`batch_open`) + let open = run > 0 || list > 0; + for c in batch_commands(run_steps, records.as_raw() as usize, open) { + let res = |raw: usize| { + let p = raw as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).cloned() + }; + match c { + Cmd::Barriers { all, uav, transitions } => { + let uav = uav.and_then(res); + let held: Vec<(ID3D12Resource, D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES)> = transitions.iter().filter_map(|&(r, a, b)| Some((res(r)?, a, b))).collect(); + let t: Vec<_> = held.iter().map(|(r, a, b)| (r, *a, *b)).collect(); + emit_barrier_set(&l, all, uav.as_ref(), &t); + } + Cmd::ComputeRs(r) => { + let p = r as *mut c_void; + l.SetComputeRootSignature(ID3D12RootSignature::from_raw_borrowed(&p)); + } + Cmd::GraphicsRs(r) => { + let p = r as *mut c_void; + l.SetGraphicsRootSignature(ID3D12RootSignature::from_raw_borrowed(&p)); + } + Cmd::Pso(p) => { + let p = p as *mut c_void; + l.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&p)); + } + Cmd::ComputeView(s, va) => l.SetComputeRootUnorderedAccessView(s, va), + Cmd::GraphicsView(s, va) => l.SetGraphicsRootUnorderedAccessView(s, va), + Cmd::Dispatch(n) => l.Dispatch(n, 1, 1), + Cmd::DispatchMesh(n) => l6.DispatchMesh(n, 1, 1), + Cmd::Indirect(sig, b, at) => { + let (sp, bp) = (sig as *mut c_void, b as *mut c_void); + l.ExecuteIndirect(ID3D12CommandSignature::from_raw_borrowed(&sp).unwrap(), 1, ID3D12Resource::from_raw_borrowed(&bp).unwrap(), at, None::<&ID3D12Resource>, 0); + } + Cmd::Bind(_) | Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_) | Cmd::TimesBegin(_) | Cmd::TimesEnd => {} + } + } + } + emit_transition(&l, &scratch[list], D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + l.Close().unwrap(); + lists.push((alloc, l)); + } + let submit: Vec> = lists.iter().map(|(_, l)| Some(l.cast().unwrap())).collect(); + queue.ExecuteCommandLists(&submit); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + for &(_, _, d, groups, indirect) in &draws { + let got: Vec = (0..4).map(|g| *o.add((d * 16 + g) as usize)).collect(); + let want: Vec = (0..4).map(|g| if g < groups { d } else { 0 }).collect(); + assert_eq!(got, want, "the records the mesh pass of draw {d} read (ExecuteIndirect {indirect})"); + } + mem.Unmap(0, None); + out.Unmap(0, None); + } + } + /// With heap windows the two-pass programs read the memory windows from the shared heap /// (`pso::mem_windows`): both passes' binds set it on a list that has none, as `bind_abi` does. /// (Heap windows are opt-in: run with `XCL_HEAP_WINDOWS=1`, else skipped.) From 5ab4f6476705abb175ad735c5f6247341e51644f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:07:26 +0100 Subject: [PATCH 116/175] Shaders: --measure-pso --direct and --measure-dxil time the run's DXIL cold `xcl shaders --measure-pso` timed only the HLSL path, although direct DXIL is the default, and reported no memory. Now: - `--measure-pso HEX --direct` times the runtime's translation of the record (the direct translator with the environment's XCL_DIRECT_* / XCL_DXIL_NO_OPT switches; no translated caches), - `--measure-dxil` times a DXIL file or a translated-cache entry (its static samplers included): the exact bytes a run handed the driver, - every compile reports the most private commit and working set the process grew by meanwhile (a 2 ms sampler thread: amdxc64 may use threads of its own). ShaderCacheControl(DISABLE) does not keep the AMD driver from serving a compile from its own cache (25 ms for a program it built before), and --repeat's second run is a hit. AMD keys that cache by the application, so a cold measurement runs a copy of xcl.exe under a new name, e.g. xclm.exe. Measured so (RX 9070 XT, one compile per process): the compact form of a retail title's 223 KB scattering program took 43 s and +5.5 GB, its plain form 13.5 s and +0.85 GB. --- crates/xcl/src/gpu/recomp/pso.rs | 6 + crates/xcl/src/main.rs | 4 +- crates/xcl/src/shaders.rs | 214 ++++++++++++++++++++++++++++--- 3 files changed, 203 insertions(+), 21 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ab4c9fcfc3..34d3a5a6b4 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -657,6 +657,12 @@ fn enormous(stage: Stage, hlsl_len: usize) -> bool { stage == Stage::Compute && hlsl_len > dxc::UNOPTIMISED_ABOVE } +/// The DXIL a run would make of a console program now, without the in-memory or disk caches +/// (`xcl shaders --measure-pso --direct`): the routing and switches of the environment. +pub(crate) fn console_dxil_uncached(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result { + compile_console_shader(blob, stage, sampler_base, windows, split_wave64).map(|(c, _)| c) +} + // Changes here, in `fspx`, or in `console_translation` that alter the cached result must bump // `TRANSLATION_GLUE_REVISION` in build.rs; cache serialization changes need not bump it. /// The program's DXIL, and whether it is an `enormous` one the direct translator made (its diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 7726d0268a..abc06f83bc 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -40,7 +40,9 @@ Usage: --export-hlsl DIR [--count N] [--min-kb N] [--record-hash HEX]: writes deterministic compute HLSL for investigation; an exact hash bypasses the size threshold. --measure-pso HEX [--repeat N]: times cache-disabled driver compilation of one exact - compute record with XCL's real root signature and static samplers. + compute record with XCL's real root signature and static samplers, and the commit + the driver took; with --direct the runtime's translation (XCL_DIRECT_* switches). + --measure-dxil [--repeat N]: the same for a DXIL file or translated-cache entry. --direct [--sample N] [--seed S] [--validate] [--compare]: direct DXIL translator coverage over a seeded sample (default 200 programs, 0 = all); also --timeout, --max-bytes, --threads, --json, --hash H, --dump DIR. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 6ad60a53d9..00b3c71e22 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -811,6 +811,8 @@ struct ShadersOptions { count: usize, record_hash: Option, measure_pso: Option, + /// `--measure-dxil`: the input is one DXIL file or translated-cache entry to time + measure_dxil: bool, repeat: usize, precompile: bool, limit: usize, @@ -849,6 +851,7 @@ fn parse_args(args: &[String]) -> Result { count: 2, record_hash: None, measure_pso: None, + measure_dxil: false, repeat: 1, precompile: false, limit: usize::MAX, @@ -889,6 +892,7 @@ fn parse_args(args: &[String]) -> Result { "--count" => opts.count = p.parse_usize("--count")?, "--record-hash" => opts.record_hash = Some(p.parse_hex_u64("--record-hash")?), "--measure-pso" => opts.measure_pso = Some(p.parse_hex_u64("--measure-pso")?), + "--measure-dxil" => opts.measure_dxil = true, "--repeat" => opts.repeat = p.parse_usize("--repeat")?, "--precompile" => opts.precompile = true, "--limit" => opts.limit = p.parse_usize("--limit")?, @@ -975,6 +979,9 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if opts.graphics_records { return graphics_worker(path, runtime_windows()); } + if opts.measure_dxil { + return measure_dxil(path, opts.repeat.max(1)); + } let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -1029,6 +1036,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { opts.repeat.max(1), runtime_windows(), opts.split, + if opts.direct { PsoSource::Runtime } else { PsoSource::Hlsl }, ); } if opts.precompile { @@ -1182,8 +1190,8 @@ enum MeasureError { /// `CreateComputePipelineState`. The implicit D3D and driver caches must both be disabled; /// refusing to do that is an error rather than a misleading warm-cache measurement. /// This is the HLSL path the runtime uses by default (not `XCL_DIRECT_DXIL`). -fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option) -> i32 { - match measure_pso_result(input, hash, repeat, windows, split) { +fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option, source: PsoSource) -> i32 { + match measure_pso_result(input, hash, repeat, windows, split, source) { Ok(()) => 0, Err(MeasureError::Unavailable(e) | MeasureError::Failed(e)) => { eprintln!("xcl shaders --measure-pso: {e}"); @@ -1192,39 +1200,168 @@ fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Opt } } -fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option) -> Result<(), MeasureError> { +/// Where `--measure-pso` takes a console program's DXIL from. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum PsoSource { + /// the HLSL path through DXC + Hlsl, + /// `--direct`: the runtime's translation (`pso::console_dxil_uncached`: the direct DXIL + /// translator with the environment's `XCL_DIRECT_*` / `XCL_DXIL_NO_OPT` switches, or its HLSL + /// fallback), so a form can be timed before a run builds it + Runtime, +} + +/// A D3D12 device whose implicit driver and D3D caches are off for this process: every +/// `CreateComputePipelineState` is a cold compile. Refusing to turn them off is an error rather +/// than a misleading warm-cache measurement. +fn cacheless_pipelines() -> Result { use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; + use MeasureError::Unavailable; + let pipeline = Pipelines::new().map_err(|e| Unavailable(format!("no GPU device: {e}")))?; + let dev9 = pipeline.dev.cast::().map_err(|e| Unavailable(format!("ID3D12Device9 is required to disable the driver cache: {e}")))?; + let cache_kinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER; + unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) } + .map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?; + Ok(pipeline) +} + +fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option, source: PsoSource) -> Result<(), MeasureError> { use MeasureError::{Failed, Unavailable}; let (name, blob) = record_by_hash(input, hash).map_err(Failed)?; if !is_compute_container(&blob) { return Err(Failed(format!("{name} is not a console compute shader"))); } - recomp::dxc::location().map_err(|e| Unavailable(format!("DXC: {e}")))?; - let pipeline = Pipelines::new().map_err(|e| Unavailable(format!("no GPU device: {e}")))?; + if source == PsoSource::Hlsl { + recomp::dxc::location().map_err(|e| Unavailable(format!("DXC: {e}")))?; + } // before translating and compiling (tens of seconds for a big program): a machine that // cannot turn the caches off fails at once - let dev9 = pipeline.dev.cast::().map_err(|e| Unavailable(format!("ID3D12Device9 is required to disable the driver cache: {e}")))?; - let cache_kinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER; - unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) } - .map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?; + let pipeline = cacheless_pipelines()?; let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev)); - let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; - let dxc_start = std::time::Instant::now(); - let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; - let dxc_ms = dxc_start.elapsed().as_millis(); - let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, &translation.static_samplers).map_err(|e| Failed(format!("root signature: {e}")))?; + let made = std::time::Instant::now(); + let (dxil, samplers, how) = match source { + PsoSource::Hlsl => { + let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; + let dxc_start = std::time::Instant::now(); + let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; + (dxil, translation.static_samplers, format!("{} ms DXC", dxc_start.elapsed().as_millis())) + } + PsoSource::Runtime => { + let c = recomp::pso::console_dxil_uncached(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; + let pieces = c.dispatch_chain.as_ref().map_or(String::new(), |chain| format!(" (a chain of {} pieces: the first timed)", chain.pieces.len())); + let path = recomp::pso::compute_path(shader::fnv64(&blob)).unwrap_or("runtime"); + let dxil = c.dispatch_chain.as_ref().map_or(c.dxil.clone(), |chain| chain.pieces[0].clone()); + (dxil, c.samplers, format!("{} ms to translate, {path}{pieces}", made.elapsed().as_millis())) + } + }; + let label = format!("PSO {hash:016x}: {} bytes DXIL, {how}", dxil.len()); + time_compute_pso(&pipeline, &dxil, &samplers, repeat, &label, &name) +} + +/// `--measure-dxil`: one exact compute DXIL – a file the translator wrote (`XCL_DXIL_DUMP`), or +/// an entry of the translated cache (`\translated\v2\\_Compute_….bin`, +/// with its static samplers) – timed as `--measure-pso` times a record's. An entry is what a run +/// handed the driver, byte for byte, so its compile can be measured long after the run. +fn measure_dxil(path: &Path, repeat: usize) -> i32 { + let r = std::fs::read(path).map_err(|e| MeasureError::Failed(format!("{}: {e}", path.display()))).and_then(|bytes| { + let (dxil, samplers) = translated_entry(&bytes).map_err(MeasureError::Failed)?; + let pipeline = cacheless_pipelines()?; + let label = format!("PSO file: {} bytes DXIL, {} static sampler(s)", dxil.len(), samplers.len()); + time_compute_pso(&pipeline, &dxil, &samplers, repeat, &label, &path.display().to_string()) + }); + match r { + Ok(()) => 0, + Err(MeasureError::Unavailable(e) | MeasureError::Failed(e)) => { + eprintln!("xcl shaders --measure-dxil: {e}"); + 2 + } + } +} + +/// The DXIL and static samplers of a translated-cache entry (`XCLTRAN2`: the layout +/// `pso::translated::store_in` writes), or a bare DXIL container with none. +fn translated_entry(bytes: &[u8]) -> Result<(Vec, Vec), String> { + let Some(mut r) = bytes.strip_prefix(b"XCLTRAN2".as_slice()) else { + return if bytes.starts_with(b"DXBC") { Ok((bytes.to_vec(), Vec::new())) } else { Err("neither a DXIL container nor a translated-cache entry".into()) }; + }; + let short = || "a translated-cache entry cut short".to_string(); + let u32_ = |r: &mut &[u8]| -> Result { + let (v, rest) = r.split_first_chunk::<4>().ok_or_else(short)?; + *r = rest; + Ok(u32::from_le_bytes(*v)) + }; + // identity, length and second hash of the console bytes + r = r.get(24..).ok_or_else(short)?; + let n = u32_(&mut r)? as usize; + if n > r.len() / 17 { + return Err(short()); + } + let mut samplers = Vec::with_capacity(n); + for _ in 0..n { + let s = [u32_(&mut r)?, u32_(&mut r)?, u32_(&mut r)?, u32_(&mut r)?]; + let (&cmp, rest) = r.split_first().ok_or_else(short)?; + r = rest; + samplers.push((s, cmp != 0)); + } + let len = u32_(&mut r)? as usize; + let dxil = r.get(..len).filter(|d| d.starts_with(b"DXBC")).ok_or_else(short)?; + Ok((dxil.to_vec(), samplers)) +} + +/// The process's private commit and working set now, in bytes. +fn process_memory() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; + unsafe { + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); + (c.PrivateUsage as u64, c.WorkingSetSize as u64) + } +} + +/// `f`'s result and the most private commit and working set the process had while it ran +/// (sampled every 2 ms by another thread: the driver's compiler may use threads of its own). +fn with_peak_memory(f: impl FnOnce() -> R) -> (R, (u64, u64)) { + let stop = std::sync::atomic::AtomicBool::new(false); + std::thread::scope(|s| { + let sampler = s.spawn(|| { + let mut peak = process_memory(); + while !stop.load(Ordering::Relaxed) { + let now = process_memory(); + peak = (peak.0.max(now.0), peak.1.max(now.1)); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + peak + }); + let r = f(); + stop.store(true, Ordering::Relaxed); + let peak = sampler.join().unwrap_or((0, 0)); + let now = process_memory(); + (r, (peak.0.max(now.0), peak.1.max(now.1))) + }) +} + +/// `repeat` cold driver compiles of `dxil` with XCL's ABI root signature and `samplers`, each +/// with its time and the most commit and working set the process grew by meanwhile. +fn time_compute_pso(pipeline: &Pipelines, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], repeat: usize, label: &str, name: &str) -> Result<(), MeasureError> { + use windows::Win32::Graphics::Direct3D12::*; + use MeasureError::Failed; + let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, samplers).map_err(|e| Failed(format!("root signature: {e}")))?; let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; let mut times = Vec::with_capacity(repeat); + let mut most = (0u64, 0u64); let mut failure = None; + let mb = |b: u64| b >> 20; for run in 1..=repeat { + let before = process_memory(); let start = std::time::Instant::now(); - let result = unsafe { pipeline.dev.CreateComputePipelineState::(&desc) }; + let (result, peak) = with_peak_memory(|| unsafe { pipeline.dev.CreateComputePipelineState::(&desc) }); let elapsed = start.elapsed(); match result { Ok(pso) => drop(pso), @@ -1233,7 +1370,9 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl break; } } - println!("PSO run {run}/{repeat}: {:.3} s", elapsed.as_secs_f64()); + let grew = (peak.0.saturating_sub(before.0), peak.1.saturating_sub(before.1)); + most = (most.0.max(grew.0), most.1.max(grew.1)); + println!("PSO run {run}/{repeat}: {:.3} s, peak +{} MB commit, +{} MB working set (from {} MB / {} MB)", elapsed.as_secs_f64(), mb(grew.0), mb(grew.1), mb(before.0), mb(before.1)); times.push(elapsed.as_secs_f64()); } // the root signature's reference, on every path @@ -1244,11 +1383,12 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl times.sort_by(f64::total_cmp); let median = if times.len() & 1 == 0 { (times[times.len() / 2 - 1] + times[times.len() / 2]) / 2.0 } else { times[times.len() / 2] }; println!( - "PSO {hash:016x}: {} bytes DXIL, {dxc_ms} ms DXC, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, {name}", - dxil.len(), + "{label}, {repeat} cache-off run(s), median {:.3} s, min {:.3} s, max {:.3} s, peak +{} MB commit / +{} MB working set, {name}", median, times[0], - times[times.len() - 1] + times[times.len() - 1], + mb(most.0), + mb(most.1) ); Ok(()) } @@ -3120,7 +3260,7 @@ mod tests { let blob = compute_sample(); std::fs::write(&path.0, &blob).unwrap(); let hash = shader::fnv64(&blob); - match measure_pso_result(&Input::Files(vec![path.0.clone()]), hash, 1, 4, None) { + match measure_pso_result(&Input::Files(vec![path.0.clone()]), hash, 1, 4, None, PsoSource::Hlsl) { Ok(()) => {} // no DXC, a WARP-only or cacheless device, cache control without Developer Mode Err(MeasureError::Unavailable(e)) => recomp::runner::skip_test(&e), @@ -3128,6 +3268,40 @@ mod tests { } } + /// `--measure-dxil` reads a translated-cache entry (its static samplers and DXIL, as + /// `pso::translated::store_in` writes them) or a bare container, and refuses anything else. + #[test] + fn a_translated_cache_entry_gives_its_dxil_and_samplers() { + let dxil = b"DXBC and the rest of a container".to_vec(); + let mut entry = b"XCLTRAN2".to_vec(); + entry.extend([7u8; 24]); + entry.extend(1u32.to_le_bytes()); + for w in [1u32, 2, 3, 4] { + entry.extend(w.to_le_bytes()); + } + entry.push(1); + entry.extend((dxil.len() as u32).to_le_bytes()); + entry.extend(&dxil); + let (d, samplers) = translated_entry(&entry).unwrap(); + assert_eq!(d, dxil); + assert_eq!(samplers, vec![([1, 2, 3, 4], true)]); + assert_eq!(translated_entry(&dxil).unwrap(), (dxil.clone(), vec![])); + assert!(translated_entry(&entry[..entry.len() - 4]).is_err(), "cut short"); + assert!(translated_entry(b"not a shader").is_err()); + } + + /// The peak a compile is measured by sees memory the process took and gave back meanwhile. + #[test] + fn the_peak_memory_counts_what_was_given_back() { + let before = process_memory().0; + let ((), (peak_commit, _)) = with_peak_memory(|| { + let v = vec![1u8; 256 << 20]; + std::thread::sleep(std::time::Duration::from_millis(50)); + drop(std::hint::black_box(v)); + }); + assert!(peak_commit >= before + (128 << 20), "peak {} MB, before {} MB", peak_commit >> 20, before >> 20); + } + #[test] fn aggregates_console_shaders() { let mut a = Agg::default(); From e35c384031a28aa3b79d9cf2b14623881fdad5a6 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:08:37 +0100 Subject: [PATCH 117/175] Recompiler: XCL_DIRECT_FORMS_ONLY= keeps the newer forms to them The direct translator's newer forms (declared LDS, one-wave group ids, per-access coherence, the EXEC-select fold, XCL_DIRECT_COMPACT_MIN's compact form) were made for one program, the title's shadow-mask pass (cs d9fac2f1d8f646fd, record a3c0b8a98beee431: 95.6 -> 4.0 ms on the GPU). They change the DXIL of every compute program and, through the fold, of every vertex, pixel and mesh program, so the AMD driver's shader cache of all earlier runs missed for every pipeline. At the world's start ~65 compute programs of 140-260 KB of DXIL compiled cold, plus the graphics pipelines; the loading never ended. Measured cold (RX 9070 XT, amdxc64, a fresh application name so its cache is empty; one compile per process; s / peak commit added): record old build compact-min 4096 plain (min unset) 3cd8c0e62e7072c8 15.5 / 1.06 GB 43.1-54.0 / 5.5 GB 13.5 / 0.85 GB d3404ccf73c089f3 19.2 / 1.03 48.6 / 5.0 12.8 / 0.83 5549faf87b578c45 16.9 / 0.87 37.8 / 4.3 11.2 / 0.76 5ad0174e8d9e3a1e 14.5 / 0.86 36.9 / 4.3 14.7 / 0.75 03fdbf133bbf56a7 14.3 / 0.83 33.3 / 3.6 14.7 / 0.73 a3c0b8a98beee431 18.7 / 0.64 27.6 / 2.85 17.6 / 0.59 (XCL_DXIL_NO_OPT=select with compact-min 4096: 35-63 s, 4.5-6.4 GB.) With XCL_DIRECT_FORMS_ONLY set, only the listed console programs take the newer forms, each as its own switch says; every other program is translated as before they existed. Checked offline against an earlier run's translated cache: with XCL_DIRECT_FORMS_ONLY=a3c0b8a98beee431, 700 of its entries (265 compute, 338 pixel, 97 vertex) came out byte for byte the same, so the driver cache of earlier runs still holds them (xcl.exe compiled those in 22-32 ms). Unset: unchanged. The translated caches key the list. DXIL: unchanged unless the switch is set; with it, every program outside the list gets its earlier DXIL again. The gpu/dxil sources changed, so the translated cache's identity changes (translated again, once). --- crates/xcl/src/gpu/dxil/compact_tests.rs | 38 ++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 33 ++++++++++-- crates/xcl/src/gpu/dxil/lanes.rs | 2 +- crates/xcl/src/gpu/dxil/module/opt.rs | 4 +- crates/xcl/src/gpu/recomp/pso.rs | 64 +++++++++++++++++++++++- 5 files changed, 132 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 5b12a47c09..c5bd961e79 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -455,6 +455,44 @@ fn a_compute_program_from_the_compact_size_takes_the_compact_form() { assert_eq!(kernel(Some(500)), kernel(None), "a kernel keeps its form"); } +/// `kernel::with_newer_forms(false)` (a program `XCL_DIRECT_FORMS_ONLY` does not name): the +/// translation is the one every newer form's switch off gives, byte for byte – the compact form of +/// `XCL_DIRECT_COMPACT_MIN`, the declared LDS, one-wave group ids, the EXEC-select fold – so the +/// driver's shader cache of runs before those forms still holds it; with them it is another one. +#[test] +fn a_program_left_out_of_the_newer_forms_is_translated_as_before_them() { + if compact_mode().is_some() || std::env::var_os("XCL_DXIL_NO_OPT").is_some() { + return; + } + use super::kernel::{with_newer_forms, DECLARED_LDS_FOR_TEST, ONE_WAVE_GROUP_IDS_FOR_TEST}; + use crate::gpu::recomp::CsInterface; + // a one-wave 2-D group that declares one LDS granule, writes LDS and branches on EXEC + let cs = CsInterface { threads: [8, 4, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 2, lds_dwords: 128, ..Default::default() }; + let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let mut code = encode("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)], None).unwrap(); + code.extend(repeated(100)); + let translate = || super::kernel::translate_compute(&code, o, &cs).unwrap().dxil; + let set = |lds: Option, one_wave: Option, no_fold: bool| { + DECLARED_LDS_FOR_TEST.with(|c| c.set(lds)); + ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.set(one_wave)); + super::module::NO_SELECT_FOLD.with(|c| c.set(no_fold)); + }; + set(Some(false), Some(false), true); + let before = with_compact_min(None, translate); + set(Some(true), Some(true), false); + let newer = with_compact_min(Some(500), translate); + let left_out = with_newer_forms(false, || with_compact_min(Some(500), translate)); + set(None, None, false); + assert_ne!(newer, before, "the newer forms change this program"); + assert!(left_out == before, "left out of the newer forms: {} B, before them: {} B", left_out.len(), before.len()); + assert_eq!(with_newer_forms(true, || with_compact_min(Some(500), || { + set(Some(true), Some(true), false); + let d = translate(); + set(None, None, false); + d + })), newer, "with them: as their switches say"); +} + /// A compute program in the compact form `XCL_DIRECT_COMPACT_MIN` gives it runs as in the plain /// one: every thread of a 2-D wave32 group stores its own (group, y, x). #[test] diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index f3e9d3f184..15a1cd581d 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -40,6 +40,29 @@ pub struct KernelOptions { /// (the `gpu/dxil` sources are not in build.rs's translator source hash). pub const TRANSLATOR_VERSION: u32 = 12; +thread_local! { + /// The translations on this thread may take the newer forms (`with_newer_forms`). + static NEWER_FORMS: std::cell::Cell = const { std::cell::Cell::new(true) }; +} + +/// `f` with the translations it makes on this thread taking the newer forms (`on`) or none of +/// them: the declared LDS (`XCL_DECLARED_LDS`), one-wave group ids (`XCL_ONE_WAVE_GROUP_IDS`), +/// per-access coherence (`XCL_COHERENT_PER_ACCESS`), the EXEC-select fold and the compact form of +/// `XCL_DIRECT_COMPACT_MIN`. Each still follows its own switch when on; off, a program is +/// translated as before they existed – the same DXIL, which the driver's shader cache of earlier +/// runs still holds (`pso::newer_forms_for`, `XCL_DIRECT_FORMS_ONLY`). +pub fn with_newer_forms(on: bool, f: impl FnOnce() -> R) -> R { + let before = NEWER_FORMS.with(|c| c.replace(on)); + let r = f(); + NEWER_FORMS.with(|c| c.set(before)); + r +} + +/// Whether the translation on this thread may take the newer forms (`with_newer_forms`). +pub fn newer_forms() -> bool { + NEWER_FORMS.with(|c| c.get()) +} + /// `XCL_DECLARED_LDS` (default on; `=0` off): a compute program's groupshared block is the LDS /// its header declares (`CsInterface::lds_dwords`) plus the translator's own words after it, /// instead of the whole 8,192 dwords D3D12 allows (still so when the header gives no size). A @@ -340,10 +363,12 @@ fn translate_entry_with( let per_access = COHERENT_PER_ACCESS_FOR_TEST.with(|c| c.get()); #[cfg(test)] let one_wave = ONE_WAVE_GROUP_IDS_FOR_TEST.with(|c| c.get()); + let newer = newer_forms(); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) .spawn(move || { + NEWER_FORMS.with(|c| c.set(newer)); #[cfg(test)] DECLARED_LDS_FOR_TEST.with(|c| c.set(declared_lds)); #[cfg(test)] @@ -500,7 +525,7 @@ fn translate_on_this_thread_inner( _ if !compute && !kernel => None, Some(false) => None, Some(true) => super::compact::plan(&cfg, &lw), - None => match super::compact::compact_min() { + None => match super::compact::compact_min().filter(|_| newer_forms()) { Some(min) if compute => super::compact::sized_plan(&cfg, &lw, min).or_else(|| super::compact::automatic_plan(&cfg, &lw, split)), _ => super::compact::automatic_plan(&cfg, &lw, compute && split), }, @@ -760,7 +785,7 @@ impl Lw { } let coherent = cs.is_some() && crate::gpu::recomp::needs_coherent_mem(insts); let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, coherent); - let per_access = heap_mem == Some(true) && coherent_per_access() && !crate::gpu::recomp::invalidates_caches(insts); + let per_access = heap_mem == Some(true) && coherent_per_access() && newer_forms() && !crate::gpu::recomp::invalidates_caches(insts); let i32 = s.m.i32(); let z = s.m.i32c(0); let mut lw = Lw { @@ -912,9 +937,9 @@ impl Lw { // `XCL_DECLARED_LDS`: the program's own LDS, then the translator's words; a native 2-D // / 3-D group's arrival counter (`setup_lanes_compute`) is one of them let (declared, native_counter) = match entry { - Entry::Compute(cs) if declared_lds_enabled() => { + Entry::Compute(cs) if declared_lds_enabled() && newer_forms() => { let lanes = if o.wave64 { 64 } else { 32 }; - let one_wave = one_wave_group_ids() && cs.threads.iter().product::() <= lanes; + let one_wave = one_wave_group_ids() && newer_forms() && cs.threads.iter().product::() <= lanes; (cs.lds_dwords, !split && (cs.threads[1] > 1 || cs.threads[2] > 1) && !one_wave) } _ => (0, false), diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 576116a43f..a03aafa4b3 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -145,7 +145,7 @@ impl Lw { let t = self.s.m.i1c(true); let rank = self.s.wave_prefix_bit_count(t); self.add(base, rank) - } else if y * z > 1 && !(total <= lanes && super::kernel::one_wave_group_ids()) { + } else if y * z > 1 && !(total <= lanes && super::kernel::one_wave_group_ids() && super::kernel::newer_forms()) { let i32 = self.s.m.i32(); let (g, at) = match (self.lds, lds_top_word) { (Some(l), true) => self.xw.unwrap_or((l, 8191)), diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 47a194e08c..305399be8c 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -1260,9 +1260,9 @@ impl Module { } #[cfg(test)] - let skip_select = NO_SELECT_FOLD.with(|c| c.get()); + let skip_select = NO_SELECT_FOLD.with(|c| c.get()) || !crate::gpu::dxil::kernel::newer_forms(); #[cfg(not(test))] - let skip_select = false; + let skip_select = !crate::gpu::dxil::kernel::newer_forms(); if !skip("select") && !skip_select { self.fold_guarded_selects(&order, &repl); } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 34d3a5a6b4..5a200ca4b2 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -324,6 +324,11 @@ mod translated { let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; + // `XCL_DIRECT_FORMS_ONLY`: the newer forms for these programs only + let id = match super::forms_only_tag() { + Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag), + _ => id, + }; // `XCL_NAN_GUARD=0`: disabling PS float NaN/Inf sanitization changes pixel DXIL let id = if Backend::current() != Backend::Hlsl && !crate::gpu::dxil::kernel::nan_guard_enabled() { identity_for(&id.to_string(), "xcl-nan-guard-0") @@ -580,6 +585,10 @@ mod translated { let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; let id = if crate::gpu::dxil::kernel::coherent_per_access() { identity_for(&id.to_string(), "xcl-coherent-per-access") } else { id }; let id = if crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; + let id = match super::forms_only_tag() { + Some(tag) => identity_for(&id.to_string(), &tag), + None => id, + }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); if crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) @@ -668,6 +677,41 @@ pub(crate) fn console_dxil_uncached(blob: &[u8], stage: Stage, sampler_base: u32 /// The program's DXIL, and whether it is an `enormous` one the direct translator made (its /// disk cache entry then follows that translator's version: `translated::cached`). fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool), String> { + crate::gpu::dxil::kernel::with_newer_forms(newer_forms_for(blob), || compile_console_shader_formed(blob, stage, sampler_base, windows, split_wave64)) +} + +/// `XCL_DIRECT_FORMS_ONLY=[,…]` (hex `[SHADER]` hashes of console containers, or +/// `none`; unset: every program): only these programs take the direct translator's newer forms +/// (`kernel::with_newer_forms`: declared LDS, one-wave group ids, per-access coherence, the +/// EXEC-select fold, `XCL_DIRECT_COMPACT_MIN`'s compact form, each as its own switch says); every +/// other compute, vertex, pixel, mesh and geometry program is translated as before they existed. +/// Those forms changed the DXIL of every program, so the driver's shader cache of the earlier +/// runs missed for all of them: at a retail title's world start ~65 compute programs of 140 - 260 +/// KB of DXIL were compiled cold, 28 - 54 s and 2.9 - 6.4 GB each in the compact form (11 - 18 s +/// and 0.6 - 0.9 GB in the plain one; RX 9070 XT), thousands of graphics pipelines besides, and +/// its loading stood still. With the list, the program the forms were made for keeps them and +/// the others hit that cache. The caches key the list. +pub(crate) fn newer_forms_for(blob: &[u8]) -> bool { + forms_only().is_none_or(|set| set.contains(&crate::gpu::shader::fnv64(blob))) +} + +fn forms_only() -> Option<&'static std::collections::BTreeSet> { + static V: OnceLock>> = OnceLock::new(); + V.get_or_init(|| forms_only_of(std::env::var("XCL_DIRECT_FORMS_ONLY").ok().as_deref())).as_ref() +} + +/// The records of an `XCL_DIRECT_FORMS_ONLY` value (`none` or nothing valid: none of them). +fn forms_only_of(v: Option<&str>) -> Option> { + let v = v?; + Some(v.split(',').filter_map(|h| u64::from_str_radix(h.trim().trim_start_matches("0x"), 16).ok()).collect()) +} + +/// The translated caches' tag of `XCL_DIRECT_FORMS_ONLY` (None: unset). +fn forms_only_tag() -> Option { + forms_only().map(|set| format!("xcl-direct-forms-only-{}", set.iter().map(|h| format!("{h:016x}")).collect::>().join(","))) +} + +fn compile_console_shader_formed(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool), String> { // `XCL_DEBUG_CS_SUB` names this compute shader: the HLSL path, whatever its size let cs_subs = cs_subs(blob, stage); // `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path @@ -1360,7 +1404,7 @@ pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Resul let windows = mem_windows(); let dir = dxc::cache_dir(); console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, rodata, ms, wave64| { - compile_console_mesh(blob, code, rodata, ms, wave64, windows, split_wave64) + crate::gpu::dxil::kernel::with_newer_forms(newer_forms_for(blob), || compile_console_mesh(blob, code, rodata, ms, wave64, windows, split_wave64)) }) } @@ -1415,7 +1459,8 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator (HLSL fallback) if crate::gpu::dxil::kernel::enabled() { let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: split_wave64, mem_windows: mem_windows(), sampler_base: 0 }; - match crate::gpu::dxil::kernel::translate_geometry(&code, o, &g) { + let newer = newer_forms_for(vs) || newer_forms_for(gs); + match crate::gpu::dxil::kernel::with_newer_forms(newer, || crate::gpu::dxil::kernel::translate_geometry(&code, o, &g)) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("GS"); let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); @@ -1605,6 +1650,21 @@ mod slab_tests { } } +#[cfg(test)] +mod forms_only_tests { + use super::forms_only_of; + + /// `XCL_DIRECT_FORMS_ONLY`: hex records with or without `0x`, spaces allowed; `none` (or no + /// valid record) names none of them; unset leaves every program its forms. + #[test] + fn the_forms_only_list_names_records() { + assert_eq!(forms_only_of(None), None); + let set = forms_only_of(Some(" a3c0b8a98beee431, 0x3cd8c0e62e7072c8,zz")).unwrap(); + assert_eq!(set.into_iter().collect::>(), vec![0x3cd8c0e62e7072c8, 0xa3c0b8a98beee431]); + assert!(forms_only_of(Some("none")).unwrap().is_empty()); + } +} + #[cfg(test)] mod shader_cache_tests { use super::*; From 5c5ee83fce580df879cd38028bfc267cb5e18355 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:09:34 +0100 Subject: [PATCH 118/175] Recompiler: key XCL_DXIL_NO_OPT into the translated caches XCL_DXIL_NO_OPT= leaves direct-translator passes out (select: the EXEC-select fold), which changes the DXIL, but the translated caches did not key it: a run with it reused the translations made without it, and the other way round. Its passes (sorted, any order) are now part of both identities, beside XCL_DIRECT_FORMS_ONLY's list. DXIL: unchanged. Identity: changes only when XCL_DXIL_NO_OPT is set. --- crates/xcl/src/gpu/recomp/pso.rs | 35 +++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5a200ca4b2..ffc2e82c83 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -324,9 +324,10 @@ mod translated { let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; - // `XCL_DIRECT_FORMS_ONLY`: the newer forms for these programs only - let id = match super::forms_only_tag() { - Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag), + // `XCL_DIRECT_FORMS_ONLY`: the newer forms for these programs only; `XCL_DXIL_NO_OPT`: + // the passes left out + let id = match super::forms_only_tag().into_iter().chain(super::no_opt_tag()).collect::>() { + tags if Backend::current() != Backend::Hlsl && !tags.is_empty() => identity_for(&id.to_string(), &tags.join(";")), _ => id, }; // `XCL_NAN_GUARD=0`: disabling PS float NaN/Inf sanitization changes pixel DXIL @@ -585,9 +586,9 @@ mod translated { let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; let id = if crate::gpu::dxil::kernel::coherent_per_access() { identity_for(&id.to_string(), "xcl-coherent-per-access") } else { id }; let id = if crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; - let id = match super::forms_only_tag() { - Some(tag) => identity_for(&id.to_string(), &tag), - None => id, + let id = match super::forms_only_tag().into_iter().chain(super::no_opt_tag()).collect::>() { + tags if !tags.is_empty() => identity_for(&id.to_string(), &tags.join(";")), + _ => id, }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); if crate::gpu::recomp::lower_dxil::enabled() { @@ -711,6 +712,17 @@ fn forms_only_tag() -> Option { forms_only().map(|set| format!("xcl-direct-forms-only-{}", set.iter().map(|h| format!("{h:016x}")).collect::>().join(","))) } +/// The translated caches' tag of `XCL_DXIL_NO_OPT` (the direct translator's passes left out; +/// None: unset or empty): the DXIL is another one without them. +fn no_opt_tag() -> Option { + no_opt_tag_of(std::env::var("XCL_DXIL_NO_OPT").ok().as_deref()) +} + +fn no_opt_tag_of(v: Option<&str>) -> Option { + let passes: std::collections::BTreeSet<&str> = v?.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + (!passes.is_empty()).then(|| format!("xcl-dxil-no-opt-{}", passes.into_iter().collect::>().join(","))) +} + fn compile_console_shader_formed(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool), String> { // `XCL_DEBUG_CS_SUB` names this compute shader: the HLSL path, whatever its size let cs_subs = cs_subs(blob, stage); @@ -1652,7 +1664,7 @@ mod slab_tests { #[cfg(test)] mod forms_only_tests { - use super::forms_only_of; + use super::{forms_only_of, no_opt_tag_of}; /// `XCL_DIRECT_FORMS_ONLY`: hex records with or without `0x`, spaces allowed; `none` (or no /// valid record) names none of them; unset leaves every program its forms. @@ -1663,6 +1675,15 @@ mod forms_only_tests { assert_eq!(set.into_iter().collect::>(), vec![0x3cd8c0e62e7072c8, 0xa3c0b8a98beee431]); assert!(forms_only_of(Some("none")).unwrap().is_empty()); } + + /// `XCL_DXIL_NO_OPT` keys the translated caches by the passes it names, in any order. + #[test] + fn the_passes_left_out_are_a_cache_tag() { + assert_eq!(no_opt_tag_of(None), None); + assert_eq!(no_opt_tag_of(Some(" , ")), None); + assert_eq!(no_opt_tag_of(Some("select")).as_deref(), Some("xcl-dxil-no-opt-select")); + assert_eq!(no_opt_tag_of(Some("select, dce")), no_opt_tag_of(Some("dce,select"))); + } } #[cfg(test)] From 4dea333d1bd70237deea1cf27f9b7bba84438aa5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:10:30 +0100 Subject: [PATCH 119/175] D3D12.X: builds a title thread waits for go to urgent pipeline workers In a test run the title's loading thread waited XCL_CS_PSO_WAIT_MS (20 s) for one compute pipeline after another - 1b5466f2..., 8e5e632a..., 0a0e9b56..., c4d9c4a0..., eleven in all, programs of 3-60 KB of DXIL that no worker had even translated - and skipped their dispatches, while the four pipeline workers held 160-250 KB programs compiled one at a time (each 25-38 s cold, gated by XCL_HUGE_PSO_BYTES=65536): 0 presents, submits or draws from 64 s to the end at 300 s. A budgeted wait only enqueued the build at the tail of the workers' FIFO. A bind that waits for a pipeline no worker has taken now puts it into NEEDED (once), the list the workers already take before their queue for submits, and wakes an urgent worker: XCL_PSO_URGENT_WORKERS (default 2, at most 8, 0: off as before) threads that build only what NEEDED holds, so they are free when every regular worker is in a long driver compile or waiting for its turn at the huge-compile gate. A submit's needed pipelines wake them too. They are xcl-pso threads: a huge compile of theirs takes its turn at the gate as a wanted worker build. DXIL: unchanged. --- crates/xcl/src/hle/d3d12x/pso_async.rs | 97 ++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index bf42b142f4..0384af1ceb 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -58,6 +58,8 @@ struct Pending { kept: std::sync::atomic::AtomicBool, /// its shaders' names, for the line of a late one (`named`) name: Mutex>>, + /// a wait of one of the title's threads put it before the workers' queue (`urge`) + urged: std::sync::atomic::AtomicBool, } /// Whether one of the title's threads waits for the pipeline, and the preload worker building it. @@ -627,6 +629,66 @@ fn next_needed() -> Option> { NEEDED.lock().unwrap().pop_front() } +/// An urgent worker waits here for `NEEDED` (`spawn_urgent_workers`). +static URGENT_CV: Condvar = Condvar::new(); +/// builds the urgent workers ran +static URGENT_BUILT: AtomicUsize = AtomicUsize::new(0); + +/// `XCL_PSO_URGENT_WORKERS=` (default 2, at most 8; 0: none): workers that build nothing but +/// the pipelines one of the title's threads or a submit is waiting for (`NEEDED`: `urge`, +/// `need_by_submit`). The other workers take those before their queue too, but only between two +/// builds: on a cold driver cache every one of them may be in a driver compile of tens of seconds, +/// or waiting its turn for one (`real::big_compile_turn`). A retail title's loading thread then +/// waited 20 s (`XCL_CS_PSO_WAIT_MS`) for one small compute pipeline after another – programs of +/// 3 - 60 KB of DXIL that no worker had even translated – while the four workers held 160 - 250 KB +/// programs compiled one at a time: 0 frames for 220 s. +fn urgent_workers() -> usize { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| urgent_workers_of(std::env::var("XCL_PSO_URGENT_WORKERS").ok().as_deref())) +} + +fn urgent_workers_of(v: Option<&str>) -> usize { + v.and_then(|v| v.trim().parse::().ok()).unwrap_or(2).min(8) +} + +/// The urgent workers (`urgent_workers`), started at the first build waited for. +fn spawn_urgent_workers() { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + for k in 0..urgent_workers() { + // (an `xcl-pso` name: its huge driver compile takes its turn as a worker's, `real::driver_compile_identified`) + let _ = std::thread::Builder::new().name(format!("xcl-pso-urgent-{k}")).stack_size(64 << 20).spawn(|| loop { + let p = { + let mut q = NEEDED.lock().unwrap(); + loop { + if let Some(p) = q.pop_front() { + break p; + } + q = URGENT_CV.wait(q).unwrap(); + } + }; + if build_queued(&p) { + let n = URGENT_BUILT.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} pipelines a title thread or a submit waited for built by the urgent workers (XCL_PSO_URGENT_WORKERS)"); + } + } + }); + } + }); +} + +/// `p` goes before the workers' queue (`NEEDED`), once: one of the title's threads waits for it +/// now and no worker has taken it yet. An urgent worker takes it at once (`urgent_workers`). +fn urge(p: &Arc) { + if urgent_workers() == 0 || p.urged.swap(true, Ordering::AcqRel) || !p.untaken() { + return; + } + spawn_urgent_workers(); + NEEDED.lock().unwrap().push_back(p.clone()); + URGENT_CV.notify_one(); +} + /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. fn drop_unstarted_job(p: &Pending) { let job = p.job.lock().unwrap().take(); @@ -799,6 +861,7 @@ impl Pending { on_use: Default::default(), kept: Default::default(), name: Default::default(), + urged: Default::default(), } } @@ -1420,6 +1483,35 @@ mod used_tests { } } + /// A bind that waits for a pipeline no worker has taken puts it before the queue, once, and an + /// urgent worker builds it: the regular workers may all be in long driver compiles. (Its job + /// never reaches them here: it is marked sent, as one the queue already holds.) + #[test] + fn a_waited_build_goes_to_an_urgent_worker() { + assert_eq!(urgent_workers_of(None), 2); + assert_eq!(urgent_workers_of(Some("0")), 0); + assert_eq!(urgent_workers_of(Some("99")), 8); + if urgent_workers() == 0 { + return; + } + let standin = 0x7E57_A601usize; + let (tx, rx) = mpsc::channel::(); + submit_lazy(standin, true, Box::new(move || { + let _ = tx.send(std::thread::current().name().unwrap_or_default().to_string()); + 0x7A61 + }), 0); + let p = entry(standin).unwrap(); + p.sent.store(true, Ordering::Release); + assert_eq!(resolve_within(&p, standin, std::time::Duration::from_secs(20)), 0x7A61, "built within the wait"); + let by = rx.recv_timeout(std::time::Duration::from_secs(1)).unwrap(); + assert!(by.starts_with("xcl-pso-urgent-"), "built by {by:?}"); + assert!(p.urged.load(Ordering::Acquire)); + // (built: urged again, it is not queued again) + urge(&p); + assert!(!NEEDED.lock().unwrap().iter().any(|q| Arc::ptr_eq(q, &p))); + let _ = released(standin); + } + /// A dispatch is put off to the submit only where it would wait now: not with a pipeline that /// writes only images (its dispatches are left out while it is built) nor with one a bind /// already waited for past its budget. A submit that says it will wait for a pipeline counts @@ -2716,6 +2808,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> // (the title's thread is held from here until the pipeline is built or the budget is over) let mut wait = Wait::new(p); p.want(); + urge(p); if wait.until_done(Some(budget)) { return built(p); } @@ -2895,7 +2988,11 @@ pub fn need_by_submit(pso: usize) { p.sent.store(true, Ordering::Release); if !std::mem::replace(&mut p.demand.lock().unwrap().by_submit, true) { NEEDED_MADE.fetch_add(1, Ordering::Relaxed); + if urgent_workers() > 0 { + spawn_urgent_workers(); + } NEEDED.lock().unwrap().push_back(p); + URGENT_CV.notify_one(); let _ = queue().lock().unwrap().send(Box::new(|| ())); } } From 927524e7692b827bae41f6552f32277b665fd783 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:11:29 +0100 Subject: [PATCH 120/175] D3D12.X: XCL_PSO_RAM_FLOOR_MB lets driver compiles start as RAM allows The huge-compile gate waits for commit headroom, which this PC has in plenty (77 GB of commit, 31.8 GB of RAM): in a test run four cold compiles of 200 KB compute programs (4-5.5 GB each in the compact form, measured offline) took the title from 15 to 25 GB within seconds, and memguard ended it at 3.6 GB of free RAM with 49 GB of commit still free. With one compile at a time the RAM held, but the loading crawled. XCL_PSO_RAM_FLOOR_MB= (unset or 0: off): a driver compile of 64 KB of DXIL or more on a pipeline worker starts only while the available RAM, less 8 KB a DXIL byte for each such compile still running (the plain form took 4-5 KB a byte, the compact form 20-29), leaves n MB - or when none runs, so one always goes on. The RAM wait comes after the huge-compile slot and shows in the driver compile line's gate time; a wait of over 1 s is logged. With it XCL_HUGE_PSO_CONCURRENCY can be raised: the concurrency then follows the free RAM. DXIL: unchanged. --- crates/xcl/src/hle/d3d12x/real.rs | 149 +++++++++++++++++++++++++++++- 1 file changed, 148 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 04a574e416..a48d3b4276 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5421,9 +5421,12 @@ fn pso_trace() -> bool { /// `[SHADER]` lines and `xcl shaders --measure-pso`) and whether a driver blob was supplied. /// Also returns the time spent in the driver alone (not waiting for a slot). fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration) { - let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let worker = std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let huge = gate && bytes >= huge_pso_bytes() && worker; let waited = std::time::Instant::now(); let _slot = huge.then(|| huge_compile_turn(bytes)); + // (after the slot: a compile holding one waits for RAM, not one that has none yet) + let _ram = (gate && worker).then(|| pso_ram_floor().and_then(|floor| RAM_GATE.turn(bytes, floor, available_ram))).flatten(); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; @@ -5568,6 +5571,103 @@ fn big_compile_headroom(dxil_len: usize) -> u64 { (3u64 << 30).max(dxil_len as u64 * 512) } +/// `XCL_PSO_RAM_FLOOR_MB=` (unset or 0: off): a driver compile of `RAM_GATED_BYTES` of DXIL or +/// more on a pipeline worker starts only while the RAM available, less what the gated compiles +/// still running are expected to take (`compile_ram_estimate`), leaves n MB - or when no other one +/// runs, so one always goes on. The commit headroom of `big_compile_turn` does not see this: on a +/// PC with 32 GB of RAM and 77 GB of commit, four cold compiles of a retail title's 200 KB compute +/// programs (4 - 5.5 GB each in the compact form) took the title from 15 to 25 GB within seconds +/// and the memory guard ended it at 3.6 GB of free RAM, with 49 GB of commit still free. The +/// concurrency then follows the free RAM, up to the slots' caps when there is plenty. +fn pso_ram_floor() -> Option { + static V: std::sync::OnceLock> = std::sync::OnceLock::new(); + *V.get_or_init(|| pso_ram_floor_of(std::env::var("XCL_PSO_RAM_FLOOR_MB").ok().as_deref())) +} + +fn pso_ram_floor_of(v: Option<&str>) -> Option { + v.and_then(|v| v.trim().parse::().ok()).filter(|&mb| mb > 0).map(|mb| mb << 20) +} + +/// DXIL from which a driver compile waits for RAM (`pso_ram_floor`): smaller ones take +/// milliseconds and tens of MB. +const RAM_GATED_BYTES: usize = 64 << 10; + +/// The RAM a cold driver compile of `bytes` of DXIL is expected to take at most: 8 KB a byte. +/// Measured on an RX 9070 XT (amdxc64, cold cache, 2026-11-29): the plain form of a retail +/// title's 140 - 256 KB compute programs took 0.6 - 1.1 GB (4 - 5 KB a byte), the compact form +/// (`XCL_DIRECT_COMPACT_MIN`) of the same programs 2.9 - 6.4 GB (20 - 29 KB a byte). +fn compile_ram_estimate(bytes: usize) -> u64 { + bytes as u64 * 8192 +} + +/// The physical memory available now (None: not known). +fn available_ram() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPhys) +} + +/// The driver compiles that waited for RAM and still run: how many, and the RAM they are expected +/// to take (`pso_ram_floor`). +struct RamGate { + running: Mutex<(usize, u64)>, + cv: std::sync::Condvar, +} + +static RAM_GATE: RamGate = RamGate { running: Mutex::new((0, 0)), cv: std::sync::Condvar::new() }; + +/// A compile's place among `RamGate::running` until it ends. +struct RamTurn(&'static RamGate, u64); + +impl Drop for RamTurn { + fn drop(&mut self) { + let mut r = self.0.running.lock().unwrap(); + r.0 -= 1; + r.1 = r.1.saturating_sub(self.1); + self.0.cv.notify_all(); + } +} + +impl RamGate { + /// Waits until a compile of `bytes` leaves `floor` of the RAM `available` says is free, less + /// the running ones' estimates, or until none runs (None: below `RAM_GATED_BYTES`). + fn turn(&'static self, bytes: usize, floor: u64, available: impl Fn() -> Option) -> Option { + if bytes < RAM_GATED_BYTES { + return None; + } + let need = compile_ram_estimate(bytes); + let mut r = self.running.lock().unwrap(); + let mut logged = false; + let started = std::time::Instant::now(); + loop { + let fits = available().is_none_or(|a| a.saturating_sub(r.1) >= floor.saturating_add(need)); + if r.0 == 0 || fits { + break; + } + if !logged && started.elapsed() >= std::time::Duration::from_secs(1) { + logged = true; + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a driver compile of {bytes} B DXIL waits for RAM (XCL_PSO_RAM_FLOOR_MB: {} MB to stay free; {} running, {} MB expected of them, {} MB available) ({} so far)", + floor >> 20, + r.0, + r.1 >> 20, + available().unwrap_or(0) >> 20, + n + 1 + ); + } + } + r = self.cv.wait_timeout(r, std::time::Duration::from_millis(250)).unwrap().0; + } + r.0 += 1; + r.1 += need; + Some(RamTurn(self, need)) + } +} + /// That much commit is free (true when that is not known). pub(super) fn big_compile_commit_free(need: u64) -> bool { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; @@ -5582,6 +5682,53 @@ mod big_compile_tests { use std::sync::atomic::AtomicBool; use std::time::{Duration, Instant}; + #[test] + fn the_ram_floor_is_in_mib_and_off_unless_positive() { + assert_eq!(pso_ram_floor_of(Some(" 6144 ")), Some(6144 << 20)); + assert_eq!(pso_ram_floor_of(Some("0")), None); + assert_eq!(pso_ram_floor_of(Some("lots")), None); + assert_eq!(pso_ram_floor_of(None), None); + } + + /// A gated compile starts when it leaves the floor free beside what the running ones are + /// expected to take, or when none runs; a small one is not gated. + #[test] + fn driver_compiles_start_as_the_free_ram_allows() { + static G: RamGate = RamGate { running: Mutex::new((0, 0)), cv: std::sync::Condvar::new() }; + let gb = 1u64 << 30; + // expected: 1 GB + let bytes = 128 << 10; + let available = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(2 * gb)); + let a = available.clone(); + let now = move || Some(a.load(Ordering::Relaxed)); + assert!(G.turn(1024, 8 * gb, now.clone()).is_none(), "a small compile is not gated"); + let first = G.turn(bytes, 8 * gb, now.clone()).expect("the first goes on whatever the RAM"); + let started = std::sync::Arc::new(AtomicBool::new(false)); + let (s, n) = (started.clone(), now.clone()); + let second = std::thread::spawn(move || { + let t = G.turn(bytes, 8 * gb, n); + s.store(true, Ordering::Release); + t + }); + std::thread::sleep(Duration::from_millis(400)); + assert!(!started.load(Ordering::Acquire), "2 GB available: the second waits"); + // the 8 GB floor + 1 GB for it + the 1 GB the first is expected to take + available.store(10 * gb, Ordering::Relaxed); + let t = Instant::now(); + while !started.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(started.load(Ordering::Acquire), "10 GB available: the second goes on"); + let second = second.join().unwrap(); + assert_eq!(*G.running.lock().unwrap(), (2, 2 * gb)); + drop(first); + drop(second); + assert_eq!(*G.running.lock().unwrap(), (0, 0)); + // when no other runs, one goes on with no RAM to spare + available.store(0, Ordering::Relaxed); + assert!(G.turn(bytes, 8 * gb, now).is_some()); + } + #[test] fn a_late_build_waits_for_half_the_headroom() { let bytes = huge_pso_bytes(); From 19f303d6993490ddc64bd6ffbb715fe5a8586100 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:24:21 +0100 Subject: [PATCH 121/175] Shaders: --measure-* also report the commit a compile leaves behind The peak a cold driver compile reaches is transient; what the driver keeps after the pipeline is released stays for the rest of a run. Each measured compile now also prints the commit left after it. --- crates/xcl/src/shaders.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 00b3c71e22..13f6f9429f 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1372,7 +1372,9 @@ fn time_compute_pso(pipeline: &Pipelines, dxil: &[u8], samplers: &[recomp::pso:: } let grew = (peak.0.saturating_sub(before.0), peak.1.saturating_sub(before.1)); most = (most.0.max(grew.0), most.1.max(grew.1)); - println!("PSO run {run}/{repeat}: {:.3} s, peak +{} MB commit, +{} MB working set (from {} MB / {} MB)", elapsed.as_secs_f64(), mb(grew.0), mb(grew.1), mb(before.0), mb(before.1)); + // (what the driver keeps once the pipeline is gone: a run's builds keep it as long) + let left = process_memory().0.saturating_sub(before.0); + println!("PSO run {run}/{repeat}: {:.3} s, peak +{} MB commit, +{} MB working set (from {} MB / {} MB), +{} MB commit left after", elapsed.as_secs_f64(), mb(grew.0), mb(grew.1), mb(before.0), mb(before.1), mb(left)); times.push(elapsed.as_secs_f64()); } // the root signature's reference, on every path From 36e16cf44d29c0958eaa399f65f205de6906ea05 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:18:03 +0100 Subject: [PATCH 122/175] Recompiler: default to the retail run's tested forms and compile limits The direct translator's newer forms (declared LDS, one-wave group ids, the EXEC-select fold, the compact form from XCL_DIRECT_COMPACT_MIN) were on for every program by default. They change the DXIL of every compute program, so the AMD driver's own shader cache missed for all of them: ~65 big compute programs compiled cold at 28-54 s and up to 6 GB each in the compact form, the loading stood still, and one such run lost the device. They were measured only with XCL_DIRECT_FORMS_ONLY naming the shadow-mask program and the cold compiles taken two at a time. Defaults now, as in that run (RX 9070 XT, 300 s, no device removal, open world 4.0 fps median against 3.0 before; the shadow-mask program 98.6 -> 18.6 ms a frame): - XCL_DIRECT_FORMS_ONLY unset: the shadow-mask program only; XCL_DIRECT_FORMS_ONLY=all gives every program the forms as before. - XCL_DIRECT_COMPACT_MIN unset: 4096 (only for the programs above); 0 turns it off. - XCL_HUGE_PSO_BYTES 65536 (was 262144), XCL_HUGE_PSO_CONCURRENCY 2 (was 1). The translated caches are keyed by both values, so the first run translates once more; the driver cache of the earlier runs still holds every program outside the list. --- README.md | 4 ++-- crates/xcl/src/gpu/dxil/compact.rs | 27 +++++++++++++++++++++++++-- crates/xcl/src/gpu/recomp/pso.rs | 28 +++++++++++++++++++++------- crates/xcl/src/hle/d3d12x/real.rs | 13 ++++++++----- 4 files changed, 56 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 3ac3142167..3469d04ec6 100644 --- a/README.md +++ b/README.md @@ -328,9 +328,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. scratch buffer of at most `XCL_SPLIT_SCRATCH_MB` (default 256); the chains of one recording share it, and `XCL_SPLIT_SCRATCH_TOTAL_MB` (default 384) bounds what all recordings not yet reset hold together (past it a dispatch runs in smaller slabs). -- Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 262144) built on the +- Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 65536) built on the background `xcl-pso*` workers take turns in the driver's compiler: `XCL_HUGE_PSO_CONCURRENCY` - at once (default 1, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so + at once (default 2, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so they cannot occupy the ordinary huge-pipeline slot; one of them can therefore run next to the ordinary ones, and each gated compile starts only with 3 GB of commit free. Smaller pipelines and those a game thread waits for never wait. `xcl.log` shows each huge one as a numbered diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 0a5a7faff6..422254828e 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -267,7 +267,8 @@ pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { repeated.then_some(p) } -/// `XCL_DIRECT_COMPACT_MIN=` (unset: off): a compute program of at least that +/// `XCL_DIRECT_COMPACT_MIN=` (unset: `DEFAULT_COMPACT_MIN`; 0: off; it applies only +/// to the programs `XCL_DIRECT_FORMS_ONLY` gives the newer forms): a compute program of at least that /// many reachable non-terminator instructions takes the compact form whenever it has one whose /// table fits (`sized_plan`), however little of it repeats. The automatic choice is about size; /// this one is about speed: on a big program the driver's register allocation of the plain @@ -280,7 +281,29 @@ pub fn compact_min() -> Option { return v; } static V: std::sync::OnceLock> = std::sync::OnceLock::new(); - *V.get_or_init(|| std::env::var("XCL_DIRECT_COMPACT_MIN").ok().and_then(|v| v.trim().parse::().ok()).filter(|&n| n > 0)) + *V.get_or_init(|| compact_min_of(std::env::var("XCL_DIRECT_COMPACT_MIN").ok().as_deref())) +} + +/// `XCL_DIRECT_COMPACT_MIN` unset: the measured retail run's value (the shadow-mask program, +/// ~6,000 instructions, compact: 95.6 → 4.0 ms offline with the declared LDS). +const DEFAULT_COMPACT_MIN: usize = 4096; + +/// The size of an `XCL_DIRECT_COMPACT_MIN` value: unset, `DEFAULT_COMPACT_MIN`; 0 or not a +/// number, off. +fn compact_min_of(v: Option<&str>) -> Option { + match v { + None => Some(DEFAULT_COMPACT_MIN), + Some(v) => v.trim().parse::().ok().filter(|&n| n > 0), + } +} + +#[cfg(test)] +#[test] +fn the_compact_min_is_on_by_default_and_0_turns_it_off() { + assert_eq!(compact_min_of(None), Some(DEFAULT_COMPACT_MIN)); + assert_eq!(compact_min_of(Some(" 8192 ")), Some(8192)); + assert_eq!(compact_min_of(Some("0")), None); + assert_eq!(compact_min_of(Some("big")), None); } #[cfg(test)] diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ffc2e82c83..ed9358ee61 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -681,8 +681,9 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: crate::gpu::dxil::kernel::with_newer_forms(newer_forms_for(blob), || compile_console_shader_formed(blob, stage, sampler_base, windows, split_wave64)) } -/// `XCL_DIRECT_FORMS_ONLY=[,…]` (hex `[SHADER]` hashes of console containers, or -/// `none`; unset: every program): only these programs take the direct translator's newer forms +/// `XCL_DIRECT_FORMS_ONLY=[,…]` (hex `[SHADER]` hashes of console containers, +/// `none`, or `all` for every program; unset: `DEFAULT_FORMS_ONLY`, the run measured with it): +/// only these programs take the direct translator's newer forms /// (`kernel::with_newer_forms`: declared LDS, one-wave group ids, per-access coherence, the /// EXEC-select fold, `XCL_DIRECT_COMPACT_MIN`'s compact form, each as its own switch says); every /// other compute, vertex, pixel, mesh and geometry program is translated as before they existed. @@ -701,13 +702,24 @@ fn forms_only() -> Option<&'static std::collections::BTreeSet> { V.get_or_init(|| forms_only_of(std::env::var("XCL_DIRECT_FORMS_ONLY").ok().as_deref())).as_ref() } -/// The records of an `XCL_DIRECT_FORMS_ONLY` value (`none` or nothing valid: none of them). +/// `XCL_DIRECT_FORMS_ONLY` unset: the retail title's shadow-mask program +/// (CS_GenerateShadowMasks_Checkerboard_NoHair), the one the forms were made for. A retail run +/// with this list (RX 9070 XT, 300 s, no device removal) took it from 98.6 to 18.6 ms a frame +/// and the open world from 3.0 to 4.0 fps; with the forms on every program (`all`) the cold +/// driver compiles stalled the loading and one run lost the device. +const DEFAULT_FORMS_ONLY: u64 = 0xa3c0b8a98beee431; + +/// The records of an `XCL_DIRECT_FORMS_ONLY` value: unset, `DEFAULT_FORMS_ONLY`; `all`, every +/// program (None); `none` or nothing valid, none of them. fn forms_only_of(v: Option<&str>) -> Option> { - let v = v?; + let Some(v) = v else { return Some([DEFAULT_FORMS_ONLY].into()) }; + if v.trim().eq_ignore_ascii_case("all") { + return None; + } Some(v.split(',').filter_map(|h| u64::from_str_radix(h.trim().trim_start_matches("0x"), 16).ok()).collect()) } -/// The translated caches' tag of `XCL_DIRECT_FORMS_ONLY` (None: unset). +/// The translated caches' tag of `XCL_DIRECT_FORMS_ONLY` (None: `all`). fn forms_only_tag() -> Option { forms_only().map(|set| format!("xcl-direct-forms-only-{}", set.iter().map(|h| format!("{h:016x}")).collect::>().join(","))) } @@ -1667,10 +1679,12 @@ mod forms_only_tests { use super::{forms_only_of, no_opt_tag_of}; /// `XCL_DIRECT_FORMS_ONLY`: hex records with or without `0x`, spaces allowed; `none` (or no - /// valid record) names none of them; unset leaves every program its forms. + /// valid record) names none of them; `all` leaves every program its forms; unset names the + /// shadow-mask program only. #[test] fn the_forms_only_list_names_records() { - assert_eq!(forms_only_of(None), None); + assert_eq!(forms_only_of(None).unwrap().into_iter().collect::>(), vec![super::DEFAULT_FORMS_ONLY]); + assert_eq!(forms_only_of(Some(" ALL ")), None); let set = forms_only_of(Some(" a3c0b8a98beee431, 0x3cd8c0e62e7072c8,zz")).unwrap(); assert_eq!(set.into_iter().collect::>(), vec![0x3cd8c0e62e7072c8, 0xa3c0b8a98beee431]); assert!(forms_only_of(Some("none")).unwrap().is_empty()); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a48d3b4276..9859adb05a 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5274,14 +5274,16 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// A compute pipeline with a console CS: `None` = not a console shader, `Some(Err)` = console /// shader the recompiler could not take, `Some(Ok(hr))` = translated pipeline created (or the /// driver's verdict on it). -/// DXIL size from which a pipeline's driver compile is "huge" (default 256 KB, `XCL_HUGE_PSO_BYTES`): +/// DXIL size from which a pipeline's driver compile is "huge" (default 64 KB, `XCL_HUGE_PSO_BYTES`; +/// 256 KB before: on an RX 9070 XT a retail title's cold 90 – 260 KB compute programs took 1 – 38 s +/// and up to 5.5 GB each, four at a time, and its run was ended for RAM): /// a compute one goes to the background, and any of them built on an `xcl-pso*` worker waits /// for one of the `XCL_HUGE_PSO_CONCURRENCY` slots. NVIDIA's compiler (nvgpucomp64) takes /// minutes and ~1 GB for a 1 – 2 MB program; ~20 of them at once (one per worker) were slower /// in total than 1 – 2 at a time. Small programs (ms each) never wait. pub(super) fn huge_pso_bytes() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); - *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_BYTES").ok().as_deref(), 256 << 10, 1, usize::MAX)) + *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_BYTES").ok().as_deref(), 64 << 10, 1, usize::MAX)) } /// `XCL_SKIP_CS_KB=`: the DXIL size in bytes from which a compute program gets no pipeline @@ -5306,13 +5308,14 @@ mod skip_cs_tests { } } -/// Huge driver compiles at once on the workers (default 1, `XCL_HUGE_PSO_CONCURRENCY`). +/// Huge driver compiles at once on the workers (default 2, `XCL_HUGE_PSO_CONCURRENCY`; 2 with the +/// 64 KB threshold is what the measured retail runs used: one at a time left its loading waiting). fn huge_pso_concurrency() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); - *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 1, 1, 64)) + *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 2, 1, 64)) } -/// Hard cap on concurrent huge (`>= 256 KB`) driver compiles even when wanted by a title bind +/// Hard cap on concurrent huge (`>= huge_pso_bytes()`) driver compiles even when wanted by a title bind /// (`XCL_HUGE_PSO_WANTED_CONCURRENCY`, default 2, always `>= huge_pso_concurrency()`). Prevents a /// burst of lazy compute binds from launching 10+ huge driver compiles simultaneously and spiking /// process commit into OOM, while still letting a wanted build overtake 1 background build. From 069c29fe656796c8ab357d4c4597af0459cae304 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Sun, 29 Nov 2026 20:32:02 +0100 Subject: [PATCH 123/175] D3D12.X: a held resource's batch is sealed without waiting for a busy queue late_release::Held::drain signals each queue's fence under HELD, and native_queue_signal waits for the queue's submit lease. drain_known runs from a resource's last Release, which D3D12's runtime can make inside a call of its own (a list's Reset, alloc_pool::reset_list) while holding a runtime lock; the thread with the lease can be waiting for that lock (sparse::readback_after_execute_with resetting its allocator inside queue_submit::with). On Windows the three threads then waited for each other (title thread on HELD, the Reset thread on the lease, the queue thread on the runtime lock); reported by raylitebull on #3444 for main's code merged into amd-dev. vkd3d-proton has no such runtime lock. Sealing now takes the lease only when it is free (queue_submit::try_with, native_queue_try_signal); a queue whose turn is another thread's leaves the batch open, and the next drain (the late-release thread, every TICK) closes it. --- crates/xcl/src/hle/d3d12x/late_release.rs | 18 +++++++-- crates/xcl/src/hle/d3d12x/queue_submit.rs | 48 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 11 ++++++ 3 files changed, 73 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18987b3647..22683eb4e0 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -77,14 +77,24 @@ impl Held { self.fences.insert(key, (f, 0)); } let (fence, value) = self.fences.get_mut(&key).unwrap(); - if super::real::native_queue_signal(q, &*fence, *value + 1).is_err() { - ok = false; - break; + // Not a wait for the queue's turn: this runs under `HELD`, and from a resource's last + // `Release`, which the runtime can make inside a call of its own (a list's `Reset`) + // while it holds a lock the thread with the turn may be waiting for (an allocator + // `Reset` in `sparse::readback_after_execute_with`): the three then waited for each + // other on Windows (vkd3d-proton has no such lock). A busy queue leaves the batch + // open; the next drain (the thread here, every `TICK`) closes it. + match super::real::native_queue_try_signal(q, &*fence, *value + 1) { + Some(Ok(())) => {} + Some(Err(_)) | None => { + ok = false; + break; + } } *value += 1; marks.push((fence.clone(), *value)); } - // (no fence or no signal: the device is gone – the batch stays open, and held) + // (no fence or no signal: the device is gone, or a queue's turn is another thread's – + // the batch stays open, and held) if ok { self.last_seal = Some(Instant::now()); let dead = std::mem::take(&mut self.open); diff --git a/crates/xcl/src/hle/d3d12x/queue_submit.rs b/crates/xcl/src/hle/d3d12x/queue_submit.rs index 060160a828..2fb34b8d61 100644 --- a/crates/xcl/src/hle/d3d12x/queue_submit.rs +++ b/crates/xcl/src/hle/d3d12x/queue_submit.rs @@ -46,6 +46,21 @@ impl Lease { } } +impl Lease { + /// `enter`, or None while another thread holds the lease (no wait). + fn try_enter(self: &Arc) -> Option { + let me = std::thread::current().id(); + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.owner.is_some_and(|owner| owner != me) { + return None; + } + state.owner = Some(me); + state.depth += 1; + drop(state); + Some(Guard(Arc::clone(self))) + } +} + struct Guard(Arc); impl Drop for Guard { @@ -90,6 +105,18 @@ pub(super) fn with(queue: usize, f: impl FnOnce() -> R) -> R { f() } +/// `with`, or None without running `f` while another thread holds the queue's turn. For callers +/// that may run inside a D3D12 call of the runtime's (a resource's last `Release` from a list's +/// `Reset`): the thread with the turn can be waiting for that call's lock in the runtime (an +/// allocator `Reset` while it submits), so waiting for the turn there would never end. +pub(super) fn try_with(queue: usize, f: impl FnOnce() -> R) -> Option { + if queue == 0 { + return Some(f()); + } + let _guard = lease(queue).try_enter()?; + Some(f()) +} + /// Forward Release and discard the raw-address lease after a final native release. Pointer /// identity prevents a newly created generation at the same address from being removed. pub(super) fn release(queue: usize, f: impl FnOnce() -> u32) -> u32 { @@ -107,6 +134,27 @@ pub(super) fn release(queue: usize, f: impl FnOnce() -> u32) -> u32 { #[cfg(test)] mod tests { use super::*; + + #[test] + fn try_with_does_not_wait_for_another_threads_turn() { + let queue = 0x7e57_0001usize; + created(queue); + let (held_tx, held_rx) = std::sync::mpsc::channel(); + let (done_tx, done_rx) = std::sync::mpsc::channel::<()>(); + let holder = std::thread::spawn(move || { + with(queue, || { + held_tx.send(()).unwrap(); + done_rx.recv().unwrap(); + }) + }); + held_rx.recv().unwrap(); + assert!(try_with(queue, || ()).is_none(), "another thread has the turn"); + done_tx.send(()).unwrap(); + holder.join().unwrap(); + assert_eq!(try_with(queue, || 7), Some(7)); + // re-entrant on the thread that has the turn + assert_eq!(with(queue, || try_with(queue, || 8)), Some(8)); + } use std::ffi::c_void; use std::sync::mpsc; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 05fa05e926..6b9b340d6e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1198,6 +1198,17 @@ pub(crate) unsafe fn native_queue_signal(queue: &ID3D12CommandQueue, fence: &ID3 }) } +/// `native_queue_signal`, or None while another thread has the queue's turn (`queue_submit::try_with`). +pub(crate) unsafe fn native_queue_try_signal(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: u64) -> Option> { + let raw = queue.as_raw(); + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT; + let f = native_queue_fn(raw, 14); + super::queue_submit::try_with(raw as usize, || { + let f: F = std::mem::transmute(f); + windows::core::HRESULT(f(raw, fence.as_raw(), value)).ok() + }) +} + /// Wait through the PC queue slot, bypassing the title's shifted queue layout. pub(crate) unsafe fn native_queue_wait(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: u64) -> windows::core::Result<()> { let raw = queue.as_raw(); From 9990331afc64fe8380599ecc68c19651c11ec4d6 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:16:48 +0100 Subject: [PATCH 124/175] D3D12.X: XCL_TRACE_INDEXED logs the state of textures draws pick by index The black heads of the retail title (three runs on the RX 9070 XT) could not be traced to a texture: its draws are bindless. A console shader that indexes the view heap itself (ResourceDescriptorHeap[k]) loads the T# in slot k of the bound view heap, so every G-buffer draw of capture_2040 has "views": [] and the capture names none of the head's textures. New module indexed.rs: the candidate indices of a draw (root constants, root CBVs, CBVs in its tables, as bind::uncover_indexed scanned them) are resolved through the slots of the view heap the list set (heap base + 32 k -> T# word 0 -> the shared heap's resource). - XCL_TRACE_INDEXED=1 (diagnostic, off): each texture a graphics draw picks by index is looked at once a frame, before the draw's own fixes: how title_textures keeps it (active / shadowed / displaced / not uploaded / GPU-written), which levels of its T# have no video memory pages (vram::levels_with_pages: they read as zeros), whether the PC view samples them, and whether the T# in the slot is the one XCL wrote for the view or one the title rewrote (a MIN_LOD / base level of its own, which a translated implicit-LOD sample does not apply). Suspect textures are logged once per state with frame, pipeline and render targets; a summary line every 2 s. - XCL_CAPTURE_FRAME: a draw's "views" also list the textures it picks by index. No change to translated shaders (DXIL) and none without the switches. Tested: cargo test -p xcl --lib indexed capture (11 passed). --- crates/xcl/src/hle/d3d12x/bind.rs | 67 ++-- crates/xcl/src/hle/d3d12x/capture.rs | 3 +- crates/xcl/src/hle/d3d12x/indexed.rs | 391 ++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 5 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 28 ++ 6 files changed, 454 insertions(+), 41 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/indexed.rs diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e9907845da..ac980a00cf 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -698,46 +698,14 @@ unsafe fn uncover_bound_tables(layout: Option<&Layout>, args: &[u8], u: &crate:: /// them. A source that is shadowed then (a newer placement lies over its memory) is not uploaded, /// and the bake takes nothing from it – once, for the run: a head stays black. /// So every word of the draw's root constants and constant buffers (root ones, and those in the -/// first 16 slots of its tables) that is the index of a shadowed texture makes that texture -/// active again, for the upload ahead of the list's submit. `XCL_BAKE_SOURCES=0` turns it off. -unsafe fn uncover_indexed(layout: Option<&Layout>, args: &[u8], u: &crate::gpu::uma::Uma) { +/// first 16 slots of its tables: `indexed::indices`) that is the index of a shadowed texture +/// makes that texture active again, for the upload ahead of the list's submit. +/// `XCL_BAKE_SOURCES=0` turns it off. +unsafe fn uncover_indexed(indices: &[u32]) { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); if !*ON.get_or_init(|| std::env::var("XCL_BAKE_SOURCES").map_or(true, |v| v.trim() != "0")) { return; } - let Some(layout) = layout.filter(|_| super::title_textures::has_shadowed()) else { return }; - let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); - let mut indices: Vec = Vec::new(); - let mut push = |v: u32| { - if v != 0 && v < 4 << 20 && indices.len() < 4096 { - indices.push(v); - } - }; - for p in &layout.params { - match *p { - Param::Constants { at, count } => (0..count.min(64) as usize).for_each(|k| push(word(at as usize + 4 * k))), - Param::Descriptor { at } => { - let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; - super::ambient::scan_cbv_indices(va, 2048, &mut push); - } - Param::Table { at } => { - let offset = word(at as usize) as usize; - if offset == 0 { - continue; - } - let mut table = [0u8; 16 * 32]; - super::title_textures::copy_readable(u.base() + offset, &mut table); - for slot in table.chunks_exact(32) { - let w: [u32; 4] = std::array::from_fn(|k| u32::from_le_bytes(slot[4 * k..4 * k + 4].try_into().unwrap())); - if let Some((va, len)) = super::ambient::decode_cbv_vsharp(w) { - super::ambient::scan_cbv_indices(va, len, &mut push); - } - } - } - } - } - indices.sort_unstable(); - indices.dedup(); let resources: Vec = indices.iter().map(|&i| super::console_heap::named_by_index(i)).filter(|&r| r != 0 && r != super::console_heap::GONE).collect(); let shadowed = super::title_textures::shadowed_among(&resources); static DRAWS: AtomicU64 = AtomicU64::new(0); @@ -778,7 +746,16 @@ pub(super) unsafe fn capture_work(this: *mut c_void, kind: impl FnOnce() -> supe }); (root, s.heaps, s.pso) }); - let views = table_resources_of(this, gfx, super::capture::TABLE_SLOTS); + let mut views = table_resources_of(this, gfx, super::capture::TABLE_SLOTS); + // and the textures it picks by index through the view heap's slots (`indexed`) + let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) }); + if let (Some(l), Some(u)) = (layout.as_deref(), crate::gpu::uma::get()) { + for n in super::indexed::named(&super::indexed::indices(l, &args, u), heaps[0]) { + if !views.contains(&n.res) { + views.push(n.res); + } + } + } Some(super::capture::work(this, kind(), pso, gfx, root, heaps, views)) }) } @@ -4853,8 +4830,20 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let real = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?.clone(); uncover_bound_tables(layout.as_deref(), &args, u); - if gfx && super::pso_async::is_kept(pso) { - uncover_indexed(layout.as_deref(), &args, u); + if gfx { + let bake = super::pso_async::is_kept(pso); + let trace = super::indexed::trace_on(); + let uncover = bake && super::title_textures::has_shadowed(); + if let Some(l) = layout.as_deref().filter(|_| trace || uncover) { + let indices = super::indexed::indices(l, &args, u); + // (what the draw finds, before it is seen to) + if trace { + super::indexed::trace_draw(this, pso, &indices, heaps[0], bake); + } + if uncover { + uncover_indexed(&indices); + } + } } let b = Bound { rs, views, pso: pc, io: views[0] }; rebind(this, list, &b, gfx); diff --git a/crates/xcl/src/hle/d3d12x/capture.rs b/crates/xcl/src/hle/d3d12x/capture.rs index 5f4876e74b..1bfa0fd452 100644 --- a/crates/xcl/src/hle/d3d12x/capture.rs +++ b/crates/xcl/src/hle/d3d12x/capture.rs @@ -220,7 +220,8 @@ pub(super) struct Work { root: Vec, delta: bool, heaps: [u32; 2], - /// resources the first slots of its descriptor tables name + /// resources the first slots of its descriptor tables name, and the textures it picks by index + /// through the view heap's slots (`indexed`) views: Vec, outcome: Option, } diff --git a/crates/xcl/src/hle/d3d12x/indexed.rs b/crates/xcl/src/hle/d3d12x/indexed.rs new file mode 100644 index 0000000000..72c06cb7fe --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/indexed.rs @@ -0,0 +1,391 @@ +//! Textures a draw picks by index. A console shader that indexes the view heap itself +//! (`ResourceDescriptorHeap[k]`; root signatures with CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) loads +//! the T# in slot k of the view heap its list set (`bind::set_heaps`: the heap's 32-bit console +//! address) and samples the PC view that T#'s word 0 names in the shared heap +//! (`console_heap::named_by_index`). k itself is not an index of the shared heap: slot k of a +//! heap has SRV `2k` of the heap's own PC heap, or `first + 2 (k mod PAGE_SLOTS)` where the +//! slot's page has its place in the shared heap, so the descriptor at shared index k is another +//! slot's view, of another texture. Where k comes from is the title's (root constants, a constant +//! buffer); every word of those is a candidate (`indices`). +//! +//! `XCL_TRACE_INDEXED=1` (a diagnostic): each texture a graphics draw picks by index is looked at +//! once a frame, before the draw's own fixes: how XCL keeps it (`title_textures::kept`), which of +//! the levels its T# names have no video memory pages (`vram::levels_with_pages`: a level that +//! had no texels when it was last uploaded reads as zeros), and whether the T# in the slot is the +//! one XCL wrote for the view (`note_made`) or one the title changed (a MIN_LOD or base level of +//! its own, which a translated shader's sample does not apply: the PC view keeps the levels it +//! was made with). A texture that is shadowed, not uploaded yet, has levels without pages in its +//! view, or has a T# that is not XCL's is logged with the frame and the pipeline, once per state; +//! every 2 s a line counts them. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use windows::Win32::Graphics::Direct3D12::*; + +use super::console_list::{Layout, Param}; + +/// indices taken from one draw at most +const INDICES_MOST: usize = 4096; +/// lines of textures logged at most +const LINES_MOST: u64 = 3000; + +/// `XCL_TRACE_INDEXED` +pub(super) fn trace_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TRACE_INDEXED").is_ok_and(|v| v.trim() == "1")) +} + +/// The words a draw's arguments hold that may be indices: its root constants (64 a parameter), +/// its root CBVs and the CBVs in the first 16 slots of its tables (2 KiB each). +pub(super) unsafe fn indices(layout: &Layout, args: &[u8], u: &crate::gpu::uma::Uma) -> Vec { + let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap())); + let mut out: Vec = Vec::new(); + let mut push = |v: u32| { + if v != 0 && v < 4 << 20 && out.len() < INDICES_MOST { + out.push(v); + } + }; + for p in &layout.params { + match *p { + Param::Constants { at, count } => (0..count.min(64) as usize).for_each(|k| push(word(at as usize + 4 * k))), + Param::Descriptor { at } => { + let va = (word(at as usize) as u64 | (word(at as usize + 4) as u64) << 32) as usize; + super::ambient::scan_cbv_indices(va, 2048, &mut push); + } + Param::Table { at } => { + let offset = word(at as usize) as usize; + if offset == 0 { + continue; + } + let mut table = [0u8; 16 * 32]; + super::title_textures::copy_readable(u.base() + offset, &mut table); + for slot in table.chunks_exact(32) { + let w: [u32; 4] = std::array::from_fn(|k| u32::from_le_bytes(slot[4 * k..4 * k + 4].try_into().unwrap())); + if let Some((va, len)) = super::ambient::decode_cbv_vsharp(w) { + super::ambient::scan_cbv_indices(va, len, &mut push); + } + } + } + } + } + out.sort_unstable(); + out.dedup(); + out +} + +/// A texture index `k` names: the T# in slot k of the view heap, and the PC resource its word 0 +/// names in the shared heap. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Named { + pub k: u32, + pub words: [u32; 8], + pub res: usize, +} + +/// The textures `indices` name through the slots of the view heap at console address +/// `view_heap`: `words_at` reads the slot at a console address (None: not a slot), `named` the +/// resource of a shared-heap index (0: none). A slot that holds no image T# in XCL's form +/// (`desc::xcl_image_words`), or whose T# names nothing, names no texture. One entry a resource. +pub(super) fn resolve(indices: &[u32], view_heap: u32, words_at: impl Fn(u32) -> Option<[u32; 8]>, named: impl Fn(u32) -> usize) -> Vec { + let mut out: Vec = Vec::new(); + if view_heap == 0 { + return out; + } + for &k in indices { + let Some(at) = k.checked_mul(super::console_heap::SLOT).and_then(|o| view_heap.checked_add(o)) else { continue }; + let Some(words) = words_at(at) else { continue }; + if words[3] >> 28 < 8 || words[1] & 0xFF != 0 { + continue; + } + let res = named(words[0]); + if res == 0 || res == super::console_heap::GONE || out.iter().any(|n| n.res == res) { + continue; + } + out.push(Named { k, words, res }); + } + out +} + +/// The textures `indices` name (`resolve`), in the bound view heap `view_heap`. +pub(super) fn named(indices: &[u32], view_heap: u32) -> Vec { + resolve(indices, view_heap, super::console_heap::words_at, super::console_heap::named_by_index) +} + +// --------------------------------------------------------------------------------------- +// XCL_TRACE_INDEXED +// --------------------------------------------------------------------------------------- + +/// The T# XCL wrote for the SRV at shared-heap index i, and its view's ResourceMinLODClamp. +static MADE: Mutex>> = Mutex::new(None); + +/// XCL wrote `words` for the SRV at shared-heap index `index`, made with `desc` (`XCL_TRACE_INDEXED`). +pub(super) fn note_made(index: u32, words: &[u32; 8], desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) { + if !trace_on() { + return; + } + let clamp = desc.map_or(0.0, view_clamp); + MADE.lock().unwrap().get_or_insert_with(HashMap::new).insert(index, (*words, clamp)); +} + +/// A texture view's ResourceMinLODClamp. +fn view_clamp(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> f32 { + // SAFETY: the union member the view dimension names + unsafe { + let a = &v.Anonymous; + match v.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE1D => a.Texture1D.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE1DARRAY => a.Texture1DArray.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE2D => a.Texture2D.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => a.Texture2DArray.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURE3D => a.Texture3D.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURECUBE => a.TextureCube.ResourceMinLODClamp, + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => a.TextureCubeArray.ResourceMinLODClamp, + _ => 0.0, + } + } +} + +/// What the levels a view names have: those without pages, and of them the ones the PC view +/// samples and the ones the T# in the slot leaves out. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub(super) struct Holes { + /// levels of the T#'s range [base, last] without pages + pub none: Vec, + /// of them, those the PC view can sample (from its first level and its clamp on) + pub sampled: Vec, + /// of `sampled`, those the T# in the slot leaves out (its base level or its MIN_LOD): the + /// title keeps the shader off them, the PC view does not + pub left_out_by_tsharp: Vec, +} + +/// `pages`: whether each level has pages; `now`: (base level, last level, MIN_LOD) of the T# in +/// the slot; `view`: (first level, ResourceMinLODClamp) of the PC view. +pub(super) fn holes(pages: &[bool], now: (u32, u32, f32), view: (u32, f32)) -> Holes { + let (base, last, min_lod) = now; + let from_view = view.0.max(view.1.max(0.0).floor() as u32); + let from_tsharp = base.max(min_lod.max(0.0).floor() as u32); + let none: Vec = (base.min(view.0)..=last).filter(|&l| pages.get(l as usize).is_some_and(|&p| !p)).collect(); + let sampled: Vec = none.iter().copied().filter(|&l| l >= from_view).collect(); + let left_out_by_tsharp = sampled.iter().copied().filter(|&l| l < from_tsharp).collect(); + Holes { none, sampled, left_out_by_tsharp } +} + +#[derive(Default)] +struct Trace { + frame: u64, + /// resources looked at in this frame + seen: HashSet, + /// (view heap, index) → what it named in this frame + slots: HashMap<(u32, u32), Option>, + /// resource → the state last logged + logged: HashMap, + lines: u64, + window: Window, +} + +#[derive(Default)] +struct Window { + since: Option, + first_frame: u64, + draws: u64, + named: u64, + looked: u64, + shadowed: u64, + pending: u64, + holes: u64, + sampled: u64, + left_out: u64, + rewritten: u64, +} + +static TRACE: Mutex> = Mutex::new(None); + +/// `XCL_TRACE_INDEXED`: a graphics draw on `list` with pipeline `pso` (`bake`: a bake's) picks the +/// textures `indices` name in the view heap at `view_heap`. +pub(super) unsafe fn trace_draw(list: *mut std::ffi::c_void, pso: usize, indices: &[u32], view_heap: u32, bake: bool) { + let (p, b) = super::present::counters(); + let frame = p.max(b); + let mut g = TRACE.lock().unwrap(); + let t = g.get_or_insert_with(Trace::default); + if t.frame != frame { + t.frame = frame; + t.seen.clear(); + t.slots.clear(); + } + // (a slot is read once a frame: draws share their materials' indices) + let mut named: Vec = Vec::new(); + for &k in indices { + let n = *t.slots.entry((view_heap, k)).or_insert_with(|| self::named(&[k], view_heap).first().copied()); + if let Some(n) = n.filter(|n| !named.iter().any(|m| m.res == n.res)) { + named.push(n); + } + } + let w = &mut t.window; + if w.since.is_none() { + *w = Window { since: Some(Instant::now()), first_frame: frame, ..Window::default() }; + } + w.draws += 1; + w.named += named.len() as u64; + let made = MADE.lock().unwrap(); + // the draw's render targets (their resources where known), for a logged line + let mut targets: Option> = None; + for n in named { + if !t.seen.insert(n.res) { + continue; + } + let w = &mut t.window; + w.looked += 1; + let Some(img) = crate::gpu::desc::image(&n.words) else { continue }; + let kept = super::title_textures::kept(n.res); + let pages = super::vram::levels_with_pages(n.res); + let mine = made.as_ref().and_then(|m| m.get(&n.words[0])).copied(); + let rewritten = mine.is_some_and(|(m, _)| m[1..] != n.words[1..]); + let view = mine.and_then(|(m, c)| crate::gpu::desc::image(&m).map(|i| (i.base_level, c))).unwrap_or((img.base_level, 0.0)); + let h = pages.as_deref().map(|p| holes(p, (img.base_level, img.last_level, img.min_lod), view)).unwrap_or_default(); + let shadowed = kept.is_some_and(|k| !k.active); + let pending = kept.is_some_and(|k| k.pending); + w.shadowed += shadowed as u64; + w.pending += pending as u64; + w.holes += !h.none.is_empty() as u64; + w.sampled += !h.sampled.is_empty() as u64; + w.left_out += !h.left_out_by_tsharp.is_empty() as u64; + w.rewritten += rewritten as u64; + if !(shadowed || pending || !h.sampled.is_empty() || rewritten) { + t.logged.remove(&n.res); + continue; + } + let state = { + use std::hash::{Hash, Hasher}; + let mut s = std::collections::hash_map::DefaultHasher::new(); + (kept, &h, rewritten, n.words, pages.as_deref()).hash(&mut s); + s.finish() + }; + if t.logged.insert(n.res, state) == Some(state) || t.lines >= LINES_MOST { + continue; + } + t.lines += 1; + let how = kept.map_or("not a title texture".to_string(), |k| { + format!( + "title texture at {:#x}: {}{}{}{}{}{}", + k.va, + if k.active { "active" } else if k.displaced { "shadowed (displaced)" } else { "shadowed" }, + if k.pending { ", not uploaded yet" } else { "" }, + if k.gpu_written { ", GPU-written" } else { "" }, + if k.placed { ", placed on shared pages" } else { "" }, + if k.unmapped { ", tiles unmapped" } else { "" }, + if k.paged { ", read where the title's page mappings put its pages" } else { "" }, + ) + }); + let levels = pages.as_deref().map_or("all levels have pages".to_string(), |p| { + format!( + "levels with pages {}, without {:?}; of the view's: without {:?}, sampled by the PC view {:?}, left out by the T# {:?}", + p.iter().map(|&x| if x { '1' } else { '0' }).collect::(), + (0..p.len() as u32).filter(|&l| !p[l as usize]).collect::>(), + h.none, + h.sampled, + h.left_out_by_tsharp + ) + }); + let tsharp = match mine { + Some((m, c)) if rewritten => { + let mi = crate::gpu::desc::image(&m); + format!( + "T# not as XCL made it: made levels {:?} clamp {c}, now levels {}..{} MIN_LOD {} (words made {:08x?}, now {:08x?})", + mi.map(|i| (i.base_level, i.last_level)), + img.base_level, + img.last_level, + img.min_lod, + m, + n.words + ) + } + Some((_, c)) => format!("T# as XCL made it (view clamp {c})"), + None => format!("T# levels {}..{} MIN_LOD {} (made before the trace)", img.base_level, img.last_level, img.min_lod), + }; + let targets = targets.get_or_insert_with(|| super::list_x::bound_render_targets(list).into_iter().map(|h| super::present::rtv_resource(h).unwrap_or(h)).collect()); + crate::xlog_info!( + "D3D12.X: indexed texture {:#x} ({}x{}, format {}, {} levels) by slot {} in frame {frame}, pipeline {pso:#x}{}, targets {targets:#x?}: {how}; {levels}; {tsharp}", + n.res, + img.width, + img.height, + img.format, + img.max_mip + 1, + n.k, + if bake { " (a bake's)" } else { "" } + ); + } + drop(made); + let w = &mut t.window; + if w.since.is_some_and(|s| s.elapsed() >= Duration::from_secs(2)) { + crate::xlog_info!( + "D3D12.X: indexed textures (frames {}..{frame}): {} draws picked {} textures by index, {} looked at (once a frame each): {} shadowed (show what they held), {} not uploaded yet, {} with levels in their T# without pages, {} of them sampled by the PC view, {} of those left out by the T# (its base level / MIN_LOD); {} T#s not as XCL made them; {} lines so far", + w.first_frame, + w.draws, + w.named, + w.looked, + w.shadowed, + w.pending, + w.holes, + w.sampled, + w.left_out, + w.rewritten, + t.lines + ); + t.window = Window::default(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An image T# in XCL's form naming shared-heap SRV `index`. + fn tsharp(index: u32) -> [u32; 8] { + crate::gpu::desc::xcl_image_for_view(index, 1, crate::gpu::desc::ImageType::D2, 256, 256, 1, 9) + } + + /// `ResourceDescriptorHeap[k]` reads slot k of the bound view heap: the index names the + /// texture whose T# lies there, not the shared heap's descriptor k (another slot's: slot k + /// of a heap has SRV `2k` or a place on its page in the shared heap). + #[test] + fn an_index_names_the_texture_of_its_slot_in_the_view_heap() { + const HEAP: u32 = 0xb8a0_0000; + // slots 5 and 7 of the heap hold T#s naming shared SRVs 1010 and 1014 (page at 1000) + let slots: HashMap = [(HEAP + 5 * 32, tsharp(1010)), (HEAP + 7 * 32, tsharp(1014)), (HEAP + 9 * 32, [0x1234, 0, 0, 0, 0, 0, 0, 0])].into(); + let names: HashMap = [(1010, 0xA), (1014, 0xB), (5, 0xBAD5), (7, 0xBAD7), (9, 0xBAD9)].into(); + let words_at = |at: u32| slots.get(&at).copied(); + let named = |i: u32| names.get(&i).copied().unwrap_or(0); + let got: Vec = resolve(&[5, 7, 9, 11], HEAP, words_at, named).into_iter().map(|n| n.res).collect(); + // slot 9 holds a buffer V#, slot 11 nothing: no textures + assert_eq!(got, vec![0xA, 0xB]); + // the same texture twice is one; no heap bound: none + assert_eq!(resolve(&[5, 5], HEAP, words_at, named).len(), 1); + assert!(resolve(&[5], 0, words_at, named).is_empty()); + // an index whose slot would lie past 4 GiB names nothing + assert!(resolve(&[u32::MAX / 16], HEAP, words_at, named).is_empty()); + } + + /// The levels of a T# without pages: those the PC view samples, and of them those the T# in + /// the slot leaves out where the title changed its base level or MIN_LOD. + #[test] + fn levels_without_pages_are_told_against_the_view_and_the_tsharp() { + // levels 0 and 1 have no pages + let pages = [false, false, true, true, true]; + // T# and view as made: levels 0..4, both sampled + let h = holes(&pages, (0, 4, 0.0), (0, 0.0)); + assert_eq!((h.none.clone(), h.sampled.clone(), h.left_out_by_tsharp.clone()), (vec![0, 1], vec![0, 1], vec![])); + // the title's T# says MIN_LOD 2: the shader would not go below level 2, the PC view does + let h = holes(&pages, (0, 4, 2.0), (0, 0.0)); + assert_eq!((h.sampled.clone(), h.left_out_by_tsharp.clone()), (vec![0, 1], vec![0, 1])); + // its base level 1: only level 0 left out by it + let h = holes(&pages, (1, 4, 0.0), (0, 0.0)); + assert_eq!((h.none.clone(), h.sampled.clone(), h.left_out_by_tsharp.clone()), (vec![0, 1], vec![0, 1], vec![0])); + // a PC view clamped at 2 samples none of them + let h = holes(&pages, (0, 4, 0.0), (0, 2.0)); + assert_eq!((h.none, h.sampled), (vec![0, 1], vec![])); + // all levels with pages: nothing + assert_eq!(holes(&[true; 5], (0, 4, 0.0), (0, 0.0)), Holes::default()); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index dfcd3d9e34..f8b9cd9ff8 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -32,6 +32,7 @@ mod gpu_awake; mod gpu_profile; mod gpu_times; pub mod guard; +mod indexed; mod indirect_guard; mod late_release; pub mod layout; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9859adb05a..a6f5fa1f5d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3203,7 +3203,10 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, super::ambient::note_descriptor(slot.at, amb_idx, res as usize, amb_fmt, rdesc.Format.0, false); super::lut3d::viewed(res as usize, &rdesc, desc.as_ref(), slot.index, cpu); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { - Some(t) => super::console_heap::write(&slot, &t), + Some(t) => { + super::indexed::note_made(slot.index, &t, desc.as_ref()); + super::console_heap::write(&slot, &t) + } None => { if trace_preskin() { static M: AtomicU64 = AtomicU64::new(0); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 470f8b58b4..91d5199f84 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1199,6 +1199,34 @@ pub fn address(res: usize) -> Option { t.by_res.get(&res).or_else(|| t.shadowed.get(&res)).map(|e| e.va) } +/// How a title texture is kept now (`XCL_TRACE_INDEXED`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub(super) struct Kept { + pub va: usize, + /// the newest texture over its memory; else shadowed: not uploaded, it shows what it held + pub active: bool, + /// shadowed again by `uncover`, its source still linked for a few frames + pub displaced: bool, + /// its first upload is still to come + pub pending: bool, + pub gpu_written: bool, + pub placed: bool, + /// its tiles were unmapped when a placement over another range superseded it + pub unmapped: bool, + /// its pages are read where the title's page mappings put them + pub paged: bool, +} + +/// How texture `res` is kept (None: not a title texture). +pub(super) fn kept(res: usize) -> Option { + let t = TEXTURES.lock().unwrap(); + let (e, active) = match t.by_res.get(&res) { + Some(e) => (e, true), + None => (t.shadowed.get(&res)?, false), + }; + Some(Kept { va: e.va, active, displaced: t.displaced.contains_key(&res), pending: e.pending, gpu_written: e.gpu_written, placed: e.placed, unmapped: e.unmapped, paged: e.paged }) +} + /// (texture, subresource or ALL_SUBRESOURCES, state after) of a transition the title recorded type Transition = (usize, u32, D3D12_RESOURCE_STATES); From 8dfc4692c2e9e868bcaa6241895117f1cf889ecc Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:19:18 +0100 Subject: [PATCH 125/175] D3D12.X: a bake's indices name textures through the view heap's slots bind::uncover_indexed (8942a5b9, XCL_BAKE_SOURCES) makes the shadowed source textures of the title's head bakes active again before their upload. It took each candidate index k from the draw's constants as an index of the shared PC heap (console_heap::named_by_index(k)). A console shader's ResourceDescriptorHeap[k] reads slot k of the bound view heap instead, whose T# word 0 is the PC index: first + 2 (k mod PAGE_SLOTS) of the slot's page in the shared heap, or 2k. So the descriptor at shared index k is another slot's view: the fix made unrelated shadowed textures active again (each displacing the texture active over its memory) and left the bake's own shadowed sources stale. A run's log shows it at work: "a bake's draw (#26) picks 99 textures by index, 2 of them shadowed". - XCL_INDEX_BY_SLOT (on by default; 0: the shared-heap lookup as before): indices resolve through the view heap the list set (heap base + 32 k -> T# -> resource), indexed::resources. - XCL_UNCOVER_INDEXED=1 (off by default): every graphics draw's shadowed textures picked by index are made active again, as a bake's are. This title is bindless, so uncover_bound_tables never sees its G-buffer draws' textures; for a run once XCL_TRACE_INDEXED shows such draws sampling shadowed textures. The test resolves indices against a heap whose slot k holds the T# of shared index 1000 + 2k; it fails with the shared-heap lookup (it names the textures of shared indices 5, 7, 9). Not known yet whether shadowed bake sources are the cause of the black heads: XCL_TRACE_INDEXED is the check. No change to translated shaders (DXIL). Tested: cargo test -p xcl --lib indexed capture pso_async (51 passed). --- crates/xcl/src/hle/d3d12x/bind.rs | 38 +++++++++++++----------- crates/xcl/src/hle/d3d12x/indexed.rs | 43 ++++++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index ac980a00cf..a151dac09b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -693,29 +693,33 @@ unsafe fn uncover_bound_tables(layout: Option<&Layout>, args: &[u8], u: &crate:: } /// A draw whose result is drawn once and kept (`pso_async::is_kept`: the title's bake of its -/// characters' skin and decorations) picks its source textures by their index in the shared -/// heap, from its constants, and names none in a table: `uncover_bound_tables` does not see +/// characters' skin and decorations) picks its source textures by their index in the view heap +/// (`indexed`), from its constants, and names none in a table: `uncover_bound_tables` does not see /// them. A source that is shadowed then (a newer placement lies over its memory) is not uploaded, /// and the bake takes nothing from it – once, for the run: a head stays black. /// So every word of the draw's root constants and constant buffers (root ones, and those in the -/// first 16 slots of its tables: `indexed::indices`) that is the index of a shadowed texture -/// makes that texture active again, for the upload ahead of the list's submit. -/// `XCL_BAKE_SOURCES=0` turns it off. -unsafe fn uncover_indexed(indices: &[u32]) { +/// first 16 slots of its tables) that names a shadowed texture through the slots of the view heap +/// `view_heap` (`indexed::resources`) makes that texture active again, for the upload ahead of the +/// list's submit. `XCL_BAKE_SOURCES=0` turns it off; `XCL_UNCOVER_INDEXED=1` does it for every +/// graphics draw (`bake` false: not a bake's). +unsafe fn uncover_indexed(indices: &[u32], view_heap: u32, bake: bool) { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); if !*ON.get_or_init(|| std::env::var("XCL_BAKE_SOURCES").map_or(true, |v| v.trim() != "0")) { return; } - let resources: Vec = indices.iter().map(|&i| super::console_heap::named_by_index(i)).filter(|&r| r != 0 && r != super::console_heap::GONE).collect(); + let resources = super::indexed::resources(indices, view_heap); let shadowed = super::title_textures::shadowed_among(&resources); - static DRAWS: AtomicU64 = AtomicU64::new(0); - static FOUND: AtomicU64 = AtomicU64::new(0); - let (n, found) = (DRAWS.fetch_add(1, Ordering::Relaxed) + 1, FOUND.fetch_add(shadowed as u64, Ordering::Relaxed) + shadowed as u64); - if shadowed != 0 || n.is_power_of_two() { - crate::xlog_info!( - "D3D12.X: a bake's draw (#{n}) picks {} textures by index, {shadowed} of them shadowed: made active again for its upload ({found} so far)", - resources.len() - ); + if bake { + static DRAWS: AtomicU64 = AtomicU64::new(0); + static FOUND: AtomicU64 = AtomicU64::new(0); + let (n, found) = (DRAWS.fetch_add(1, Ordering::Relaxed) + 1, FOUND.fetch_add(shadowed as u64, Ordering::Relaxed) + shadowed as u64); + if shadowed != 0 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a bake's draw (#{n}) picks {} textures by index ({}), {shadowed} of them shadowed: made active again for its upload ({found} so far)", + resources.len(), + if super::indexed::by_slot() { "through the view heap's slots" } else { "as shared-heap indices, XCL_INDEX_BY_SLOT=0" } + ); + } } if shadowed != 0 { super::title_textures::uncover_drawn(&resources); @@ -4833,7 +4837,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi if gfx { let bake = super::pso_async::is_kept(pso); let trace = super::indexed::trace_on(); - let uncover = bake && super::title_textures::has_shadowed(); + let uncover = (bake || super::indexed::uncover_all()) && super::title_textures::has_shadowed(); if let Some(l) = layout.as_deref().filter(|_| trace || uncover) { let indices = super::indexed::indices(l, &args, u); // (what the draw finds, before it is seen to) @@ -4841,7 +4845,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi super::indexed::trace_draw(this, pso, &indices, heaps[0], bake); } if uncover { - uncover_indexed(&indices); + uncover_indexed(&indices, heaps[0], bake); } } } diff --git a/crates/xcl/src/hle/d3d12x/indexed.rs b/crates/xcl/src/hle/d3d12x/indexed.rs index 72c06cb7fe..b1d6484c2a 100644 --- a/crates/xcl/src/hle/d3d12x/indexed.rs +++ b/crates/xcl/src/hle/d3d12x/indexed.rs @@ -8,6 +8,14 @@ //! slot's view, of another texture. Where k comes from is the title's (root constants, a constant //! buffer); every word of those is a candidate (`indices`). //! +//! `XCL_INDEX_BY_SLOT` (on by default): the indices a bake's draw picks (`bind::uncover_indexed`) +//! name textures through the slots of the bound view heap. `0`: through the shared heap's +//! descriptor at that index, as before – which made other textures active again and left the +//! bake's own shadowed sources as they were. +//! +//! `XCL_UNCOVER_INDEXED=1` (off by default): every graphics draw's shadowed textures picked by +//! index are made active again, as a bake's are (`bind::uncover_indexed`). +//! //! `XCL_TRACE_INDEXED=1` (a diagnostic): each texture a graphics draw picks by index is looked at //! once a frame, before the draw's own fixes: how XCL keeps it (`title_textures::kept`), which of //! the levels its T# names have no video memory pages (`vram::levels_with_pages`: a level that @@ -31,6 +39,22 @@ const INDICES_MOST: usize = 4096; /// lines of textures logged at most const LINES_MOST: u64 = 3000; +fn switch(name: &str, default: bool) -> bool { + std::env::var(name).map_or(default, |v| v.trim() != "0") +} + +/// `XCL_INDEX_BY_SLOT` +pub(super) fn by_slot() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch("XCL_INDEX_BY_SLOT", true)) +} + +/// `XCL_UNCOVER_INDEXED` +pub(super) fn uncover_all() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch("XCL_UNCOVER_INDEXED", false)) +} + /// `XCL_TRACE_INDEXED` pub(super) fn trace_on() -> bool { static ON: OnceLock = OnceLock::new(); @@ -113,6 +137,20 @@ pub(super) fn named(indices: &[u32], view_heap: u32) -> Vec { resolve(indices, view_heap, super::console_heap::words_at, super::console_heap::named_by_index) } +/// The resources a bake's draw picks by index: through the view heap's slots (`by_slot`), or as +/// the shared heap's descriptors at those indices (before). +pub(super) fn resources(indices: &[u32], view_heap: u32) -> Vec { + pick(indices, view_heap, by_slot(), super::console_heap::words_at, super::console_heap::named_by_index) +} + +/// `resources` with the slots and names given (`resolve`). +fn pick(indices: &[u32], view_heap: u32, by_slot: bool, words_at: impl Fn(u32) -> Option<[u32; 8]>, named: impl Fn(u32) -> usize) -> Vec { + if by_slot { + return resolve(indices, view_heap, words_at, named).into_iter().map(|n| n.res).collect(); + } + indices.iter().map(|&i| named(i)).filter(|&r| r != 0 && r != super::console_heap::GONE).collect() +} + // --------------------------------------------------------------------------------------- // XCL_TRACE_INDEXED // --------------------------------------------------------------------------------------- @@ -357,9 +395,10 @@ mod tests { let names: HashMap = [(1010, 0xA), (1014, 0xB), (5, 0xBAD5), (7, 0xBAD7), (9, 0xBAD9)].into(); let words_at = |at: u32| slots.get(&at).copied(); let named = |i: u32| names.get(&i).copied().unwrap_or(0); - let got: Vec = resolve(&[5, 7, 9, 11], HEAP, words_at, named).into_iter().map(|n| n.res).collect(); // slot 9 holds a buffer V#, slot 11 nothing: no textures - assert_eq!(got, vec![0xA, 0xB]); + assert_eq!(pick(&[5, 7, 9, 11], HEAP, true, words_at, named), vec![0xA, 0xB]); + // (the shared heap's descriptors at those indices are other slots' textures) + assert_eq!(pick(&[5, 7, 9, 11], HEAP, false, words_at, named), vec![0xBAD5, 0xBAD7, 0xBAD9]); // the same texture twice is one; no heap bound: none assert_eq!(resolve(&[5, 5], HEAP, words_at, named).len(), 1); assert!(resolve(&[5], 0, words_at, named).is_empty()); From 3de7ab10af6d5bb2516c89d450585e9995fda379 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:16:12 +0100 Subject: [PATCH 126/175] Shaders: --measure-pso --direct times every piece of a split program A program the direct translator splits into a dispatch chain was timed by its first piece with XCL's ABI root signature, which a piece does not take: CreateComputePipelineState refused it with E_INVALIDARG after 2 s, so none of a retail title's ray-tracing resolve programs could be measured. Now each piece is built with the chain's root signature, then the whole form (what an indirect dispatch runs) with the ABI one, and the translation's sizes and commit are printed before the driver's compiles, which may not end. Measured with it (RX 9070 XT, cold driver cache, a world run's env without XCL_RT_LEAVE_OUT): cloth_default:CS_RaytracingResolve_ae7b7f3c (57 KB console code) translates in 0.4 s to a 564 KB whole form, 20 - 39 s and +1.45 GB commit in the driver, plus 10 pieces (725 KB) of 1 - 4 s and 11 - 147 MB each. CS_ScreenProbes_ActivateRays translates in 0.24 s to one 235 KB program (not split: one loop); its driver compile passed +5.6 GB in 22 s and, with XCL_DIRECT_COMPACT=0, +7.7 GB in 80 s without finishing. --- crates/xcl/src/main.rs | 3 ++- crates/xcl/src/shaders.rs | 28 ++++++++++++++++++++++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index abc06f83bc..4b7011b2fc 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -41,7 +41,8 @@ Usage: compute HLSL for investigation; an exact hash bypasses the size threshold. --measure-pso HEX [--repeat N]: times cache-disabled driver compilation of one exact compute record with XCL's real root signature and static samplers, and the commit - the driver took; with --direct the runtime's translation (XCL_DIRECT_* switches). + the driver took; with --direct the runtime's translation (XCL_DIRECT_* switches), + and of a split program every piece, then its whole form. --measure-dxil [--repeat N]: the same for a DXIL file or translated-cache entry. --direct [--sample N] [--seed S] [--validate] [--compare]: direct DXIL translator coverage over a seeded sample (default 200 programs, 0 = all); also diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 13f6f9429f..3e50885a55 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1250,10 +1250,25 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl } PsoSource::Runtime => { let c = recomp::pso::console_dxil_uncached(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; - let pieces = c.dispatch_chain.as_ref().map_or(String::new(), |chain| format!(" (a chain of {} pieces: the first timed)", chain.pieces.len())); let path = recomp::pso::compute_path(shader::fnv64(&blob)).unwrap_or("runtime"); - let dxil = c.dispatch_chain.as_ref().map_or(c.dxil.clone(), |chain| chain.pieces[0].clone()); - (dxil, c.samplers, format!("{} ms to translate, {path}{pieces}", made.elapsed().as_millis())) + let how = format!("{} ms to translate, {path}", made.elapsed().as_millis()); + // (before the driver's compiles, which may not end: what the translation made, and the + // commit it left) + let pieces = c.dispatch_chain.as_ref().map_or(String::new(), |chain| format!(", pieces {:?} bytes", chain.pieces.iter().map(Vec::len).collect::>())); + println!("PSO {hash:016x}: translated, {how}: whole {} bytes{pieces}; process commit {} MB", c.dxil.len(), process_memory().0 >> 20); + // a split program: each piece (what a direct dispatch runs) with the chain's root + // signature, then its whole form (what an indirect dispatch runs) with the ABI one + if let Some(chain) = &c.dispatch_chain { + let rs = recomp::pso::dispatch_chain_root_signature(&pipeline.dev, &c.samplers).map_err(|e| Failed(format!("chain root signature: {e}")))?; + for (i, piece) in chain.pieces.iter().enumerate() { + let label = format!("PSO {hash:016x}: piece {}/{} {} bytes DXIL, {how}", i + 1, chain.pieces.len(), piece.len()); + time_compute_pso_in(&pipeline, rs.clone(), piece, repeat, &label, &name)?; + } + let pieces: usize = chain.pieces.iter().map(Vec::len).sum(); + let label = format!("PSO {hash:016x}: whole form {} bytes DXIL, {how}, a chain of {} pieces ({pieces} bytes)", c.dxil.len(), chain.pieces.len()); + return time_compute_pso(&pipeline, &c.dxil, &c.samplers, repeat, &label, &name); + } + (c.dxil, c.samplers, how) } }; let label = format!("PSO {hash:016x}: {} bytes DXIL, {how}", dxil.len()); @@ -1346,9 +1361,14 @@ fn with_peak_memory(f: impl FnOnce() -> R) -> (R, (u64, u64)) { /// `repeat` cold driver compiles of `dxil` with XCL's ABI root signature and `samplers`, each /// with its time and the most commit and working set the process grew by meanwhile. fn time_compute_pso(pipeline: &Pipelines, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], repeat: usize, label: &str, name: &str) -> Result<(), MeasureError> { + let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, samplers).map_err(|e| MeasureError::Failed(format!("root signature: {e}")))?; + time_compute_pso_in(pipeline, rs, dxil, repeat, label, name) +} + +/// `time_compute_pso` with the root signature `rs` (a dispatch chain's piece has its own). +fn time_compute_pso_in(pipeline: &Pipelines, rs: windows::Win32::Graphics::Direct3D12::ID3D12RootSignature, dxil: &[u8], repeat: usize, label: &str, name: &str) -> Result<(), MeasureError> { use windows::Win32::Graphics::Direct3D12::*; use MeasureError::Failed; - let rs = recomp::pso::abi_root_signature_with(&pipeline.dev, true, samplers).map_err(|e| Failed(format!("root signature: {e}")))?; let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, From 3fc427317bb636c564c1d4e2b61fa129a47afbde Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:18:08 +0100 Subject: [PATCH 127/175] D3D12.X: XCL_RT_LEAVE_OUT_COUNT=1 counts the work of left-out programs Running a retail title without XCL_RT_LEAVE_OUT does not fit a 32 GB PC: its CS_ScreenProbes_ActivateRays program alone took over 7.7 GB in the driver's compiler without finishing, and its ~200 CS_RaytracingResolve programs bound in a world frame take 20 - 39 s and ~1.5 GB each (whole form) plus ten chain pieces of 1 - 4 s. The resolve programs are dispatched only indirectly, with counts the title's passes write for the rays that hit each material: while every ray misses (XCL_RT_GATE=miss) those counts should be zero, and leaving the programs out then loses nothing. Nothing showed whether they are. With the switch on, each skipped ExecuteIndirect of a left-out program gets indirect_guard's pass (which every other ExecuteIndirect already gets) so its counts are read on the GPU and back on the CPU; a skipped direct Dispatch has its groups counted on the CPU. Every 10 s one line says how many dispatches there were and how many had work (a warning when any had). Off by default. --- crates/xcl/src/hle/d3d12x/bind.rs | 2 + crates/xcl/src/hle/d3d12x/left_out.rs | 212 ++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 7 + 4 files changed, 222 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/left_out.rs diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index a151dac09b..15695d006f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3409,6 +3409,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if signature_dispatches(sig) && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { super::targets::note_dispatch(); count(DISPATCHES_SKIPPED); + super::left_out::indirect(this, raw_pso, pso, sig, max, args, args_off, count_buf); 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 dispatch with a pipeline that has no translated console shader ({raw_pso:#x}) skipped"); @@ -4462,6 +4463,7 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f crate::xlog_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped"); } count(DISPATCHES_SKIPPED); + super::left_out::direct(pso, launch.map(|(g, _)| g)); return; } let Some((groups, limits)) = launch else { diff --git a/crates/xcl/src/hle/d3d12x/left_out.rs b/crates/xcl/src/hle/d3d12x/left_out.rs new file mode 100644 index 0000000000..5507e86de7 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/left_out.rs @@ -0,0 +1,212 @@ +//! `XCL_RT_LEAVE_OUT_COUNT=1` (off by default; only with `XCL_RT_LEAVE_OUT`): the work the +//! compute programs `XCL_RT_LEAVE_OUT` leaves out would have done, counted and logged every 10 s. +//! +//! What it is for: a retail title's ray-tracing resolve programs (~1,000, ~200 bound in a world +//! frame) are dispatched only indirectly, with group counts its own passes wrote for the rays +//! that hit something of each material. While every ray misses (`XCL_RT_GATE=miss`) those counts +//! should be zero, and leaving the programs out then loses nothing – but their cold driver builds +//! (20 - 39 s and ~1.5 GB each, plus their dispatch chains' pieces) would take an hour of a run. +//! This shows whether the counts are zero: each indirect dispatch of a left-out program has its +//! counts read on the GPU by `indirect_guard`'s pass (which every other ExecuteIndirect already +//! gets), and the CPU reads them back from its ring once the GPU is past them. A direct dispatch +//! (the screen probes' ray activation: 920 groups a frame) has its groups counted on the CPU. + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +/// How long a read-back waits for the GPU before it is given up (a list never submitted). +const STALE: Duration = Duration::from_secs(5); +/// Read-backs waiting at most (the guard's ring has 2^18 slots). +const MOST_PENDING: usize = 1 << 16; +/// How often the line is logged. +const EVERY: Duration = Duration::from_secs(10); + +/// Whether the counting is on: `XCL_RT_LEAVE_OUT_COUNT=1` with `XCL_RT_LEAVE_OUT` set. +pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + let on = switch(std::env::var("XCL_RT_LEAVE_OUT_COUNT").ok().as_deref()) && crate::gpu::rt_leave_out::enabled(); + if on { + crate::xlog_info!("XCL_RT_LEAVE_OUT_COUNT: the work of the compute programs left out is counted (every 10 s)"); + } + on + }) +} + +fn switch(v: Option<&str>) -> bool { + v.is_some_and(|v| v.trim() == "1") +} + +/// The left-out pipelines (the dummy the title got) and their console programs' records. +static PSOS: Mutex>> = Mutex::new(None); + +/// `pso` is the dummy pipeline of the left-out console program `cs`. +pub(super) fn note(pso: usize, cs: &[u8]) { + if pso != 0 && on() { + PSOS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, crate::gpu::shader::fnv64(cs)); + } +} + +/// `pso` was released (another pipeline may be made at its address). +pub(super) fn forget(pso: usize) { + if let Some(m) = PSOS.lock().unwrap().as_mut() { + m.remove(&pso); + } +} + +fn record_of(pso: usize) -> Option { + PSOS.lock().unwrap().as_ref()?.get(&pso).copied() +} + +/// What was counted since the last line. +#[derive(Default, Debug, PartialEq)] +struct Window { + direct: u64, + direct_groups: u64, + indirect: u64, + /// indirect dispatches whose counts were read back, those with work, and their groups + read: u64, + with_work: u64, + groups: u64, + /// the most groups one indirect dispatch had, and its program's record + most: (u64, u64), + /// not read: not a plain dispatch signature, a count buffer, or the GPU never got to it + unread: u64, +} + +impl Window { + /// An indirect dispatch of `record`'s program whose counts read back as `c`. + fn counted(&mut self, record: u64, c: [u32; 3]) { + self.read += 1; + let groups = c.iter().map(|&n| n as u64).product::(); + if groups > 0 { + self.with_work += 1; + self.groups += groups; + if groups > self.most.0 { + self.most = (groups, record); + } + } + } +} + +struct State { + window: Window, + since: Instant, + /// slots of the guard's ring whose counts are not read back yet, oldest first + pending: VecDeque<(u32, u64, Instant)>, + /// with work so far (all windows) + with_work: u64, +} + +fn state() -> &'static Mutex { + static S: OnceLock> = OnceLock::new(); + S.get_or_init(|| Mutex::new(State { window: Window::default(), since: Instant::now(), pending: VecDeque::new(), with_work: 0 })) +} + +/// A direct dispatch of `pso`, skipped, of `groups` (None: not known). +pub(super) fn direct(pso: usize, groups: Option<[u32; 3]>) { + if !on() || record_of(pso).is_none() { + return; + } + let mut s = state().lock().unwrap(); + s.window.direct += 1; + s.window.direct_groups += groups.map_or(0, |g| g.iter().map(|&n| n as u64).product()); + report(&mut s); +} + +/// An ExecuteIndirect of `pso` (the title's pipeline, `raw` before it was resolved), skipped: +/// its counts are read by the guard's pass recorded on `list` now, and back later. +pub(super) unsafe fn indirect(list: *mut c_void, raw: usize, pso: usize, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize) { + if !on() { + return; + } + let Some(record) = record_of(raw).or_else(|| record_of(pso)) else { return }; + let checked = super::indirect_guard::check(list, pso, sig, max, args, args_off, count_buf); + if let Some(c) = &checked { + // (the guard's pass bound a root signature and a pipeline of its own, and left its buffer + // in UAV state: as after a pass that read the counts in place of the dispatch) + c.read(list); + super::list_x::restore_after_internal_pass(list, false, true); + } + let mut s = state().lock().unwrap(); + s.window.indirect += 1; + match checked { + Some(c) => { + if s.pending.len() >= MOST_PENDING { + s.pending.pop_front(); + s.window.unread += 1; + } + s.pending.push_back((c.slot, record, Instant::now())); + } + None => s.window.unread += 1, + } + report(&mut s); +} + +/// Reads back what the GPU has read, and logs the window every `EVERY`. +fn report(s: &mut State) { + while let Some(&(slot, record, at)) = s.pending.front() { + match super::indirect_guard::counts(slot) { + Some(c) => s.window.counted(record, c), + None if at.elapsed() > STALE => s.window.unread += 1, + None => break, + } + s.pending.pop_front(); + } + if s.since.elapsed() < EVERY { + return; + } + let w = std::mem::take(&mut s.window); + s.since = Instant::now(); + s.with_work += w.with_work; + let most = if w.most.0 > 0 { format!(", the most {} groups (record {:016x})", w.most.0, w.most.1) } else { String::new() }; + let line = format!( + "XCL_RT_LEAVE_OUT: in the last 10 s the programs left out were dispatched {} times directly ({} groups) and {} times indirectly: {} of those read back, {} with work ({} groups{most}), {} not read", + w.direct, w.direct_groups, w.indirect, w.read, w.with_work, w.groups, w.unread + ); + if w.with_work > 0 { + crate::xlog_warn!("{line} – what was left out would have run"); + } else { + crate::xlog_info!("{line} ({} with work so far)", s.with_work); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_switch_is_off_unless_one() { + assert!(switch(Some(" 1 "))); + assert!(!switch(Some("0"))); + assert!(!switch(Some("yes"))); + assert!(!switch(None)); + } + + /// Counts read back add up per window: zeros are dispatches without work, the product of the + /// three is the groups (in 64 bits: a float's bits read as counts are billions), the most is + /// kept with its program. + #[test] + fn read_back_counts_add_up() { + let mut w = Window::default(); + w.counted(0xA, [0, 4, 1]); + w.counted(0xB, [12, 1, 1]); + w.counted(0xC, [0x3F80_0000, 2, 1]); + w.counted(0xD, [5, 1, 0]); + assert_eq!(w.read, 4); + assert_eq!(w.with_work, 2); + assert_eq!(w.groups, 12 + 0x3F80_0000u64 * 2); + assert_eq!(w.most, (0x3F80_0000u64 * 2, 0xC)); + } + + /// A released pipeline's address is not taken for a left-out one's any more. + #[test] + fn a_forgotten_pipeline_is_not_counted() { + PSOS.lock().unwrap().get_or_insert_with(HashMap::new).insert(0x7E57_1E00, 0x1234); + assert_eq!(record_of(0x7E57_1E00), Some(0x1234)); + forget(0x7E57_1E00); + assert_eq!(record_of(0x7E57_1E00), None); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f8b9cd9ff8..6f3c921376 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -35,6 +35,7 @@ pub mod guard; mod indexed; mod indirect_guard; mod late_release; +mod left_out; pub mod layout; pub mod list_x; mod look_stats; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a6f5fa1f5d..2bbde820fc 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2607,6 +2607,7 @@ pub(super) fn forget_pso_for_test(pso: usize) { fn forget_pso(pso: usize) { super::dred::forget_pso(pso); dispatch_chain::forget(pso); + super::left_out::forget(pso); TRANSLATED_COMPUTE.remove(pso); if let Some(s) = CONSOLE_COMPUTE.lock().unwrap().as_mut() { s.remove(&pso); @@ -8249,6 +8250,12 @@ unsafe fn compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, copy.CS = bytecode(&dummy().cs); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let hr2 = finish_pso(this, f, © as *const _ as *const c_void, riid, ppv); + if left_out && hr2 >= 0 && !ppv.is_null() { + // (`XCL_RT_LEAVE_OUT_COUNT`: its dispatches' work is counted) + if let Some(cs) = shader_bytes(&(*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)).CS) { + super::left_out::note(*ppv as usize, cs); + } + } if !left_out || hr2 < 0 { note_fallback("compute PSO", hr, hr2 >= 0); } From 67af2f063d0c92c7d4547abed27075ab6e800bef Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:29:44 +0100 Subject: [PATCH 128/175] D3D12.X: reflections that found nothing take the light around them While every ray misses (XCL_RT_GATE=miss), the title's reflection miss program (CS_RayMiss_, opaque and transparent layers) writes the sky's light, 10 - 30 in the half-resolution miss image, for every reflection ray, also indoors and under cars. The resolve then adds that as specular on every glossy surface: skin looks wet or plastic, hair gets white sparkles and car paint glitters. After the miss program, each texel whose picture is not the sky gets the stand-in's light from the points around it along the reflected direction (from the depth's normal), the way VIctory-Neo's Role::Miss does, scaled by XCL_AMBIENT_SPECULAR (default 1, Neo's value; 0 leaves the image as the title wrote it). Before any frame's light is kept the image is left as well. XCL's own FXC shader only: no translated program's DXIL changes. --- THIRD_PARTY.md | 2 +- crates/xcl/src/hle/d3d12x/ambient.rs | 306 ++++++++++++++++++++++++++- 2 files changed, 298 insertions(+), 10 deletions(-) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 5f80288fae..d34af92c67 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -12,7 +12,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | | [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs` (the programs left out); `crates/xcl/src/hle/d3d12x/ambient.rs`: the cells and their slow mean, and the stand-in for the indirect light made in space – `LIGHT_PLACE_HLSL`, `LIGHT_GATHER_HLSL`, the depth path of `AMBIENT_FILL_R9G9B9E5_HLSL`, `AIR_CAP_HLSL` and the resolve's descriptor slots, after `place`, `gather`, `raise`, `clear_air`, `LIGHT` and `DEPTH` of its `ambient.rs` (commit 99a7f9b) | port of the HLSL into XCL's ambient pass (2026-11-28) | -| [VIctory-Neo](https://github.com/KyleS98/VIctory-Neo) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/mirror.rs`: the light around a mirror's view – the programs' parts by name, `XCL_MIRROR_AMBIENT` and the pass and its programs, after its `crates/victory-gpu/src/mirror.rs` (commits a3af274, 9b61dc9); `crates/xcl/src/hle/d3d12x/depth_uav.rs`: a depth plane brought up to date from its twin before the draws that test against it, after 7da5c9d; `crates/xcl/src/hle/d3d12x/ambient.rs`: the reflections' hold to the light around and their resolve slots (3aca295), the bound on transparent surfaces' light (`CS_SpatialFilterAlpha`, a6e85c6) and the probes' blue garbage test, after its `crates/victory-gpu/src/ambient.rs` at bdc3f38 | port adapted to XCL's passes and state (2026-11-29) | +| [VIctory-Neo](https://github.com/KyleS98/VIctory-Neo) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/mirror.rs`: the light around a mirror's view – the programs' parts by name, `XCL_MIRROR_AMBIENT` and the pass and its programs, after its `crates/victory-gpu/src/mirror.rs` (commits a3af274, 9b61dc9); `crates/xcl/src/hle/d3d12x/depth_uav.rs`: a depth plane brought up to date from its twin before the draws that test against it, after 7da5c9d; `crates/xcl/src/hle/d3d12x/ambient.rs`: the reflections' hold to the light around and their resolve slots (3aca295), the bound on transparent surfaces' light (`CS_SpatialFilterAlpha`, a6e85c6) and the probes' blue garbage test, after its `crates/victory-gpu/src/ambient.rs` at bdc3f38; the stand-in for reflections that found nothing (`MISS_LIGHT_HLSL`, `XCL_AMBIENT_SPECULAR`, the `CS_RayMiss` slots and layers), after its `Role::Miss`, `reflect_light` and `VICTORY_AMBIENT_SPECULAR` at bdc3f38 | port adapted to XCL's passes and state (2026-11-29) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 914f269114..3e510ca48f 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -13,7 +13,7 @@ //! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, //! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`, `XCL_AMBIENT_FRAME`, //! `XCL_AMBIENT_KEEP`, `XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`, `XCL_AMBIENT_SPACE`, `XCL_AMBIENT_SPLIT`, -//! `XCL_AMBIENT_REFLECT_HOLD`, `XCL_AMBIENT_ALPHA`. +//! `XCL_AMBIENT_REFLECT_HOLD`, `XCL_AMBIENT_ALPHA`, `XCL_AMBIENT_SPECULAR`. //! //! The sky alone leaves a night scene black wherever no lamp reaches. So the fill is also raised //! to an estimate taken from the frame itself: the light the visible surfaces send out, which the @@ -53,6 +53,18 @@ //! title's rays fill (`CS_SpatialFilterAlpha` writes it last): with rays that find nothing it holds //! the sky's light everywhere, and the dust of a room shows as white specks. It is held as the //! air's is, to `XCL_AMBIENT_ALPHA` times the light around (5 unless given, 0: off). +//! +//! Reflections are traced at half the picture's size: rays the screen-space march resolves take +//! the light seen on screen, the others find nothing and `CS_RayMiss` gives each the sky's light +//! from the sky's cube maps – indoors and at night far above the room's (a cutscene of VIctory-Neo: +//! 10 to 30 against 0.01 to 0.1), the wet look of skin, the sparkles in hair and on car paint. +//! Right after that program (opaque and transparent surfaces; water is left) each texel of its +//! image gets `XCL_AMBIENT_SPECULAR` (1 unless given, 0: off) of the light the gathered points +//! send along the reflected direction instead (`MISS_LIGHT_HLSL`); what the screen-space resolve +//! finds next is still written over it. Ported from VIctory-Neo +//! (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later; its `Role::Miss`, `reflect_light`, +//! `VICTORY_AMBIENT_SPECULAR`, 2026-11-29): the same estimate along the reflected direction, the +//! slots the program writes and reads, which surfaces it acts on. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; @@ -96,6 +108,9 @@ struct Config { /// the light of transparent surfaces and particles is held to this many times the light /// around (0: as the title has it) alpha: f32, + /// reflection rays that found nothing take this share of the light around along the + /// reflected direction instead of the sky's (0: the sky's, as the title has it) + specular: f32, } impl Default for Config { @@ -117,6 +132,8 @@ impl Default for Config { reflect_hold: 1.25, // VIctory-Neo's 4, as `reflect_hold` alpha: 5.0, + // VIctory-Neo's `VICTORY_AMBIENT_SPECULAR=1`: all of the estimate + specular: 1.0, } } } @@ -159,6 +176,7 @@ fn config() -> &'static Config { sky: env_f32("XCL_AMBIENT_SKY", def.sky, 0.0, 1.0), reflect_hold: env_f32("XCL_AMBIENT_REFLECT_HOLD", def.reflect_hold, 0.0, 16.0), alpha: env_f32("XCL_AMBIENT_ALPHA", def.alpha, 0.0, 16.0), + specular: env_f32("XCL_AMBIENT_SPECULAR", def.specular, 0.0, 4.0), } }) } @@ -244,6 +262,9 @@ pub(super) enum PassRole { /// filters the light of transparent surfaces and particles, a 3D volume before the eye /// (`CS_SpatialFilterAlpha`, the last program that writes it) AlphaLight, + /// gives the reflection rays that found nothing the sky's light (`CS_RayMiss`, not + /// `CS_RayMiss_Volumetrics` nor the screen probes' `CS_ScreenProbe_RayMiss`) + RayMiss, } /// Where the reflections' resolves write them: root parameter and dword of its table, the first @@ -257,6 +278,24 @@ const REFLECTION_SLOTS: [(usize, usize); 2] = [(1, 128), (1, 136)]; /// (`ALPHA`, a6e85c6). const ALPHA_SLOT: (usize, usize) = (1, 24); +/// Where `CS_RayMiss` writes the reflected light (R11G11B10_FLOAT, half the picture's size) and +/// where it reads the depth (32-bit, the picture's size), as `REFLECTION_SLOTS`. From VIctory-Neo +/// (`MISS_LIGHT`, `MISS_DEPTH`). +const MISS_LIGHT_SLOT: (usize, usize) = (1, 104); +const MISS_DEPTH_SLOT: (usize, usize) = (0, 1000); +/// Which surfaces a `CS_RayMiss` dispatch's rays are of (its first root constant): the opaque ones +/// and the transparent ones are given the estimate; water's (the depth there is of what lies +/// under it) and any other are left as the title has them. From VIctory-Neo (`MISS_OPAQUE`, +/// `MISS_ALPHA`). +const MISS_LAYERS: [u32; 2] = [0, 1]; + +/// `CS_RayMiss_` and the eight hex digits of a variant's hash, then `_`: not `CS_RayMiss_Volumetrics` +/// nor `CS_ScreenProbe_RayMiss` (VIctory-Neo's `is_miss`). +fn is_ray_miss(blob: &[u8]) -> bool { + const NAME: &[u8] = b"CS_RayMiss_"; + blob.windows(NAME.len() + 9).any(|w| w.starts_with(NAME) && w[NAME.len()..NAME.len() + 8].iter().all(u8::is_ascii_hexdigit) && w[NAME.len() + 8] == b'_') +} + fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool { if needle.is_empty() || haystack.len() < needle.len() { return false; @@ -287,6 +326,8 @@ fn classify_cs(blob: &[u8]) -> Option { Some(PassRole::Radiance) } else if contains_ascii_ci(blob, b"CS_SpatialFilterAlpha") { Some(PassRole::AlphaLight) + } else if is_ray_miss(blob) { + Some(PassRole::RayMiss) } else { None } @@ -628,6 +669,7 @@ struct AmbientDevice { air_pso: ID3D12PipelineState, keep_pso: ID3D12PipelineState, mean_pso: ID3D12PipelineState, + miss_pso: ID3D12PipelineState, sky_copy: ID3D12Resource, sky_level: ID3D12Resource, dummy_depth: ID3D12Resource, @@ -991,6 +1033,60 @@ void main(uint3 at : SV_DispatchThreadID) { } "#; +/// The reflected light of a texel of `CS_RayMiss`'s image (R11G11B10_FLOAT, `width` x `height`, +/// half the picture's size), after `light_hlsl`: the light the four gathered points about it send +/// along the reflected direction (the normal rebuilt from the depth of the `depth_w` x `depth_h` +/// picture, as the diffuse fill takes it along the normal), `ao_strength` of it (the share, +/// `XCL_AMBIENT_SPECULAR` over `XCL_AMBIENT_FRAME`: the cells hold the frame's share of the light +/// surfaces send out). Where the picture shows the sky nothing is reflected (left as it was), and +/// before any frame's light is kept the image is left as the title has it. Ported from +/// VIctory-Neo's `reflect_light` (see the module's note). +const MISS_LIGHT_HLSL: &str = r#" +RWTexture2D out_uav : register(u0); +[numthreads(8, 8, 1)] +void main(uint3 at : SV_DispatchThreadID) { + if (at.x >= width || at.y >= height || depth_w == 0u || depth_h == 0u) return; + float4 mean = sky_level[1]; + if (!(mean.a > 0.0) || !all(isfinite(mean.rgb))) return; + float2 size = float2(depth_w, depth_h); + int2 p = int2((float2(at.xy) + 0.5) * size / float2(width, height)); + float3 c = seen(p, size); + if (c.z >= 999.0) return; + float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size); + float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size); + float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c; + float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c; + float3 n = normalize(cross(dy, dx) + float3(0.0, 0.0, -1e-9)); + if (dot(n, c) > 0.0) n = -n; + float3 v = normalize(c); + float3 ray = v - 2.0 * dot(v, n) * n; + float2 g = (float2(p) + 0.5) / size * float2(PX, PY) - 0.5; + int2 g0 = int2(floor(g)); + float2 f = g - float2(g0); + float4 sr = float4(0.0, 0.0, 0.0, 0.0), sg = float4(0.0, 0.0, 0.0, 0.0), sb = float4(0.0, 0.0, 0.0, 0.0); + float sum = 0.0; + [unroll] + for (int k = 0; k < 4; ++k) { + int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1); + float z = seen(int2((float2(q) + 0.5) * size / float2(PX, PY)), size).z; + float2 bw = float2((k & 1) ? f.x : 1.0 - f.x, (k >> 1) ? f.y : 1.0 - f.y); + float w = (bw.x * bw.y + 1e-3) / (0.02 + abs(z - c.z) / c.z); + uint at0 = POINT_AT + (q.y * PX + q.x) * 3; + sr += w * sky_level[at0]; + sg += w * sky_level[at0 + 1]; + sb += w * sky_level[at0 + 2]; + sum += w; + } + float3 all_ = float3(sr.w, sg.w, sb.w) / sum; + // radiance from the first moments: three times the direction's share for an even spread of + // directions, a little less for a smooth image + float3 found = all_ + 2.0 * float3(dot(sr.xyz, ray), dot(sg.xyz, ray), dot(sb.xyz, ray)) / sum; + found = clamp(found, 0.1 * all_, 3.0 * all_); + found = lerp(found, mean.rgb, 0.2) * ao_strength; + out_uav[at.xy] = all(isfinite(found)) ? clamp(found, 0.0, 16.0) : float3(0.0, 0.0, 0.0); +} +"#; + /// The diffuse light of a texel of the resolve's output (`R9G9B9E5_SHAREDEXP` packed in /// `R32_UINT`), after `light_hlsl`. With the depth: the four gathered points /// around the texel, those at its own depth first, along the normal the depth gives, shaded where @@ -1368,6 +1464,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let air_bc = compile_cs_sm5(AIR_CAP_HLSL)?; let keep_bc = compile_cs_sm5(FRAME_KEEP_HLSL)?; let mean_bc = compile_cs_sm5(FRAME_MEAN_HLSL)?; + let miss_bc = compile_cs_sm5(&light_hlsl(MISS_LIGHT_HLSL))?; // Shared compute RS: [0] 8 root constants (b0), [1] 1 SRV (t0), [2] 2 UAVs (u0..u1) let srv_range = D3D12_DESCRIPTOR_RANGE { @@ -1471,6 +1568,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let air_pso = make_cs(&air_bc, "xcl ambient air_cap")?; let keep_pso = make_cs(&keep_bc, "xcl ambient frame_keep")?; let mean_pso = make_cs(&mean_bc, "xcl ambient frame_mean")?; + let miss_pso = make_cs(&miss_bc, "xcl ambient miss_light")?; let default_hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let make_res = |rd: &D3D12_RESOURCE_DESC, init: D3D12_RESOURCE_STATES| -> Option { @@ -1561,6 +1659,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { air_pso, keep_pso, mean_pso, + miss_pso, sky_copy, sky_level, dummy_depth, @@ -1996,6 +2095,28 @@ unsafe fn find_dispatch_views( ); } } + if role == PassRole::RayMiss { + // Its own slots only (a guess by format could take another half-size image of the + // light): the reflected light, and the depth of the picture it was traced from + let light = pinned(MISS_LIGHT_SLOT.0, MISS_LIGHT_SLOT.1).filter(|(ve, rd)| ve.is_uav && ve.fmt == 26 && flat(rd) && rd.DepthOrArraySize == 1); + uav = light.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, rd.Width as u32, rd.Height, 1)); + let at_least = |w: u64, h: u32| uav.is_some_and(|(_, _, uw, uh, _)| w >= uw as u64 && h >= uh); + let depth = pinned(MISS_DEPTH_SLOT.0, MISS_DEPTH_SLOT.1).filter(|(ve, rd)| !ve.is_uav && matches!(ve.fmt, 21 | 41 | 46) && flat(rd) && at_least(rd.Width, rd.Height)); + static SLOTS: AtomicU64 = AtomicU64::new(0); + if SLOTS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: the missed reflections' light is {} ({:?}), their depth {} ({:?})", + if light.is_some() { "the one in its slot" } else { "not in its slot: left as the title has it" }, + uav.map(|(r, f, w, h, _)| (r, f, w, h)), + if depth.is_some() { "the one in its slot" } else { "not in its slot" }, + depth.as_ref().map(|(ve, rd)| (ve.res, ve.fmt, rd.Width, rd.Height)) + ); + } + depth_hit = depth.map(|(ve, rd)| (ve.res, ve.fmt, rd.Width as u32, rd.Height)); + if depth_hit.is_none() { + uav = None; + } + } if role == PassRole::TemporalResolve && !want_3d { // The resolve's own slots: its // light at dword 176 of root parameter 1's table, the depth it reads at dword 464 of @@ -2052,6 +2173,7 @@ pub(super) unsafe fn after_compute_dispatch( | PassRole::InscatteringVolume | PassRole::Radiance | PassRole::AlphaLight + | PassRole::RayMiss ) { return; } @@ -2059,9 +2181,20 @@ pub(super) unsafe fn after_compute_dispatch( if role == PassRole::InscatteringVolume && cfg.air <= 0.0 || role == PassRole::Radiance && cfg.frame <= 0.0 || role == PassRole::AlphaLight && cfg.alpha <= 0.0 + || role == PassRole::RayMiss && (cfg.specular <= 0.0 || cfg.frame <= 0.0) { return; } + // (which surfaces the miss program's rays are of: its first root constant) + if role == PassRole::RayMiss { + let layer = layout.and_then(|l| l.params.iter().find_map(|p| match *p { + Param::Constants { at, count } if count > 0 => args.get(at as usize..at as usize + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())), + _ => None, + })); + if !layer.is_some_and(|l| MISS_LAYERS.contains(&l)) { + return; + } + } let ty = list_x::tracked_list_type(list); if !matches!(ty, Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE)) { static BAD_TY: AtomicU64 = AtomicU64::new(0); @@ -2130,7 +2263,7 @@ pub(super) unsafe fn after_compute_dispatch( let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); let (depth_raw, depth_fmt, depth_w, depth_h, has_depth) = match (role, depth_opt) { - (PassRole::TemporalResolve, Some((r, f, dw, dh))) => (r as *mut c_void, DXGI_FORMAT(f), dw, dh, 1u32), + (PassRole::TemporalResolve | PassRole::RayMiss, Some((r, f, dw, dh))) => (r as *mut c_void, DXGI_FORMAT(f), dw, dh, 1u32), _ => (ad.dummy_depth.as_raw(), DXGI_FORMAT_R32_FLOAT, 1, 1, 0u32), }; let is_reflect_role = matches!(role, PassRole::ReflectionHistory | PassRole::ReflectionResolve); @@ -2243,6 +2376,12 @@ pub(super) unsafe fn after_compute_dispatch( [w, h, d, 0, 0, cfg.alpha.to_bits(), 0, 0], (w.div_ceil(8), h.div_ceil(8), d.div_ceil(2)), ), + // (the cells hold `frame` of what the surfaces send out: the share is of all of it) + PassRole::RayMiss => ( + ad.miss_pso.as_raw(), + [w, h, depth_w, depth_h, has_depth, (cfg.specular / cfg.frame).to_bits(), sky_ready as u32, PRE_SKY_FALLBACK.to_bits()], + (w.div_ceil(8), h.div_ceil(8), 1), + ), PassRole::SkyDome => return, }; set_heaps(list, 1, &heap_raw); @@ -2252,9 +2391,15 @@ pub(super) unsafe fn after_compute_dispatch( set_cs_consts(list, 0, 8, consts.as_ptr(), 0); set_cs_table(list, 1, gpu0); set_cs_table(list, 2, gpu0 + inc); - if role == PassRole::TemporalResolve && uav_fmt == 42 && has_depth != 0 { + if role == PassRole::TemporalResolve && uav_fmt == 42 && has_depth != 0 || role == PassRole::RayMiss { // where the cells are seen, then their light gathered at the points: what the fill reads + // (for the missed reflections: from this frame's depth, the picture's size; the diffuse + // fill makes them again later in the frame) let level = ad.sky_level.as_raw() as usize; + if role == PassRole::RayMiss { + let picture = [depth_w, depth_h, depth_w, depth_h, has_depth, 0, sky_ready as u32, 0]; + set_cs_consts(list, 0, 8, picture.as_ptr(), 0); + } let passes = [ (ad.place_pso.as_raw(), FRAME_CELLS.0.div_ceil(8), FRAME_CELLS.1.div_ceil(4)), (ad.gather_pso.as_raw(), GATHER_POINTS.0.div_ceil(8), GATHER_POINTS.1.div_ceil(2)), @@ -2267,6 +2412,9 @@ pub(super) unsafe fn after_compute_dispatch( } super::dred::mark_pipeline(list, pso as usize, pso as usize); set_pso(list, pso); + if role == PassRole::RayMiss { + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + } } dispatch(list, disp.0, disp.1, disp.2); uav_barrier(list, uav_res); @@ -2305,6 +2453,16 @@ pub(super) unsafe fn after_compute_dispatch( ); } } + if role == PassRole::RayMiss { + static GIVEN: AtomicU64 = AtomicU64::new(0); + let n = GIVEN.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: ambient: reflections that found nothing given {} of the light around along the reflected direction, {w}x{h} ({n} so far)", + cfg.specular + ); + } + } if role == PassRole::AlphaLight { static BOUND: AtomicU64 = AtomicU64::new(0); let n = BOUND.fetch_add(1, Ordering::Relaxed) + 1; @@ -2450,6 +2608,7 @@ mod tests { assert!(compile_cs_sm5(AIR_CAP_HLSL).is_some(), "AIR_CAP_HLSL failed D3DCompile"); assert!(compile_cs_sm5(FRAME_KEEP_HLSL).is_some(), "FRAME_KEEP_HLSL failed D3DCompile"); assert!(compile_cs_sm5(FRAME_MEAN_HLSL).is_some(), "FRAME_MEAN_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(&light_hlsl(MISS_LIGHT_HLSL)).is_some(), "MISS_LIGHT_HLSL failed D3DCompile"); // the cells the fills read are the cells the keeping writes, and the mean sums all of them assert_eq!((FRAME_CELLS, GATHER_POINTS, LEVEL_ELEMENTS), ((64, 36), (160, 90), 2 + 2 * 2304 + 3 * 14400)); } @@ -2614,6 +2773,86 @@ mod tests { assert!(ALPHA_SLOT.1 % 8 == 0 && !REFLECTION_SLOTS.contains(&ALPHA_SLOT)); } + /// The reflection rays' miss program is followed (opaque and transparent surfaces), not the + /// volumetrics' nor the screen probes'; it gets all of the estimate unless the switch says + /// otherwise, and its slots are whole descriptors of their tables. + #[test] + fn the_missed_reflections_are_followed_and_given_the_estimate_by_default() { + assert_eq!(classify_cs(b"..sr_tracing:CS_RayMiss_de6b91a6_Wrapped.."), Some(PassRole::RayMiss)); + assert_eq!(classify_cs(b"..sr_tracing:CS_RayMiss_Volumetrics_3c5d8c00_Wrapped.."), None); + assert_eq!(classify_cs(b"..CS_ScreenProbe_RayMiss_80a88544_Wrapped.."), None); + assert_eq!(classify_cs(b"..CS_RayMiss_de6b91a_.."), None, "eight hex digits"); + assert_eq!(Config::default().specular, 1.0, "VIctory-Neo's VICTORY_AMBIENT_SPECULAR=1"); + assert_eq!(parse_f32(Some("0"), 1.0, 0.0, 4.0), 0.0, "0: the sky's light, as the title has it"); + assert_eq!(MISS_LAYERS, [0, 1]); + assert!(MISS_LIGHT_SLOT.1 % 8 == 0 && MISS_DEPTH_SLOT.1 % 8 == 0 && MISS_LIGHT_SLOT.0 == 1 && MISS_DEPTH_SLOT.0 == 0); + // the points the program reads are where the gather writes them + assert!(LIGHT_COMMON_HLSL.contains(&format!("#define POINT_AT {}", 2 + 2 * FRAME_CELLS.0 * FRAME_CELLS.1))); + } + + /// R11G11B10_FLOAT of non-negative values (round to nearest), and back. + fn pack_r11g11b10(c: [f32; 3]) -> u32 { + let one = |v: f32, bits: u32| -> u32 { + if v <= 0.0 { + return 0; + } + let e = v.log2().floor() as i32; + let mut m = ((v / 2f32.powi(e) - 1.0) * (1 << bits) as f32).round() as u32; + let mut e = e + 15; + if m == 1 << bits { + m = 0; + e += 1; + } + assert!((1..31).contains(&e), "{v} out of the test's range"); + (e as u32) << bits | m + }; + one(c[0], 6) | one(c[1], 6) << 11 | one(c[2], 5) << 22 + } + + fn unpack_r11g11b10(v: u32) -> [f32; 3] { + let one = |x: u32, bits: u32| { + let (e, m) = (x >> bits, x & ((1 << bits) - 1)); + if e == 0 { m as f32 / (1 << bits) as f32 * 2f32.powi(-14) } else { (1.0 + m as f32 / (1 << bits) as f32) * 2f32.powi(e as i32 - 15) } + }; + [one(v & 0x7FF, 6), one((v >> 11) & 0x7FF, 6), one(v >> 22, 5)] + } + + /// After the miss program, a reflection that found nothing holds the light the points around + /// send along the reflected direction (here the same from everywhere: 0.1 of what surfaces + /// send out kept by the cells, the share 1 / 0.8 of it) instead of the sky's 20; where the + /// picture shows the sky it is left, and before any frame's light is kept so is all of it. + #[test] + fn missed_reflections_take_the_light_around_on_gpu() { + assert_eq!(pack_r11g11b10([20.0, 20.0, 20.0]), pack_r11g11b10(unpack_r11g11b10(pack_r11g11b10([20.0, 20.0, 20.0])))); + let sky = pack_r11g11b10([20.0, 20.0, 20.0]); + let texels = [sky; 64]; + // the top half 10 m away (depth is 0.1 m over the distance), the bottom half the sky + let mut depth = [0.0f32; 64]; + depth[..32].fill(0.01); + let mut level = vec![[0.0f32; 4]; LEVEL_ELEMENTS as usize]; + level[0] = [0.6, 0.6, 0.6, 0.6]; + level[1] = [0.1, 0.1, 0.1, 1.0]; + let cells = (FRAME_CELLS.0 * FRAME_CELLS.1) as usize; + level[2..2 + cells].fill([0.1, 0.1, 0.1, 1.0]); + level[2 + 2 * cells..].fill([0.0, 0.0, 0.0, 0.1]); + let share = Config::default().specular / Config::default().frame; + let consts = [8, 8, 8, 8, 1, share.to_bits(), 1, 0]; + let run = |level: &[[f32; 4]]| unsafe { run_on_image(|ad| &ad.miss_pso, DXGI_FORMAT_R11G11B10_FLOAT, false, Some(&depth), consts, &texels, level) }; + let Some(out) = run(&level) else { return }; + for (i, &v) in out.iter().enumerate() { + let c = unpack_r11g11b10(v); + if i < 32 { + // (within a step of the 5-bit blue mantissa: the store rounds toward zero) + assert!(c.iter().all(|&x| (x - 0.1 * share).abs() < 0.1 * share / 32.0), "texel {i}: {c:?} for {}", 0.1 * share); + } else { + assert_eq!(v, sky, "texel {i} shows the sky: left as it was"); + } + } + level[1][3] = 0.0; + let Some(out) = run(&level) else { return }; + assert!(out.iter().all(|&v| v == sky), "no frame's light kept: the image as the title has it"); + } + /// R9G9B9E5 as the programs pack it. fn pack_r9(c: [f32; 3]) -> u32 { let c = c.map(|v| v.clamp(0.0, 65408.0)); @@ -2647,6 +2886,20 @@ mod tests { consts: [u32; 8], texels: &[u32; 64], level: &[[f32; 4]], + ) -> Option<[u32; 64]> { + run_on_image(pick, DXGI_FORMAT_R32_UINT, raw_t0, None, consts, texels, level) + } + + /// `run_on_r9_image` with an image of `format` (32 bits a texel) and, given `depth`, an 8x8 + /// R32_FLOAT depth holding it at `t0`. + unsafe fn run_on_image( + pick: impl Fn(&AmbientDevice) -> &ID3D12PipelineState, + format: DXGI_FORMAT, + raw_t0: bool, + depth: Option<&[f32; 64]>, + consts: [u32; 8], + texels: &[u32; 64], + level: &[[f32; 4]], ) -> Option<[u32; 64]> { assert_eq!(level.len(), LEVEL_ELEMENTS as usize); let mut dev: Option = None; @@ -2690,7 +2943,8 @@ mod tests { const PITCH: usize = 256; let level_bytes = LEVEL_ELEMENTS as usize * 16; let image_at = level_bytes.next_multiple_of(512); - let upload = make(D3D12_HEAP_TYPE_UPLOAD, &buffer((image_at + 8 * PITCH) as u64), D3D12_RESOURCE_STATE_GENERIC_READ); + let depth_at = image_at + 8 * PITCH; + let upload = make(D3D12_HEAP_TYPE_UPLOAD, &buffer((depth_at + 8 * PITCH) as u64), D3D12_RESOURCE_STATE_GENERIC_READ); let readback = make(D3D12_HEAP_TYPE_READBACK, &buffer((8 * PITCH) as u64), D3D12_RESOURCE_STATE_COPY_DEST); let image = make( D3D12_HEAP_TYPE_DEFAULT, @@ -2700,18 +2954,37 @@ mod tests { Height: 8, DepthOrArraySize: 1, MipLevels: 1, - Format: DXGI_FORMAT_R32_UINT, + Format: format, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() }, D3D12_RESOURCE_STATE_COPY_DEST, ); + let depth_image = depth.map(|_| { + make( + D3D12_HEAP_TYPE_DEFAULT, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + ) + }); let mut p = std::ptr::null_mut(); upload.Map(0, None, Some(&mut p)).unwrap(); std::ptr::copy_nonoverlapping(level.as_ptr() as *const u8, p as *mut u8, level_bytes); for y in 0..8 { std::ptr::copy_nonoverlapping(texels[y * 8..].as_ptr(), (p as *mut u8).add(image_at + y * PITCH) as *mut u32, 8); + if let Some(depth) = depth { + std::ptr::copy_nonoverlapping(depth[y * 8..].as_ptr(), (p as *mut u8).add(depth_at + y * PITCH) as *mut f32, 8); + } } upload.Unmap(0, None); @@ -2725,10 +2998,11 @@ mod tests { let copy_buffer: unsafe extern "system" fn(*mut c_void, *mut c_void, u64, *mut c_void, u64, u64) = std::mem::transmute(real::orig_fn(list_raw, 15)); copy_buffer(list_raw, ad.sky_level.as_raw(), 0, upload.as_raw(), 0, level_bytes as u64); list_x::transition(list_raw, ad.sky_level.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - let footprint = |offset: usize| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + let footprint_of = |offset: usize, format: DXGI_FORMAT| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: offset as u64, - Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R32_UINT, Width: 8, Height: 8, Depth: 1, RowPitch: PITCH as u32 }, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: 8, Height: 8, Depth: 1, RowPitch: PITCH as u32 }, }; + let footprint = |offset: usize| footprint_of(offset, format); let in_image = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&image), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, @@ -2746,6 +3020,20 @@ mod tests { }; list_x::pc_copy_texture_region(list_raw, &in_image, 0, 0, 0, &in_upload, std::ptr::null()); list_x::transition(list_raw, image.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + if let Some(d) = &depth_image { + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(d), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint_of(depth_at, DXGI_FORMAT_R32_FLOAT) }, + }; + list_x::pc_copy_texture_region(list_raw, &to, 0, 0, 0, &from, std::ptr::null()); + list_x::transition(list_raw, d.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } let (cpu0, gpu0) = ad.alloc_group(); let inc = ad.inc as u64; @@ -2767,7 +3055,7 @@ mod tests { ) } else { ( - ad.dummy_depth.as_raw(), + depth_image.as_ref().map_or(ad.dummy_depth.as_raw(), |d| d.as_raw()), D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R32_FLOAT, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, @@ -2777,7 +3065,7 @@ mod tests { ) }; let image_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: DXGI_FORMAT_R32_UINT, + Format: format, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 } }, }; From f0255ae8187466e07921ccf344374414a0e67df6 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:45:12 +0100 Subject: [PATCH 129/175] XGameRuntime: skipped Bink movies show black instead of their memory With XCL_SKIP_BINK the title's movies are fast-advanced without decoding, but the title still draws the frame buffers it registered with BinkRegisterFrameBuffers through its own YUV shader. Nothing ever wrote them, so it showed whatever the memory held: the full-screen cyan/green noise frames (six frames of two runs, each inside a "Bink: skipping movie #n" window of the log) and, where the planes were zero, the flat green frame (every texel 0xff008700 = (0, 135, 0), which is RAD's BT.601 limited-range conversion of Y = cR = cB = 0). The skip now wraps BinkRegisterFrameBuffers as well: it remembers the title's BINKFRAMEBUFFERS per movie and paints the Y / cR / cB planes of every frame set black (16 / 128 / 128) and an alpha plane 0, when the buffers are registered for a movie that will be skipped and again when the skip begins. The H plane is left alone. The struct layout is the one Bink2Scarlett.dll uses: BinkGetFrameBuffersInfo writes the sizes at +0x04..+0x10 and clears three 0x50-byte plane sets at +0x18, setting each 16-byte plane's Allocate at +8; the decoder reads the buffer pointer at +0 of the frame set FrameNum (+0x14) selects. BinkRegisterFrameBuffers keeps the title's pointer, so the title's struct is the one Bink would decode into. A struct with other than 1-3 frame sets, or a plane whose pitch is below its width, is not touched. XCL_SKIP_BINK_BLACK=0 leaves the planes as before. Nothing changes without XCL_SKIP_BINK (the exports are not wrapped then). The test fails with the switch off. No change to translated shaders. --- crates/xcl/src/hle/bink.rs | 183 ++++++++++++++++++++++++++++++++++++- 1 file changed, 182 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/bink.rs b/crates/xcl/src/hle/bink.rs index 84fa573aa5..18b949d611 100644 --- a/crates/xcl/src/hle/bink.rs +++ b/crates/xcl/src/hle/bink.rs @@ -12,10 +12,15 @@ //! - `1` / `on` / `true` / `intro`: skip non-looping movies (intro/logo/cutscenes); looping //! movies (`BINKWILLLOOP`, bit 7 of `OpenFlags`) still forward to the real Bink DLL //! - `all`: skip all Bink movies, including looping ones +//! +//! A skipped movie's frame buffers (the planes the title registers with `BinkRegisterFrameBuffers` +//! and draws through its own YUV shader) are never decoded into, so the title showed whatever its +//! memory held: full-screen noise, or flat green (0, 135, 0) where the planes were zero. +//! They are painted black instead (`XCL_SKIP_BINK_BLACK=0` leaves them as they are). #![allow(non_snake_case)] -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Mutex, Once, OnceLock}; @@ -38,6 +43,73 @@ pub struct BinkHeader { /// `BINKWILLLOOP` flag in `BinkHeader::open_flags` (set by `BinkSetWillLoop`). pub const BINK_WILL_LOOP: u32 = 0x0000_0080; +/// One plane of `BINKFRAMEBUFFERS`. Layout read from `Bink2Scarlett.dll`: `BinkGetFrameBuffersInfo` +/// sets `allocate` at +8 of each 16-byte plane and the decoder reads the buffer pointer at +0. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct BinkPlane { + pub buffer: *mut u8, + pub allocate: i32, + pub buffer_pitch: u32, +} + +/// `BINKFRAMEPLANESET`: the Y, cR, cB, A and H planes of one frame. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct BinkFramePlaneSet { + pub planes: [BinkPlane; 5], +} + +/// `BINKFRAMEBUFFERS` (`BinkGetFrameBuffersInfo` writes the sizes and clears 3 plane sets at +0x18; +/// `BinkRegisterFrameBuffers` keeps the title's pointer, so the title's struct is the one used). +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct BinkFrameBuffers { + pub total_frames: i32, + pub ya_width: u32, + pub ya_height: u32, + pub crcb_width: u32, + pub crcb_height: u32, + pub frame_num: u32, + pub frames: [BinkFramePlaneSet; 3], +} + +/// Bytes that make each plane black in RAD's BT.601 limited-range conversion (Y 16, cR / cB 128; +/// all-zero planes convert to (0, 135, 0)), alpha 0 so an alpha movie shows nothing; H is left alone. +const PLANE_BLACK: [Option; 5] = [Some(16), Some(128), Some(128), Some(0), None]; + +/// `XCL_SKIP_BINK_BLACK=0` leaves a skipped movie's frame buffers as the title gave them. +fn black_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SKIP_BINK_BLACK").map_or(true, |v| v.trim() != "0")) +} + +/// Paints every frame of `fb` black; returns the bytes written (0 when the struct looks wrong). +unsafe fn blacken(fb: *mut BinkFrameBuffers) -> usize { + if fb.is_null() { + return 0; + } + let f = &*fb; + if !(1..=3).contains(&f.total_frames) { + return 0; + } + let mut written = 0; + for set in &f.frames[..f.total_frames as usize] { + for (k, plane) in set.planes.iter().enumerate() { + let Some(value) = PLANE_BLACK[k] else { continue }; + let (w, h) = if k == 1 || k == 2 { (f.crcb_width, f.crcb_height) } else { (f.ya_width, f.ya_height) }; + if plane.buffer.is_null() || w == 0 || h == 0 || w > 16384 || h > 16384 || plane.buffer_pitch < w { + continue; + } + for row in 0..h as usize { + std::ptr::write_bytes(plane.buffer.add(row * plane.buffer_pitch as usize), value, w as usize); + } + written += w as usize * h as usize; + } + } + written +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Mode { Off, @@ -90,8 +162,11 @@ static REAL_DO_FRAME_ASYNC: AtomicUsize = AtomicUsize::new(0); static REAL_DO_FRAME_ASYNC_MULTI: AtomicUsize = AtomicUsize::new(0); static REAL_DO_FRAME_ASYNC_WAIT: AtomicUsize = AtomicUsize::new(0); static REAL_GOTO: AtomicUsize = AtomicUsize::new(0); +static REAL_REGISTER_FRAME_BUFFERS: AtomicUsize = AtomicUsize::new(0); static LOGGED_HANDLES: Mutex>> = Mutex::new(None); +/// Movie handle → the `BINKFRAMEBUFFERS` the title registered for it. +static FRAME_BUFFERS: Mutex>> = Mutex::new(None); static SKIPPED_MOVIES: AtomicU64 = AtomicU64::new(0); /// If `XCL_SKIP_BINK` is enabled and `function` is a wrapped Bink 2 export, store `real_addr` @@ -152,6 +227,10 @@ fn wrap_with_mode(m: Mode, function: &str, real_addr: usize) -> usize { REAL_GOTO.store(real_addr, Ordering::Release); BinkGoto_hook as usize } + "BinkRegisterFrameBuffers" => { + REAL_REGISTER_FRAME_BUFFERS.store(real_addr, Ordering::Release); + BinkRegisterFrameBuffers_hook as usize + } _ => return real_addr, }; static BANNER: Once = Once::new(); @@ -206,6 +285,12 @@ pub unsafe fn fast_advance(bink: *mut BinkHeader, m: Mode) -> bool { dur_s, h.open_flags ); + if black_on() { + if let Some(fb) = frame_buffers_of(bink) { + let bytes = blacken(fb); + crate::xlog_info!("Bink: movie #{n}'s frame buffers painted black ({bytes} bytes; XCL_SKIP_BINK_BLACK=0 leaves them)"); + } + } } h.frame_num = h.frames; h.last_frame_num = h.frames; @@ -223,6 +308,31 @@ type DoFrameAsyncFn = unsafe extern "system" fn(*mut BinkHeader, u32, u32) -> i3 type DoFrameAsyncMultiFn = unsafe extern "system" fn(*mut BinkHeader, *const u32, i32) -> i32; type DoFrameAsyncWaitFn = unsafe extern "system" fn(*mut BinkHeader, i32) -> i32; type GotoFn = unsafe extern "system" fn(*mut BinkHeader, u32, u32); +type RegisterFrameBuffersFn = unsafe extern "system" fn(*mut BinkHeader, *mut BinkFrameBuffers); + +fn remember_frame_buffers(bink: *mut BinkHeader, fb: *mut BinkFrameBuffers) { + if !bink.is_null() && !fb.is_null() { + FRAME_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(bink as usize, fb as usize); + } +} + +fn frame_buffers_of(bink: *mut BinkHeader) -> Option<*mut BinkFrameBuffers> { + let g = FRAME_BUFFERS.lock().unwrap(); + g.as_ref()?.get(&(bink as usize)).map(|&fb| fb as *mut BinkFrameBuffers) +} + +unsafe extern "system" fn BinkRegisterFrameBuffers_hook(bink: *mut BinkHeader, fb: *mut BinkFrameBuffers) { + let real = REAL_REGISTER_FRAME_BUFFERS.load(Ordering::Acquire); + if real != 0 { + let f: RegisterFrameBuffersFn = std::mem::transmute(real); + f(bink, fb); + } + remember_frame_buffers(bink, fb); + // Black before the first advance too, in case the title draws the movie before it asks for a frame. + if black_on() && should_skip_handle(bink, mode()) { + blacken(fb); + } +} unsafe extern "system" fn BinkOpen_hook(name: *const u8, flags: u32) -> *mut BinkHeader { let real = REAL_OPEN.load(Ordering::Acquire); @@ -271,6 +381,9 @@ unsafe extern "system" fn BinkClose_hook(bink: *mut BinkHeader) { if let Some(set) = LOGGED_HANDLES.lock().unwrap().as_mut() { set.remove(&(bink as usize)); } + if let Some(map) = FRAME_BUFFERS.lock().unwrap().as_mut() { + map.remove(&(bink as usize)); + } } let real = REAL_CLOSE.load(Ordering::Acquire); if real != 0 { @@ -445,6 +558,74 @@ mod tests { } } + #[test] + fn frame_buffers_abi_matches_the_dll() { + assert_eq!(std::mem::size_of::(), 0x10); + assert_eq!(std::mem::offset_of!(BinkPlane, allocate), 0x08); + assert_eq!(std::mem::size_of::(), 0x50); + assert_eq!(std::mem::offset_of!(BinkFrameBuffers, frame_num), 0x14); + assert_eq!(std::mem::offset_of!(BinkFrameBuffers, frames), 0x18); + assert_eq!(std::mem::size_of::(), 0x18 + 0xf0); + } + + #[test] + fn a_skipped_movie_shows_black_not_the_memory_its_planes_held() { + let (w, h, cw, ch, pitch, cpitch) = (64u32, 8u32, 32u32, 4u32, 80usize, 48usize); + let mut planes: Vec> = (0..6).map(|k| vec![0xA5; if k % 3 == 0 { pitch * h as usize } else { cpitch * ch as usize }]).collect(); + let none = BinkPlane { buffer: std::ptr::null_mut(), allocate: 0, buffer_pitch: 0 }; + let mut fb = BinkFrameBuffers { + total_frames: 2, + ya_width: w, + ya_height: h, + crcb_width: cw, + crcb_height: ch, + frame_num: 0, + frames: [BinkFramePlaneSet { planes: [none; 5] }; 3], + }; + for set in 0..2 { + for k in 0..3 { + let p = &mut planes[set * 3 + k]; + fb.frames[set].planes[k] = BinkPlane { buffer: p.as_mut_ptr(), allocate: 1, buffer_pitch: if k == 0 { pitch as u32 } else { cpitch as u32 } }; + } + } + // (on the heap: a stack address may repeat one another test's thread already logged) + let movie: *mut BinkHeader = Box::into_raw(Box::new(BinkHeader { width: 60, height: 8, frames: 90, frame_rate: 30, frame_rate_div: 1, ..Default::default() })); + let looping: *mut BinkHeader = Box::into_raw(Box::new(BinkHeader { frames: 90, open_flags: BINK_WILL_LOOP, ..Default::default() })); + remember_frame_buffers(looping, &mut fb); + unsafe { + // A movie that plays keeps its planes. + assert!(!fast_advance(looping, Mode::NonLooping)); + } + assert!(planes.iter().all(|p| p.iter().all(|&b| b == 0xA5))); + + remember_frame_buffers(movie, &mut fb); + unsafe { + assert!(fast_advance(movie, Mode::NonLooping)); + } + for (i, p) in planes.iter().enumerate() { + let (width, rows, stride, black) = if i % 3 == 0 { (w as usize, h as usize, pitch, 16) } else { (cw as usize, ch as usize, cpitch, 128) }; + for r in 0..rows { + assert!(p[r * stride..r * stride + width].iter().all(|&b| b == black), "plane {i} row {r}"); + // the pitch's padding is not the plane's + assert!(p[r * stride + width..(r + 1) * stride].iter().all(|&b| b == 0xA5), "plane {i} row {r} padding"); + } + } + + // A struct that does not look like frame buffers is left alone. + for frames in [0, 7] { + fb.total_frames = frames; + unsafe { + assert_eq!(blacken(&mut fb), 0); + } + } + unsafe { + BinkClose_hook(movie); + BinkClose_hook(looping); + drop(Box::from_raw(movie)); + drop(Box::from_raw(looping)); + } + } + #[test] fn wrap_only_intercepts_known_exports_when_enabled() { let dummy = 0x1234_5678usize; From f93e55fb7c7f2e6ade427e8b1f89b49b2bb62417 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:56:55 +0100 Subject: [PATCH 130/175] D3D12.X: binds do not wait for the BVH builder's pipelines while it is off While XCL_BVH_BUILDER is unset the passes of the title's XboxBvhBuilder.dll are left out (bind::bvh_builder_runs), but a bind of one of its 52 compute pipelines still waited for the build, up to XCL_CS_PSO_WAIT_MS. On a cold driver cache a retail title's recording thread waited the full 20 s for one builder pipeline after another as the world loaded behind its movies: 11-13 waits in a row, 220-260 s with no frame presented, in the runs that played the movies (three runs). 12 of the 13 programs waited for in one of them are byte for byte the DLL's containers (FNV-64 of the 52 DXBC containers in the DLL against the logged records; parts SFI0 ISG1 OSG1 PSV0 RTS0 STAT ILDN HASH DXIL, no PRIV, an ILDN path naming XboxBvhBuilder). They are not Bink's: Bink2Scarlett.dll holds no shader container, and the intro movie is drawn in the frames that run dumped. The runs that skipped the movies had warm driver caches (mean driver compile 2-35 ms against 759-3229 ms), which is why they showed no such waits. XCL_BVH_SPARE (default on, =0 waits as before) marks such a pipeline as one binds go on without (pso_async::image_only): the bind gets the stand-in at once and the build goes on in the background; its dispatches are skipped until it is built, as they were after a wait that ran out. A builder program is known by its byte code lying in the mapped xboxbvhbuilder.dll or by the builder's name in its container. With XCL_BVH_BUILDER=1 nothing changes. The translation of console programs is not touched. --- crates/xcl/src/hle/d3d12x/bind.rs | 2 +- crates/xcl/src/hle/d3d12x/bvh_spare.rs | 148 +++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_async.rs | 2 +- crates/xcl/src/hle/d3d12x/real.rs | 2 + 5 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/bvh_spare.rs diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 15695d006f..cf0591e58c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -4282,7 +4282,7 @@ fn bvh_builder_runs(flags: u32, enabled: bool) -> bool { flags & DISPATCH_THREAD_DIMENSIONS == 0 || enabled } -fn bvh_builder_enabled() -> bool { +pub(super) fn bvh_builder_enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("XCL_BVH_BUILDER").is_ok_and(|v| v.trim() == "1")) } diff --git a/crates/xcl/src/hle/d3d12x/bvh_spare.rs b/crates/xcl/src/hle/d3d12x/bvh_spare.rs new file mode 100644 index 0000000000..017eb32472 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/bvh_spare.rs @@ -0,0 +1,148 @@ +//! `XCL_BVH_SPARE` (default on; `=0` turns it off): while the title's BVH builder does not run +//! (`XCL_BVH_BUILDER` unset, `bind::bvh_builder_enabled`), binds do not wait for a compute +//! pipeline made from one of the builder's programs – those of the title's `XboxBvhBuilder.dll`, +//! known by the module their byte code lies in or by the builder's name in their debug data +//! (`ILDN`). The bind goes on with the stand-in while the pipeline is built +//! (`pso_async::image_only`), as it did once its wait had run out (`XCL_CS_PSO_WAIT_MS`). +//! +//! The builder's passes are left out while it does not run (`bind::bvh_builder_runs`), so a +//! wait for one of its pipelines held a title thread for nothing. On a cold driver cache a +//! retail title's recording thread waited 20 s (`XCL_CS_PSO_WAIT_MS=20000`) for one builder +//! pipeline after another while the world loaded behind its movies: 11 – 13 times in a row, +//! 220 – 260 s with no frame presented (12 of the 13 programs it waited for in one run were +//! byte for byte the DLL's, the 13th a program of the title's own). + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::OnceLock; + +use windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC; + +/// The builder's DLL, as `modules` names a mapped image. +const MODULE: &str = "xboxbvhbuilder.dll"; +/// The builder's name, as its programs' debug data hold it (the path of their build). +const NAME: &[u8] = b"XboxBvhBuilder"; + +fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| on_of(std::env::var("XCL_BVH_SPARE").ok().as_deref())) +} + +/// An `XCL_BVH_SPARE` value: on unless `0`. +fn on_of(v: Option<&str>) -> bool { + v.is_none_or(|v| v.trim() != "0") +} + +/// Whether console program `cs` is one of the BVH builder's: its byte code lies in the +/// builder's DLL (`module`: the mapped image it lies in), or its container names the builder. +fn builder_program(cs: &[u8], module: Option<&str>) -> bool { + module == Some(MODULE) || cs.windows(NAME.len()).any(|w| w == NAME) +} + +/// Whether binds go on without the compute pipeline of console program `cs`: with the switch +/// `on`, a program of the builder while the builder does not run (`builder_runs`). +fn spared_with(cs: &[u8], module: Option<&str>, on: bool, builder_runs: bool) -> bool { + on && !builder_runs && builder_program(cs, module) +} + +/// Whether binds go on without the compute pipeline `desc` describes, built by the workers from +/// console program `cs` (the title's byte code copied): one of the BVH builder's while it does +/// not run. The first few are logged. +pub(super) unsafe fn spared(cs: &[u8], desc: *const c_void) -> bool { + if !on() || super::bind::bvh_builder_enabled() { + return false; + } + let at = if crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + (*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)).CS.pShaderBytecode as usize + } else { + 0 + }; + let module = crate::modules::find_mapped_by_addr(at).map(|m| m.name.clone()); + if !spared_with(cs, module.as_deref(), true, false) { + return false; + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: compute pipeline of record {:016x} is one of the BVH builder's, whose passes are left out: binds go on without it while it is built (#{n}; XCL_BVH_SPARE=0 waits for them)", + crate::gpu::shader::fnv64(cs) + ); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::hle::d3d12x::pso_async; + use std::sync::mpsc; + + /// The bytes of a container whose debug data name the builder, as those of the DLL's 52 + /// programs do (their `ILDN` part holds the path of their build); no complete container. + fn builder_container() -> Vec { + let mut c = b"DXBC".to_vec(); + c.extend_from_slice(&[0; 60]); + c.extend_from_slice(b"ILDN\x40\x00\x00\x00\x00\x00\x30\x00X:\\src\\3rdparty\\Microsoft\\XboxBvhBuilder\\Build\\Release\\Output\\a.pdb\x00"); + c.extend_from_slice(&[0xAB; 32]); + c + } + + #[test] + fn the_switch_is_on_unless_0() { + assert!(on_of(None)); + assert!(on_of(Some("1"))); + assert!(on_of(Some(""))); + assert!(!on_of(Some("0"))); + assert!(!on_of(Some(" 0 "))); + } + + #[test] + fn a_builder_program_is_known_by_its_module_or_its_name() { + let plain = vec![0x5Au8; 256]; + assert!(builder_program(&builder_container(), None)); + assert!(builder_program(&plain, Some(MODULE)), "byte code in the builder's DLL"); + assert!(!builder_program(&plain, None)); + assert!(!builder_program(&plain, Some("game_scarlett_master.exe"))); + assert!(!builder_program(b"XboxBvhBuilde", None), "a part of the name is not it"); + } + + #[test] + fn only_a_builder_program_is_spared_and_only_while_the_builder_does_not_run() { + let bvh = builder_container(); + assert!(spared_with(&bvh, None, true, false)); + assert!(!spared_with(&bvh, None, true, true), "XCL_BVH_BUILDER=1: its pipelines are waited for"); + assert!(!spared_with(&bvh, None, false, false), "XCL_BVH_SPARE=0"); + assert!(!spared_with(&[0u8; 128], None, true, false), "a program of the title's own"); + } + + /// A bind does not wait for a compute pipeline of the builder still being built: it gets the + /// stand-in at once; a pipeline of the title's own is still waited for. + #[test] + fn a_bind_does_not_wait_for_a_builder_pipeline_being_built() { + let (builder, own) = (0x7E57_B5A1usize, 0x7E57_B5A2usize); + let (go, finish) = mpsc::channel::<()>(); + pso_async::submit_lazy(builder, true, Box::new(move || { + let _ = finish.recv_timeout(std::time::Duration::from_secs(30)); + 0 + }), 0); + pso_async::submit_lazy(own, true, Box::new(|| 0), 0); + // (as `real::go_background` does with what `spared` says) + for (pso, cs) in [(builder, builder_container()), (own, vec![0u8; 128])] { + if spared_with(&cs, None, true, false) { + pso_async::image_only(pso); + } + } + assert!(!pso_async::waits_for(builder), "a dispatch with it does not wait either"); + assert!(pso_async::waits_for(own), "the title's own pipeline is waited for"); + // (on a thread: a bind that waits would wait for `go`, below) + let (bound_tx, bound) = mpsc::channel(); + std::thread::spawn(move || { + let _ = bound_tx.send(pso_async::resolve_for_bind(builder)); + }); + let bind = bound.recv_timeout(std::time::Duration::from_secs(5)); + let _ = go.send(()); + assert_eq!(bind.expect("the bind waited for the build"), builder, "still being built: the stand-in"); + let _ = (pso_async::released(builder), pso_async::released(own)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 6f3c921376..5f898566e7 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -11,6 +11,7 @@ mod alloc_pool; pub mod bind; +mod bvh_spare; mod bvh_want; mod capture; pub mod console_heap; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 0384af1ceb..2334da312c 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -2875,7 +2875,7 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); if n < 16 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: a compute program that writes only images is still being built: its dispatches are left out until it is ({} so far)", n + 1); + crate::xlog_info!("D3D12.X: a compute program binds go on without (one that writes only images, or the BVH builder's) is still being built: its dispatches are left out until it is ({} so far)", n + 1); } } p.stand(pso) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2bbde820fc..2e9e64b92d 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8011,6 +8011,8 @@ unsafe fn go_background( }; // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); + // one of the BVH builder's programs while its passes are left out: binds go on without it too + let image_only = image_only || compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| super::bvh_spare::spared(b, desc))); // (a graphics pipeline's shaders by name: one that draws once and is kept is waited for) let names = match &owned { OwnedDesc::Graphics(_, b, ..) | OwnedDesc::Stream(_, _, b) => stage_names(b, &parts), From 510e466f4c248e0bc6cba7289065ee38a79f311a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:13:12 +0100 Subject: [PATCH 131/175] Tests: probe the console FSR4 upscaler's history over frames on the GPU The retail title upscales with the console's FSR4 when it runs as a Series S (1280x720 -> 1920x1080, a history kept across frames), and its people leave copies along their path, look see-through with a dot pattern, and the last shot shows through camera cuts. This probe runs the game's own amd_fidelityfx_upscaler_xbox.dll through XCL for eleven frames with clean, known inputs, so the upscaler can be checked apart from the title's G-buffer, motion vectors and depth. A 200x200 square of 1.0 on a 0.05 background holds still for six frames, then moves 600 px with motion vectors that say so (or, with ..._GONE=1, just disappears). On an RX 9070 XT the place it left keeps a third of it (0.336, then 0.305, 0.265, 0.246 three frames later; 0.315 .. 0.231 when it disappears): the history is hardly rejected, though current and history differ 20x. A darker scene keeps more (..._SCALE=0.1: 0.65 of the square). The square's depth (..._FLAT_DEPTH=1), jitter (..._JITTER=1) and compiling the passes whole (XCL_LINK_MEM=0) change nothing. A frame with reset is right (flat 0.5 everywhere), and the auto exposure FSR4 computes is sane and follows the scene (..._SMALL=1: 1.46 at scale 1, 7.37 at 0.1, 0.32 on the grey reset frame). So the upscaler as XCL runs it keeps history it should drop; the title's inputs are not needed to show it. With XCL_SKIP_CS the passes it names are left out on purpose (the frames' skipped dispatches are allowed then). Opt-in like the other FSR4 probe: XCL_SAMPLE_DLLS, XCL_CONSOLE_LISTS=1 and XCL_PROBE_FSR_TEMPORAL=1; it does nothing otherwise. ..._IMAGE= with ..._DUMP= runs a still picture and writes each output as a BMP; ..._RESET_ALL=1 sets reset on every frame. --- crates/xcl/tests/console_dlls_e2e.rs | 389 +++++++++++++++++++++++++++ 1 file changed, 389 insertions(+) diff --git a/crates/xcl/tests/console_dlls_e2e.rs b/crates/xcl/tests/console_dlls_e2e.rs index 0c6e9f5cfb..9cc5632400 100644 --- a/crates/xcl/tests/console_dlls_e2e.rs +++ b/crates/xcl/tests/console_dlls_e2e.rs @@ -1169,6 +1169,395 @@ fn fsr4_console_upscaler_creates_a_context_probe() { } } +/// f32 -> f16 bits for the probe's inputs (normal values and zero; the mantissa truncated). +fn f16_bits(x: f32) -> u16 { + let b = x.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let e = ((b >> 23) & 0xFF) as i32 - 127 + 15; + if x == 0.0 || e <= 0 { + return sign; + } + if e >= 31 { + return sign | 0x7C00; + } + sign | (e as u16) << 10 | ((b >> 13) & 0x3FF) as u16 +} + +/// Probe (`XCL_PROBE_FSR_TEMPORAL=1`, with `XCL_SAMPLE_DLLS` and `XCL_CONSOLE_LISTS=1`): the +/// console FSR4 upscaler's history over several frames on the GPU, as the retail title's camera +/// cuts and walking characters need it. A bright square on a dark background holds still for six +/// frames (the first with `reset`), then moves 600 pixels right with motion vectors that say +/// so: the place it left must show the background again (else a ghost stays behind). Then a +/// frame with `reset` and a flat grey picture must be grey everywhere (else the last shot shows +/// through a camera cut). It prints the mean red of each region per frame it reads back. +#[test] +fn fsr4_console_upscaler_drops_history_it_should_probe() { + let Some(dir) = setup() else { return }; + if std::env::var_os("XCL_PROBE_FSR_TEMPORAL").is_none() { + return; + } + let m = load(dir, "amd_fidelityfx_upscaler_xbox.dll"); + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use xcl::hle::d3d12x::console_list; + unsafe { + let iid: [u8; 16] = [0xf1, 0x19, 0x98, 0x18, 0xb6, 0x1d, 0x57, 0x4b, 0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7]; + let mut dev: *mut std::ffi::c_void = std::ptr::null_mut(); + assert!(xcl::hle::d3d12x::D3D12XboxCreateDevice(std::ptr::null_mut(), std::ptr::null(), iid.as_ptr() as _, &mut dev) >= 0); + let mut backend = FfxBackend { header: FfxHeader { ty: 0x0100_0002, next: std::ptr::null_mut() }, device: dev }; + let mut desc = FfxCreateUpscale { + header: FfxHeader { ty: 0x0001_0000, next: &mut backend.header }, + // the game's configuration, the only one the DLL takes: HDR | inverted depth | auto + // exposure, 1280x720 -> 1920x1080 + flags: 1 | 1 << 3 | 1 << 5, + max_render: [1280, 720], + max_upscale: [1920, 1080], + message: 0, + }; + let create: extern "C" fn(*mut usize, *mut FfxHeader, *const u8) -> u32 = std::mem::transmute(proc(&m, "ffxCreateContext")); + let dispatch: extern "C" fn(*mut usize, *const u32) -> u32 = std::mem::transmute(proc(&m, "ffxDispatch")); + let mut ctx = 0usize; + assert_eq!(create(&mut ctx, &mut desc.header, std::ptr::null()), 0, "ffxCreateContext"); + let device = ID3D12Device::from_raw_borrowed(&dev).unwrap(); + let tex = |w: u32, h: u32, f: DXGI_FORMAT, uav: bool| -> ID3D12Resource { + let mut r: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w as u64, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: f, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }, + if uav { D3D12_RESOURCE_STATE_UNORDERED_ACCESS } else { D3D12_RESOURCE_STATE_COPY_DEST }, + None, + &mut r, + ) + .unwrap(); + r.unwrap() + }; + let buffer = |bytes: u64, heap: D3D12_HEAP_TYPE| -> ID3D12Resource { + let mut r: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &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, + ..Default::default() + }, + if heap == D3D12_HEAP_TYPE_READBACK { D3D12_RESOURCE_STATE_COPY_DEST } else { D3D12_RESOURCE_STATE_GENERIC_READ }, + None, + &mut r, + ) + .unwrap(); + r.unwrap() + }; + let footprint = |r: &ID3D12Resource| -> (D3D12_PLACED_SUBRESOURCE_FOOTPRINT, u64) { + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + device.GetCopyableFootprints(&r.GetDesc(), 0, 1, 0, Some(&mut fp), None, None, Some(&mut total)); + (fp, total) + }; + let barrier = |r: &ID3D12Resource, before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(r), Subresource: 0, StateBefore: before, StateAfter: after }), + }, + ..Default::default() + }; + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut fence_value = 0u64; + let mut run = |list: &ID3D12GraphicsCommandList| { + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + fence_value += 1; + queue.Signal(&fence, fence_value).unwrap(); + let t0 = std::time::Instant::now(); + while fence.GetCompletedValue() < fence_value && t0.elapsed().as_secs() < 60 { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let removed = device.GetDeviceRemovedReason(); + assert!(removed.is_ok() && fence.GetCompletedValue() != u64::MAX, "device removed: {removed:?}"); + assert!(fence.GetCompletedValue() >= fence_value, "GPU work did not finish in 60 s"); + }; + let new_list = || -> (ID3D12CommandAllocator, ID3D12GraphicsCommandList) { + let a: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let l: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None).unwrap(); + (a, l) + }; + let (w, h) = (1280u32, 720u32); + let color = tex(w, h, DXGI_FORMAT_R16G16B16A16_FLOAT, false); + let depth = tex(w, h, DXGI_FORMAT_R32_FLOAT, false); + let motion = tex(w, h, DXGI_FORMAT_R16G16_FLOAT, false); + let output = tex(1920, 1080, DXGI_FORMAT_R16G16B16A16_FLOAT, true); + let uploads: Vec<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> = [&color, &depth, &motion] + .iter() + .map(|r| { + let (fp, total) = footprint(r); + (buffer(total, D3D12_HEAP_TYPE_UPLOAD), fp) + }) + .collect(); + let (ofp, ototal) = footprint(&output); + let rb = buffer(ototal, D3D12_HEAP_TYPE_READBACK); + // the scene: background 0.05 at depth 0.1, a 200x200 square of 1.0 at depth 0.9 (inverted + // depth: nearer), its left edge at `sq` (None: no square, the whole picture `flat`); + // `mv`: the square's motion vector in UV (previous position = current + mv) + // variants for finding what the history depends on: `XCL_PROBE_FSR_TEMPORAL_SCALE=` + // multiplies every colour, `XCL_PROBE_FSR_TEMPORAL_FLAT_DEPTH=1` gives the square the + // background's depth, `XCL_PROBE_FSR_TEMPORAL_JITTER=1` jitters as a title does (Halton 2/3) + let var = |name: &str| std::env::var(format!("XCL_PROBE_FSR_TEMPORAL_{name}")).ok(); + let scale: f32 = var("SCALE").and_then(|v| v.parse().ok()).unwrap_or(1.0); + let flat_depth = var("FLAT_DEPTH").is_some_and(|v| v == "1"); + let jitter = var("JITTER").is_some_and(|v| v == "1"); + // `XCL_PROBE_FSR_TEMPORAL_IMAGE=`: a still picture (raw RGB8, 1280x720) for eight + // frames instead of the square, each output written to `..._DUMP=` as a BMP; + // `..._RESET_ALL=1`: every frame with `reset` (no history) + let image: Option> = var("IMAGE").map(|f| std::fs::read(f).unwrap()); + let reset_all = var("RESET_ALL").is_some_and(|v| v == "1"); + let dump = var("DUMP"); + let (bg, lit, sq_y) = (0.05f32 * scale, 1.0f32 * scale, 260u32..460u32); + let upload = |sq: Option, flat: f32, mv: f32| { + let (prep_alloc, prep) = new_list(); + for (k, (r, (up, fp))) in [&color, &depth, &motion].iter().zip(&uploads).enumerate() { + let mut p: *mut std::ffi::c_void = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + for y in 0..fp.Footprint.Height { + let mut row: Vec = Vec::with_capacity(fp.Footprint.RowPitch as usize); + for x in 0..fp.Footprint.Width { + let on = sq.is_some_and(|s| (s..s + 200).contains(&x) && sq_y.contains(&y)); + match k { + 0 => { + let c = f16_bits(if sq.is_none() { flat * scale } else if on { lit } else { bg }); + let px = image.as_ref().map(|i| { + let at = 3 * (y * w + x) as usize; + // sRGB-ish to linear + [0, 1, 2].map(|c| f16_bits(scale * (i[at + c] as f32 / 255.0).powf(2.2))) + }); + let [r, g, b] = px.unwrap_or([c, c, c]); + for v in [r, g, b, f16_bits(1.0)] { + row.extend(v.to_le_bytes()); + } + } + 1 => row.extend((if on && !flat_depth { 0.9f32 } else { 0.1f32 }).to_le_bytes()), + _ => { + row.extend(f16_bits(if on { mv } else { 0.0 }).to_le_bytes()); + row.extend(0u16.to_le_bytes()); + } + } + } + std::ptr::copy_nonoverlapping(row.as_ptr(), (p as *mut u8).add(fp.Offset as usize + (y * fp.Footprint.RowPitch) as usize), row.len()); + } + up.Unmap(0, None); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(*r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *fp } }; + prep.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + } + // the state the dispatch names for its inputs (FFX COMPUTE_READ) + prep.ResourceBarrier(&[&color, &depth, &motion].map(|r| barrier(r, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE))); + prep.Close().unwrap(); + (prep_alloc, prep) + }; + let back_to_copy_dest = || { + let (a, l) = new_list(); + l.ResourceBarrier(&[&color, &depth, &motion].map(|r| barrier(r, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST))); + l.Close().unwrap(); + (a, l) + }; + let res = |r: &ID3D12Resource, fmt: u32, w: u32, h: u32, usage: u32, state: u32| -> [u32; 12] { + let p = r.as_raw() as usize; + [p as u32, (p >> 32) as u32, 2, fmt, w, h, 1, 1, 0, usage, state, 0] + }; + // mean red of output rectangles (x0, x1, y0, y1) + let read_regions = |regions: &[(u32, u32, u32, u32)]| -> Vec { + let half = |v: u16| -> f32 { + let (s, e, m) = ((v >> 15) as u32, ((v >> 10) & 0x1F) as i32, (v & 0x3FF) as f32); + let x = if e == 0 { m / 1024.0 * 2f32.powi(-14) } else if e == 31 { if m == 0.0 { f32::INFINITY } else { f32::NAN } } else { (1.0 + m / 1024.0) * 2f32.powi(e - 15) }; + if s == 1 { -x } else { x } + }; + let mut p: *mut std::ffi::c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let out = regions + .iter() + .map(|&(x0, x1, y0, y1)| { + let (mut sum, mut n) = (0f64, 0u32); + for y in (y0..y1).step_by(2) { + let row = (p as *const u8).add(ofp.Offset as usize + (y * ofp.Footprint.RowPitch) as usize) as *const u16; + for x in (x0..x1).step_by(2) { + let r = half(*row.add(4 * x as usize)); + assert!(r.is_finite(), "FSR4 output at ({x}, {y}) is {r}"); + sum += r as f64; + n += 1; + } + } + sum / n as f64 + }) + .collect(); + rb.Unmap(0, None); + out + }; + // output rectangles (1.5x the input): where the square was, where it went, background + let (old, new, back) = ((310u32, 590u32, 400u32, 680u32), (1210u32, 1490u32, 400u32, 680u32), (1650u32, 1850u32, 100u32, 300u32)); + // (square's left edge, flat colour, motion vector, reset, read back) + let frames: Vec<(Option, f32, f32, bool, bool)> = (0..6) + .map(|i| (Some(200), 0.0, 0.0, i == 0, i == 5)) + .chain([(Some(800), 0.0, -600.0 / 1280.0, false, true)]) + .chain((0..3).map(|_| (Some(800), 0.0, 0.0, false, true))) + .chain([(None, 0.5, 0.0, true, true)]) + .collect(); + // `XCL_PROBE_FSR_TEMPORAL_GONE=1`: from frame 6 the square is gone (no motion anywhere): the + // history there is only told apart by its colour + let frames: Vec<(Option, f32, f32, bool, bool)> = if var("GONE").is_some_and(|v| v == "1") { + frames.into_iter().enumerate().map(|(i, fr)| if (6..10).contains(&i) { (Some(4000), 0.0, 0.0, false, true) } else { fr }).collect() + } else { + frames + }; + let frames = if image.is_some() { (0..8).map(|i| (None, 0.0, 0.0, i == 0, true)).collect() } else { frames }; + let mut seen = Vec::new(); + // the upscaler's small buffers (its exposure among them): the V#s of at most 64 bytes in + // the descriptor tables its first frame names (`XCL_PROBE_FSR_TEMPORAL_SMALL=1` prints them) + let small_on = var("SMALL").is_some_and(|v| v == "1"); + let mut small: std::collections::BTreeSet<(usize, usize)> = std::collections::BTreeSet::new(); + for (f, &(sq, flat, mv, reset, read)) in frames.iter().enumerate() { + if f > 0 { + let (_a, l) = back_to_copy_dest(); + run(&l); + } + let (_pa, prep) = upload(sq, flat, mv); + run(&prep); + let (alloc, pc) = new_list(); + let console = console_list::create_with_allocator(pc.into_raw(), alloc.as_raw()); + let mut d = vec![0u32; 432 / 4]; + let put = |d: &mut Vec, at: usize, w: &[u32]| d[at / 4..at / 4 + w.len()].copy_from_slice(w); + put(&mut d, 0, &[0x0001_0001, 0, 0, 0]); + put(&mut d, 16, &[console as usize as u32, (console as usize >> 32) as u32]); + put(&mut d, 24, &res(&color, 4, w, h, 0, 4)); + put(&mut d, 72, &res(&depth, 28, w, h, 0, 4)); + put(&mut d, 120, &res(&motion, 18, w, h, 0, 4)); + put(&mut d, 312, &res(&output, 4, 1920, 1080, 2, 2)); + if jitter { + // Halton (2, 3) in pixels, -0.5..0.5, as the title's projection would be offset + let halton = |mut i: u32, b: u32| { + let (mut f, mut r) = (1f32, 0f32); + while i > 0 { + f /= b as f32; + r += f * (i % b) as f32; + i /= b; + } + r + }; + let i = f as u32 % 8 + 1; + put(&mut d, 360, &[(halton(i, 2) - 0.5).to_bits(), (halton(i, 3) - 0.5).to_bits()]); + } + put(&mut d, 368, &[(w as f32).to_bits(), (h as f32).to_bits()]); // motion vector scale + put(&mut d, 376, &[w, h, 1920, 1080]); + put(&mut d, 400, &[33.3f32.to_bits(), 1f32.to_bits()]); // frameTimeDelta, preExposure + put(&mut d, 408, &[(reset || reset_all) as u32]); + put(&mut d, 412, &[0.1f32.to_bits(), 1000f32.to_bits(), 1.0f32.to_bits(), 1f32.to_bits()]); + assert_eq!(dispatch(&mut ctx, d.as_ptr()), 0, "ffxDispatch of frame {f}"); + if small_on && f == 0 { + use xcl::hle::d3d12x::console_heap; + for &wd in &console_list::recorded_words(console) { + for k in 0..24 { + if let Some(v) = console_heap::words_at(wd.wrapping_add(32 * k)) { + if v[3] & 0xFFF == 0xFAC && v[3] >> 30 == 0 && v[2] != 0 && v[2] <= 64 { + small.insert((v[0] as usize | ((v[1] & 0xFFFF) as usize) << 32, v[2] as usize)); + } + } + } + } + } + let t = console_list::close(console).unwrap(); + // (`XCL_SKIP_CS`: the passes it names are left out on purpose) + let left_out_ok = std::env::var_os("XCL_SKIP_CS").is_some(); + assert!(t.unknown.is_none() && t.skipped == 0 && (t.skipped_dispatches == 0 || left_out_ok), "frame {f}: {t:?}"); + let pc_raw = console_list::pc_list(console).expect("the console list's PC list"); + run(ID3D12GraphicsCommandList::from_raw_borrowed(&pc_raw).unwrap()); + if read { + let (_ra, l) = new_list(); + l.ResourceBarrier(&[barrier(&output, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: ofp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&output), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + l.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + l.ResourceBarrier(&[barrier(&output, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + l.Close().unwrap(); + run(&l); + if let Some(dir) = &dump { + // the output as a BMP (sqrt for display) and how much it differs from its 4 + // neighbours on average (a dot or checker pattern raises it) + let mut p: *mut std::ffi::c_void = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let texel = |x: u32, y: u32, c: usize| -> f32 { + let v = *((p as *const u8).add(ofp.Offset as usize + (y * ofp.Footprint.RowPitch) as usize) as *const u16).add(4 * x as usize + c); + let (e, m) = (((v >> 10) & 0x1F) as i32, (v & 0x3FF) as f32); + if e == 0 { m / 1024.0 * 2f32.powi(-14) } else { (1.0 + m / 1024.0) * 2f32.powi(e - 15) } + }; + let (ow, oh) = (1920u32, 1080u32); + let mut bmp = Vec::with_capacity(54 + (ow * oh * 3) as usize); + bmp.extend(b"BM"); + for v in [54 + ow * oh * 3, 0, 54, 40, ow, oh] { + bmp.extend(v.to_le_bytes()); + } + bmp.extend(1u16.to_le_bytes()); + bmp.extend(24u16.to_le_bytes()); + for v in [0u32, ow * oh * 3, 2835, 2835, 0, 0] { + bmp.extend(v.to_le_bytes()); + } + let mut busy = 0f64; + for y in (0..oh).rev() { + for x in 0..ow { + for c in [2, 1, 0] { + bmp.push(((texel(x, y, c) / scale).clamp(0.0, 1.0).sqrt() * 255.0) as u8); + } + if (1..ow - 1).contains(&x) && (1..oh - 1).contains(&y) { + let n = (texel(x - 1, y, 1) + texel(x + 1, y, 1) + texel(x, y - 1, 1) + texel(x, y + 1, 1)) / 4.0; + busy += ((texel(x, y, 1) - n) / scale).abs() as f64; + } + } + } + rb.Unmap(0, None); + let file = std::path::Path::new(dir).join(format!("fsr4_frame{f}.bmp")); + std::fs::write(&file, bmp).unwrap(); + println!("FSR4 frame {f} written to {} (reset {}): mean |texel - its 4 neighbours| {:.5}", file.display(), reset || reset_all, busy / ((ow - 2) * (oh - 2)) as f64); + } + for &(at, n) in &small { + xcl::hle::d3d12x::sparse::readback_now(at, n); + let words: Vec = (0..n / 4).map(|k| { + let v = (at as *const u32).add(k).read_volatile(); + format!("{v:#x} ({})", f32::from_bits(v)) + }).collect(); + println!("FSR4 frame {f}: buffer {at:#x} ({n} bytes): {}", words.join(", ")); + } + let r = read_regions(&[old, new, back]); + println!("FSR4 frame {f} (square at {sq:?}, flat {flat}, mv {mv:.4}, reset {reset}): red where the square was {:.3}, where it went {:.3}, background {:.3}", r[0], r[1], r[2]); + seen.push((f, r)); + } + } + if image.is_some() { + return; + } + let at = |f: usize| seen.iter().find(|s| s.0 == f).unwrap().1.iter().map(|v| v / scale as f64).collect::>(); + assert!(at(5)[0] > 0.5 && at(5)[2] < 0.2, "a still square is upscaled where it is: {:?}", at(5)); + assert!(at(6)[0] < 0.25, "the place the square left shows the background in the frame it moved, not a ghost: {:?}", at(6)); + assert!(at(9)[0] < 0.25, "and three frames later: {:?}", at(9)); + assert!(at(10).iter().all(|v| (0.35..0.65).contains(v)), "a reset frame of flat grey is grey everywhere: {:?}", at(10)); + } +} + /// No GPU: every compute shader inside XboxBvhBuilder.dll (found by its DXBC header) against /// what XCL does with its root arguments. The shader's stage descriptor says how many user /// SGPRs it has; its RTS0 part gives the argument layout. Arguments must not be put into From 9f6e7d5e2fd89477be824592350b1723e424387e Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 19:13:21 +0100 Subject: [PATCH 132/175] FidelityFX: XCL_FFX_TRACE logs the title's upscales, XCL_FFX_RESET drops history On a Series S the retail title upscales with the console FSR4, and as XCL runs it the upscaler hardly rejects its history (the FSR4 temporal probe: a third of a bright square stays where it was, decaying ~10 % a frame). The frames show it as copies of walking people, see-through bodies with a dot pattern, and the last shot through camera cuts. The title imports ffxDispatch from amd_fidelityfx_loader_xbox.dll; like the Bink exports, the import is wrapped when a switch asks for it (resolver): - XCL_FFX_TRACE=1 (off) logs each upscale dispatch that has reset set, the first four and every 120th: reset, jitter, motion vector scale, sizes, frame time, camera, and each texture's object, format, size and state; every 120 upscales a line counts the resets. It tells whether the title resets the history at its camera cuts, and what it hands the upscaler. - XCL_FFX_RESET=1 (off) passes every upscale dispatch on with reset set (a copy of the description; the title's own stays as it was), so the upscaler keeps no history: no ghosts and no previous shot, at the cost of temporal antialiasing. To tell the history apart from the other inputs in a run, and as a stopgap. With neither switch the title's import is its own address, as before. No translated shader changes. --- crates/xcl/src/hle/ffx.rs | 198 +++++++++++++++++++++++++++++++++++++ crates/xcl/src/hle/mod.rs | 1 + crates/xcl/src/resolver.rs | 3 + 3 files changed, 202 insertions(+) create mode 100644 crates/xcl/src/hle/ffx.rs diff --git a/crates/xcl/src/hle/ffx.rs b/crates/xcl/src/hle/ffx.rs new file mode 100644 index 0000000000..b5b8b34eeb --- /dev/null +++ b/crates/xcl/src/hle/ffx.rs @@ -0,0 +1,198 @@ +//! The title's calls to its FidelityFX loader (`amd_fidelityfx_loader_xbox.dll`), seen on their +//! way to it. On a Series S the retail title upscales with the console's FSR4 (1280x720 → +//! 1920x1080, a history kept across frames); its people show copies along their path and the +//! last shot shows through a camera cut, as if the history were neither rejected nor reset. +//! +//! - `XCL_FFX_TRACE=1` (off): each upscale dispatch with `reset` set, the first four, and every +//! 120th is logged with what the upscaler is told (reset, jitter, motion vector scale, sizes, +//! frame time, camera) and its textures (object, format, size, state); every 120 dispatches a +//! line counts the resets since the last one. +//! - `XCL_FFX_RESET=1` (off): every upscale dispatch goes to the upscaler with `reset` set, so +//! it keeps no history (no ghosts, no previous shot; the picture is the current frame's, +//! upscaled, with its aliasing and dither). To tell the history apart from the other inputs. +//! +//! The dispatch description is `ffxDispatchDescUpscale` of the FidelityFX API (the console's has +//! the PC layout: HANDOFF "FSR4"), 432 bytes. + +#![allow(non_snake_case)] + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::OnceLock; + +/// `FFX_API_DISPATCH_DESC_TYPE_UPSCALE` +const DISPATCH_UPSCALE: u64 = 0x0001_0001; +/// bytes of `ffxDispatchDescUpscale` +const DESC_BYTES: usize = 432; +/// its `reset` (a bool) +const RESET_AT: usize = 408; +/// its textures (`FfxApiResource`, 48 bytes each) and their names +const RESOURCES_AT: usize = 24; +const RESOURCE_NAMES: [&str; 7] = ["colour", "depth", "motion", "exposure", "reactive", "t&c", "output"]; + +static REAL_DISPATCH: AtomicUsize = AtomicUsize::new(0); +static DISPATCHES: AtomicU64 = AtomicU64::new(0); +static RESETS: AtomicU64 = AtomicU64::new(0); + +/// "1" on, anything else (or nothing) off. +fn switch(var: &str) -> bool { + std::env::var(var).is_ok_and(|v| v.trim() == "1") +} + +fn trace_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch("XCL_FFX_TRACE")) +} + +fn reset_always() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch("XCL_FFX_RESET")) +} + +/// Lowercase DLL key of the FidelityFX loader. +pub fn is_loader_dll(key: &str) -> bool { + key == "amd_fidelityfx_loader_xbox.dll" +} + +/// `real_addr` of `function` of the loader, or the wrapper standing in for it when a switch of +/// this module is on. +pub fn wrap(function: &str, real_addr: usize) -> usize { + if real_addr == 0 || function != "ffxDispatch" || !(trace_on() || reset_always()) { + return real_addr; + } + REAL_DISPATCH.store(real_addr, Ordering::Release); + crate::xlog_info!( + "FidelityFX: the title's ffxDispatch is watched (XCL_FFX_TRACE={}, XCL_FFX_RESET={})", + trace_on() as u8, + reset_always() as u8 + ); + ffxDispatch_hook as usize +} + +fn word(d: &[u8], at: usize) -> u32 { + u32::from_le_bytes(d[at..at + 4].try_into().unwrap()) +} + +fn float(d: &[u8], at: usize) -> f32 { + f32::from_bits(word(d, at)) +} + +/// Whether `d` (a whole description) asks for a reset. +fn reset_of(d: &[u8]) -> bool { + d[RESET_AT] != 0 +} + +/// `d` with `reset` set (the rest as it was: the chain `next` still names the title's own). +fn with_reset(d: &[u8; DESC_BYTES]) -> [u8; DESC_BYTES] { + let mut c = *d; + c[RESET_AT] = 1; + c +} + +/// One line of what an upscale dispatch is told. +fn describe(d: &[u8]) -> String { + let mut s = format!( + "reset {}, jitter ({:.3}, {:.3}), motion vector scale ({}, {}), render {}x{} → {}x{}, frame time {:.1} ms, pre-exposure {}, camera near {} far {} fov {:.3}, flags {:#x}", + reset_of(d) as u8, + float(d, 360), + float(d, 364), + float(d, 368), + float(d, 372), + word(d, 376), + word(d, 380), + word(d, 384), + word(d, 388), + float(d, 400), + float(d, 404), + float(d, 412), + float(d, 416), + float(d, 420), + word(d, 428) + ); + for (k, name) in RESOURCE_NAMES.iter().enumerate() { + let at = RESOURCES_AT + 48 * k; + let obj = u64::from_le_bytes(d[at..at + 8].try_into().unwrap()); + if obj == 0 { + continue; + } + // description: type, format, width, height, depth, mips, flags, usage; then the state + s += &format!("; {name} {obj:#x} fmt {} {}x{} state {:#x}", word(d, at + 12), word(d, at + 16), word(d, at + 20), word(d, at + 40)); + } + s +} + +type Dispatch = unsafe extern "C" fn(*mut *mut c_void, *const u8) -> u32; + +/// `ffxDispatch(context, desc)` of the title. +unsafe extern "C" fn ffxDispatch_hook(context: *mut *mut c_void, desc: *const u8) -> u32 { + let real: Dispatch = std::mem::transmute(REAL_DISPATCH.load(Ordering::Acquire)); + if desc.is_null() || !crate::gpu::shader::readable(desc as usize, DESC_BYTES) || (desc as *const u64).read_unaligned() != DISPATCH_UPSCALE { + return real(context, desc); + } + let d: [u8; DESC_BYTES] = (desc as *const [u8; DESC_BYTES]).read_unaligned(); + let n = DISPATCHES.fetch_add(1, Ordering::Relaxed); + let reset = reset_of(&d); + if reset { + RESETS.fetch_add(1, Ordering::Relaxed); + } + if trace_on() { + if reset || n < 4 || n % 120 == 0 { + crate::xlog_info!("FidelityFX: upscale #{n} at present {}: {}", crate::hle::d3d12x::present::presents(), describe(&d)); + } + if n % 120 == 119 { + crate::xlog_info!("FidelityFX: {} upscales, {} of them with reset", n + 1, RESETS.load(Ordering::Relaxed)); + } + } + if reset_always() && !reset { + let c = with_reset(&d); + return real(context, c.as_ptr()); + } + real(context, desc) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(reset: bool) -> [u8; DESC_BYTES] { + let mut d = [0u8; DESC_BYTES]; + d[0..8].copy_from_slice(&DISPATCH_UPSCALE.to_le_bytes()); + d[8..16].copy_from_slice(&0x1234_5678u64.to_le_bytes()); + d[376..392].copy_from_slice(&[1280u32, 720, 1920, 1080].map(u32::to_le_bytes).concat()); + d[RESET_AT] = reset as u8; + d + } + + #[test] + fn a_forced_reset_sets_only_the_reset_byte() { + let d = desc(false); + assert!(!reset_of(&d)); + let c = with_reset(&d); + assert!(reset_of(&c)); + let changed: Vec = (0..DESC_BYTES).filter(|&i| c[i] != d[i]).collect(); + assert_eq!(changed, vec![RESET_AT], "the chain pointer and the rest stay the title's"); + } + + #[test] + fn the_description_line_names_sizes_and_reset() { + let mut d = desc(true); + // colour: an object, format 10, 1280x720, state 4 + d[24..32].copy_from_slice(&0xabcdu64.to_le_bytes()); + d[36..40].copy_from_slice(&10u32.to_le_bytes()); + d[40..48].copy_from_slice(&[1280u32, 720].map(u32::to_le_bytes).concat()); + d[64..68].copy_from_slice(&4u32.to_le_bytes()); + let s = describe(&d); + assert!(s.starts_with("reset 1,"), "{s}"); + assert!(s.contains("render 1280x720 → 1920x1080"), "{s}"); + assert!(s.contains("colour 0xabcd fmt 10 1280x720 state 0x4"), "{s}"); + assert!(!s.contains("depth"), "textures the title left out are not named: {s}"); + } + + #[test] + fn only_the_loaders_dispatch_is_wrapped() { + assert!(is_loader_dll("amd_fidelityfx_loader_xbox.dll")); + assert!(!is_loader_dll("amd_fidelityfx_upscaler_xbox.dll")); + // no switch in the test environment: the title's own address + assert_eq!(wrap("ffxCreateContext", 0x1000), 0x1000); + } +} diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index 1555d4d8d8..fdb7dc47d3 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -18,6 +18,7 @@ pub mod d3d12_layout; pub mod d3d12x; pub mod dstorage; pub mod dxcompiler; +pub mod ffx; pub mod gameinput; pub mod kbm; pub mod kernelx; diff --git a/crates/xcl/src/resolver.rs b/crates/xcl/src/resolver.rs index 7882042e3d..4a9bae6e20 100644 --- a/crates/xcl/src/resolver.rs +++ b/crates/xcl/src/resolver.rs @@ -318,6 +318,9 @@ pub fn resolve_import(dll: &str, what: &ImportName, importer: &str, delay: bool) if matches!(source, Source::GameDll(_)) && crate::hle::bink::is_bink_dll(&key) { addr = crate::hle::bink::wrap(&fname(what), addr); } + if matches!(source, Source::GameDll(_)) && crate::hle::ffx::is_loader_dll(&key) { + addr = crate::hle::ffx::wrap(&fname(what), addr); + } crate::xlog_debug!("import {importer}: {key}!{what} → {source:?}"); if let Some(f) = trace_filter() { if f.wants(&key, &fname(what), &source) { From 59e9e6e776d798495d13fadbb0eb03f8740a2227 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:43:57 +0100 Subject: [PATCH 133/175] D3D12.X: console lists log their record order and honour XCL_SKIP_CS XCL_CONSOLE_LISTS_LOG=order (off) logs each closed console list's records in their order after the counts line: dispatches with their program and group counts, the title's barriers (transitions with their states, UAV barriers), clears and their values. XCL_SKIP_CS leaves the programs it names out of console lists as it does on PC lists. With them the FSR4 probe showed that FSR4 dispatches its network passes back to back with no barrier between them (they wait for each other's flags), and that leaving its first network pass out removes the ghosts it leaves, which pointed at the passes' results rather than at their order. --- crates/xcl/src/hle/d3d12x/console_list.rs | 61 ++++++++++++++++++++++- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 30895a9b7e..bde79642fc 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -50,6 +50,25 @@ pub fn enabled() -> bool { *E.get_or_init(|| std::env::var_os("XCL_CONSOLE_LISTS").is_some()) } +/// `XCL_CONSOLE_LISTS_LOG=order` (off): each closed list's records in their order, one token +/// each (`order_token`), after the counts line. +fn order_log() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("XCL_CONSOLE_LISTS_LOG").is_ok_and(|v| v.trim() == "order")) +} + +/// One barrier of a #26 ResourceBarrier record (`D3D12_RESOURCE_BARRIER` as 4 u64) for the +/// order log: `T:>` a transition, `U` a UAV barrier (`U0`: on all), +/// `A` an aliasing barrier; `` the low 24 bits of the object's address. +fn order_token(c: &[u64]) -> String { + let res = c[1] & 0xFF_FFFF; + match c[0] as u32 { + 0 => format!("T{res:x}:{:x}>{:x}", c[2] >> 32, c[3] as u32), + 2 => format!("U{res:x}"), + _ => "A".into(), + } +} + // --------------------------------------------------------------------------------------- // root signature layouts (where each parameter sits in the root argument table) // --------------------------------------------------------------------------------------- @@ -917,6 +936,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // tracked PC descriptor heaps bound on `list` (for `heap_windows` + `SAMPLER_HEAP_DIRECTLY_INDEXED`) let mut bound_heaps: Vec = Vec::new(); let mut has_sampler_heap = false; + let mut order: Vec = Vec::new(); let chunks: Vec> = st.chunks.iter().map(|(c, used)| c[..*used].chunks(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()).collect(); 'chunks: for words in &chunks { let mut at = 0usize; @@ -980,6 +1000,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { for c in b.chunks_exact(4).filter(|c| c[0] as u32 == 0) { super::placements::note_use(c[1] as usize); } + if order_log() { + order.extend(b.chunks_exact(4).map(order_token)); + } list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, m)); } out.barriers += n as u32; @@ -1013,11 +1036,22 @@ pub unsafe fn close(obj: *mut c_void) -> Result { list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); } out.clears += 1; + if order_log() { + order.push(format!("C{:x}={:x}", q(2) & 0xFF_FFFF, values[0])); + } } else { out.skipped += 1; + if order_log() { + order.push(format!("C{:x}-skipped", q(2) & 0xFF_FFFF)); + } + } + } + _ => { + out.skipped += 1; + if order_log() { + order.push(format!("C{:x}-skipped", q(2) & 0xFF_FFFF)); } } - _ => out.skipped += 1, } at += 12; } else if w0 == COPY_TEXTURE_MARKER { @@ -1052,6 +1086,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) }, }]); out.barriers += 1; + if order_log() { + order.push("B".into()); + } at += 1; } else if w0 == DISPATCH || w0 & !4 == 0x4002_E800 { let (x, y, z) = (get(1), get(2), get(3)); @@ -1066,6 +1103,14 @@ pub unsafe fn close(obj: *mut c_void) -> Result { out.skipped_dispatches += 1; continue; } + // `XCL_SKIP_CS` (diagnostic): left out here as on PC lists + if super::real::skip_named_cs(real) { + out.skipped_dispatches += 1; + if order_log() { + order.push(format!("D{:016x}-left-out", super::real::pso_shaders(real).map_or(0, |s| s.0))); + } + continue; + } let user_sgprs = super::real::pso_user_sgprs(real); // (the list is submitted after this: its root views in a GPU view get their tiles there) super::bind::want_root_views(layout.as_deref(), &table, super::view_want::Path::RootView); @@ -1111,8 +1156,17 @@ pub unsafe fn close(obj: *mut c_void) -> Result { super::gpu_profile::end(list.as_raw(), t); ran?; out.dispatches += 1; + if order_log() { + let cs = super::real::pso_shaders(real).map_or(0, |s| s.0); + order.push(format!("D{cs:016x}[{x}x{y}x{z}]")); + } + } + _ => { + out.skipped_dispatches += 1; + if order_log() { + order.push("D-skipped".into()); + } } - _ => out.skipped_dispatches += 1, } } else if w0 & 0xC000_0000 == PARAM_BASE { let i = ((w0 >> 10) & 0x3F) as usize; @@ -1166,6 +1220,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { out.skipped ); } + if order_log() { + crate::xlog_info!("console list order: {}", order.join(" ")); + } if let Some((w, at)) = out.unknown { crate::xlog_warn!("console list: unknown record {w:#010x} (word {at}) – rest skipped"); } From 6bab0c531ce205cdf3d3c8a4ef334146efdd32ac Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:43:57 +0100 Subject: [PATCH 134/175] Recompiler: 8- and 4-bit dot products take OP_SEL halves of their sources FSR4 (amd_fidelityfx_upscaler_xbox.dll), with which the retail title upscales on a Series S, left a third of an object where it had moved away and faded it over many frames: copies along people's paths, people that look see-through, the last shot through a camera cut. The cause is its network passes' weights. The console's compiler folds constant weights into inline constants with VOP3P OP_SEL / OP_SEL_HI: 0x00400000 is an inline 64 with its 16-bit halves swapped, 0x000A000A an inline 10 in both halves, 0x00004000 an inline 2.0 (integer instructions take the f32 bits) swapped. 8 of FSR4's 29 programs do this, 8 to 16 v_dot4_i32_i8 each. Both translators took v_dot4 / v_dot8 sources whole, so those weights were 64, 10 and 0x40000000 instead. The 8- and 4-bit dot products now pick each source's halves the way the packed 16-bit ops do. A source with the default selection is emitted as before, so DXIL changes only for programs that use other selections (the FSR4 passes, and title shaders only if they do the same). Measured with the FSR4 history probe (XCL_PROBE_FSR_TEMPORAL, RX 9070 XT, warm caches), a 200 px square of 1.0 on 0.05 that moves 600 px. Where it was 0.336 in the frame it moved, then 0.305, 0.265, 0.246; now 0.050 (the background) from that frame on, and 0.005 (the background) in a ten times darker scene, with jitter and when the square just disappears. Ruled out before: barriers between the passes (a UAV barrier after every dispatch changed nothing), XCL's loop budget, the square's depth, jitter, the exposure and the passes' memory form. XCL_DOT_OP_SEL=0 takes the sources whole as before; the translated caches' identity tells the two apart. --- crates/xcl/src/gpu/dxil/lower_wide.rs | 34 ++++++++++++++++++++++---- crates/xcl/src/gpu/recomp/emit.rs | 35 +++++++++++++++++++++------ crates/xcl/src/gpu/recomp/pso.rs | 4 +++ crates/xcl/src/gpu/recomp/tests.rs | 18 ++++++++++++-- 4 files changed, 76 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index cbe3365238..c09e13ac72 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -59,6 +59,18 @@ impl Lw { let x = h(s, i, hi); s.sx16(x) }; + // a source of the 8- and 4-bit dot products with the halves OP_SEL / OP_SEL_HI pick + // (`recomp::emit` `valu_pk`: FSR4's weights are inline constants folded that way) + let dot_op_sel = vop3p && crate::gpu::recomp::emit::dot_op_sel_wanted(); + let pk = |s: &mut Self, i: usize| -> Value { + if !dot_op_sel || (sel >> i & 1 == 0 && sel_hi >> i & 1 == 1) { + return src(i); + } + let lo = h(s, i, false); + let hi = h(s, i, true); + let hi = s.shlc(hi, 16); + s.or(lo, hi) + }; let fr = |s: &mut Self, e: Value| { let e = if clamp { s.un(op::SATURATE, e) } else { e }; // The product of two binary16 operands fits exactly in binary32. @@ -102,10 +114,16 @@ impl Lw { let q = self.mul(a1, b1); Some(self.dot_sum(&[p, q], src(2), false, clamp)) } - "v_dot4_u32_u8" => Some(self.dot_n(src(0), src(1), src(2), 8, false, clamp)), - "v_dot4_i32_i8" => Some(self.dot_n(src(0), src(1), src(2), 8, true, clamp)), + "v_dot4_u32_u8" => { + let (a, b) = (pk(self, 0), pk(self, 1)); + Some(self.dot_n(a, b, src(2), 8, false, clamp)) + } + "v_dot4_i32_i8" => { + let (a, b) = (pk(self, 0), pk(self, 1)); + Some(self.dot_n(a, b, src(2), 8, true, clamp)) + } "v_dot8_u32_u4" if !clamp => { - let (a, b, c) = (src(0), src(1), src(2)); + let (a, b, c) = (pk(self, 0), pk(self, 1), src(2)); let a_lo = self.andc(a, 0x0F0F_0F0F); let b_lo = self.andc(b, 0x0F0F_0F0F); let a_hi = self.lshrc(a, 4); @@ -115,8 +133,14 @@ impl Lw { let t = self.s.dot4_add_u8_packed(c, a_lo, b_lo); Some(self.s.dot4_add_u8_packed(t, a_hi, b_hi)) } - "v_dot8_u32_u4" => Some(self.dot_n(src(0), src(1), src(2), 4, false, clamp)), - "v_dot8_i32_i4" => Some(self.dot_n(src(0), src(1), src(2), 4, true, clamp)), + "v_dot8_u32_u4" => { + let (a, b) = (pk(self, 0), pk(self, 1)); + Some(self.dot_n(a, b, src(2), 4, false, clamp)) + } + "v_dot8_i32_i4" => { + let (a, b) = (pk(self, 0), pk(self, 1)); + Some(self.dot_n(a, b, src(2), 4, true, clamp)) + } _ => None, }; if let Some(e) = dot { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 200cc90f9a..88f6efa475 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3414,6 +3414,17 @@ impl Em { } }; let si = |i: usize, hi: bool| format!("(((int)({} << 16)) >> 16)", h(i, hi)); + // a source of the 8- and 4-bit dot products: OP_SEL / OP_SEL_HI pick its 16-bit halves + // as for the packed 16-bit ops. The console's compiler folds constants that way: FSR4's + // network passes take weights 0x00400000 as an inline 64 with its halves swapped and + // 0x000A000A as an inline 10 in both halves (`dot_op_sel_wanted`) + let dot_op_sel = vop3p && dot_op_sel_wanted(); + let pk = |i: usize| -> String { + if !dot_op_sel || (sel >> i & 1 == 0 && sel_hi >> i & 1 == 1) { + return src(i); + } + format!("({} | ({} << 16))", h(i, false), h(i, true)) + }; let dyn_rm = self.dynamic_f16_rm; let fr = |e: String| { let s = if clamp { format!("saturate({e})") } else { e }; @@ -3462,16 +3473,16 @@ impl Em { h(1, true), src(2) )), - "v_dot4_u32_u8" if clamp => Some(format!("sat_u32((uint64_t)dot4_u8({}, {}, 0u) + (uint64_t){})", src(0), src(1), src(2))), - "v_dot4_i32_i8" if clamp => Some(format!("sat_i32((int64_t)(int)dot4_i8({}, {}, 0u) + (int64_t)(int){})", src(0), src(1), src(2))), - "v_dot8_u32_u4" if clamp => Some(format!("sat_u32((uint64_t)dot8_u4({}, {}, 0u) + (uint64_t){})", src(0), src(1), src(2))), - "v_dot8_i32_i4" if clamp => Some(format!("sat_i32((int64_t)(int)dot8_i4({}, {}, 0u) + (int64_t)(int){})", src(0), src(1), src(2))), + "v_dot4_u32_u8" if clamp => Some(format!("sat_u32((uint64_t)dot4_u8({}, {}, 0u) + (uint64_t){})", pk(0), pk(1), src(2))), + "v_dot4_i32_i8" if clamp => Some(format!("sat_i32((int64_t)(int)dot4_i8({}, {}, 0u) + (int64_t)(int){})", pk(0), pk(1), src(2))), + "v_dot8_u32_u4" if clamp => Some(format!("sat_u32((uint64_t)dot8_u4({}, {}, 0u) + (uint64_t){})", pk(0), pk(1), src(2))), + "v_dot8_i32_i4" if clamp => Some(format!("sat_i32((int64_t)(int)dot8_i4({}, {}, 0u) + (int64_t)(int){})", pk(0), pk(1), src(2))), "v_dot2_i32_i16" => Some(format!("(uint)({} * {} + {} * {} + (int){})", si(0, false), si(1, false), si(0, true), si(1, true), src(2))), "v_dot2_u32_u16" => Some(format!("({} * {} + {} * {} + {})", h(0, false), h(1, false), h(0, true), h(1, true), src(2))), - "v_dot4_u32_u8" => Some(format!("dot4add_u8packed({}, {}, {})", src(0), src(1), src(2))), - "v_dot4_i32_i8" => Some(format!("(uint)dot4add_i8packed({}, {}, (int){})", src(0), src(1), src(2))), - "v_dot8_u32_u4" => Some(format!("dot8_u4({}, {}, {})", src(0), src(1), src(2))), - "v_dot8_i32_i4" => Some(format!("dot8_i4({}, {}, {})", src(0), src(1), src(2))), + "v_dot4_u32_u8" => Some(format!("dot4add_u8packed({}, {}, {})", pk(0), pk(1), src(2))), + "v_dot4_i32_i8" => Some(format!("(uint)dot4add_i8packed({}, {}, (int){})", pk(0), pk(1), src(2))), + "v_dot8_u32_u4" => Some(format!("dot8_u4({}, {}, {})", pk(0), pk(1), src(2))), + "v_dot8_i32_i4" => Some(format!("dot8_i4({}, {}, {})", pk(0), pk(1), src(2))), _ => None, }; if let Some(e) = dot { @@ -6515,6 +6526,14 @@ pub(crate) fn lds_order_wanted() -> bool { lds_order_for(std::env::var("XCL_X_LDS_ORDER").ok().as_deref()) } +/// Whether the VOP3P 8- and 4-bit dot products take their sources' halves as OP_SEL / +/// OP_SEL_HI pick them (`valu_pk`); `XCL_DOT_OP_SEL=0` takes the sources whole, as before (the +/// translated cache's identity tells the two apart). +pub(crate) fn dot_op_sel_wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| lds_order_for(std::env::var("XCL_DOT_OP_SEL").ok().as_deref())) +} + /// `lds_order_wanted` for the value `env` of `XCL_X_LDS_ORDER`: on unless it is `0`. pub(super) fn lds_order_for(env: Option<&str>) -> bool { env.map_or(true, |v| v.trim() != "0") diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ed9358ee61..29b7dab425 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -336,6 +336,8 @@ mod translated { } else { id }; // `XCL_X_LDS_ORDER=0`: the split wave64 form without its LDS order, in both translators let id = if crate::gpu::recomp::emit::lds_order_wanted() { id } else { identity_for(&id.to_string(), "xcl-x-lds-order-0") }; + // `XCL_DOT_OP_SEL=0`: the 8- and 4-bit dot products without OP_SEL on their sources + let id = if crate::gpu::recomp::emit::dot_op_sel_wanted() { id } else { identity_for(&id.to_string(), "xcl-dot-op-sel-0") }; // `XCL_PS_QUAD_READS=0`: pixel shaders' quad-local lane reads through `rla`, in both translators let id = if crate::gpu::recomp::emit::ps_quad_reads_wanted() { id } else { identity_for(&id.to_string(), "xcl-ps-quad-reads-0") }; // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity @@ -591,6 +593,8 @@ mod translated { _ => id, }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); + // `XCL_DOT_OP_SEL=0` (as in `identity`) + let id = if crate::gpu::recomp::emit::dot_op_sel_wanted() { id } else { identity_for(&id.to_string(), "xcl-dot-op-sel-0") }; if crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) } else { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 735ac31b5c..12602f9145 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4017,6 +4017,15 @@ fn gpu_packed_math_dots_movrel() { ("V_DOT2_F32_F16", "ENC_VOP3P", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 5), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), ("V_DOT4_U32_U8", "ENC_VOP3P", &[("VDST", 6), ("SRC0", V + 7), ("SRC1", V + 8), ("SRC2", V + 9), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), ("V_DOT4_I32_I8", "ENC_VOP3P", &[("VDST", 11), ("SRC0", V + 7), ("SRC1", V + 12), ("SRC2", V + 9), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), + // OP_SEL / OP_SEL_HI pick the sources' halves, constants' too (FSR4's weights): + // an inline 64 with its halves swapped is 0x00400000 + ("V_DOT4_I32_I8", "ENC_VOP3P", &[("VDST", 14), ("SRC0", V + 7), ("SRC1", 192), ("SRC2", V + 9), ("OP_SEL", 2), ("OP_SEL_HI", 1), ("OP_SEL_HI_2", 1)], None), + // an inline 10 in both halves: 0x000A000A + ("V_DOT4_U32_U8", "ENC_VOP3P", &[("VDST", 15), ("SRC0", V + 7), ("SRC1", 138), ("SRC2", V + 9), ("OP_SEL_HI", 1), ("OP_SEL_HI_2", 1)], None), + // v12's halves swapped: 0x0708FF06 + ("V_DOT4_I32_I8", "ENC_VOP3P", &[("VDST", 16), ("SRC0", V + 7), ("SRC1", V + 12), ("SRC2", V + 9), ("OP_SEL", 2), ("OP_SEL_HI", 1), ("OP_SEL_HI_2", 1)], None), + // an inline 2.0 (integer instructions take the f32 bits) swapped: 0x00004000 + ("V_DOT4_U32_U8", "ENC_VOP3P", &[("VDST", 17), ("SRC0", V + 8), ("SRC1", 244), ("SRC2", V + 9), ("OP_SEL", 2), ("OP_SEL_HI", 1), ("OP_SEL_HI_2", 1)], None), ("V_PK_FMAC_F16", "ENC_VOP2", &[("VDST", 13), ("SRC0", V), ("VSRC1", 1)], None), ("S_MOV_B32", "ENC_SOP1", &[("SDST", 124), ("SSRC0", 131)], None), // m0 = 3 ("V_MOVRELS_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", V + 20)], None), // v10 = v23 @@ -4047,6 +4056,10 @@ fn gpu_packed_math_dots_movrel() { assert_eq!(f32::from_bits(v[4]), 12.375, "lane {l} v_dot2_f32_f16"); assert_eq!(v[6], 70 + l as u32, "lane {l} v_dot4_u32_u8"); assert_eq!(v[11] as i32, 4 * 8 + 3 * 7 + 2 * 6 - 1 + l as i32, "lane {l} v_dot4_i32_i8 (bytes from the low end)"); + assert_eq!(v[14], 2 * 64 + l as u32, "lane {l} v_dot4_i32_i8 op_sel:[0,1,0] op_sel_hi:[1,0,1] of an inline 64"); + assert_eq!(v[15], 4 * 10 + 2 * 10 + l as u32, "lane {l} v_dot4_u32_u8 op_sel_hi:[1,0,1] of an inline 10"); + assert_eq!(v[16] as i32, 4 * 6 - 3 + 2 * 8 + 7 + l as i32, "lane {l} v_dot4_i32_i8 op_sel:[0,1,0] op_sel_hi:[1,0,1] of a register"); + assert_eq!(v[17], 7 * 64 + l as u32, "lane {l} v_dot4_u32_u8 op_sel:[0,1,0] op_sel_hi:[1,0,1] of an inline 2.0"); assert_eq!(v[13], h(1.0 + 1.5 * 2.25) | h(2.0 - 2.0 * 0.5) << 16, "lane {l} v_pk_fmac_f16"); assert_eq!(v[10], 103, "lane {l} v_movrels_b32"); assert_eq!(v[40], l as u32, "lane {l} v_movreld_b32"); @@ -11775,9 +11788,10 @@ fn gpu_v_dot8_u32_u4_edge_cases() { (0xA5A5_5A5A, 0x5A5A_A5A5, 0x7FFF_FFFF), (0x0000_000F, 0x0000_000F, 0xFFFF_FF1F), ]; + // (OP_SEL_HI as a compiler sets it: each source's high half from its high half) let p = prog(&[ - ("V_DOT8_U32_U4", "ENC_VOP3P", &[("VDST", 3), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2)], None), - ("V_DOT8_U32_U4", "ENC_VOP3P", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("CLAMP", 1)], None), + ("V_DOT8_U32_U4", "ENC_VOP3P", &[("VDST", 3), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1)], None), + ("V_DOT8_U32_U4", "ENC_VOP3P", &[("VDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", V + 2), ("OP_SEL_HI", 3), ("OP_SEL_HI_2", 1), ("CLAMP", 1)], None), ]); let dot_u4 = |a: u32, b: u32, c: u32, clamp: bool| -> u32 { let mut sum = c as u64; From 23ee6c29025b3f6166f240620e27df6492127b64 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:37:27 +0100 Subject: [PATCH 135/175] D3D12.X: keep amd-dev's tested huge-pipeline defaults after the main merge The merge of main took main's side of real.rs and README for the huge-pipeline limits, which reverted amd-dev's 36e16cf4: XCL_HUGE_PSO_BYTES went back to 262144 and XCL_HUGE_PSO_CONCURRENCY to 1. amd-dev's defaults (65536, two at a time) are what the measured retail runs on an RX 9070 XT used: with 256 KB / one at a time the title's cold 90-260 KB compute programs (1-38 s and up to 5.5 GB each) ran four at a time below the threshold, and the loading waited one compile at a time above it. The switches still override both values. --- README.md | 4 ++-- crates/xcl/src/hle/d3d12x/real.rs | 13 ++++++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1f30b042d1..084dbd4565 100644 --- a/README.md +++ b/README.md @@ -373,9 +373,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. scratch buffer of at most `XCL_SPLIT_SCRATCH_MB` (default 256); the chains of one recording share it, and `XCL_SPLIT_SCRATCH_TOTAL_MB` (default 384) bounds what all recordings not yet reset hold together (past it a dispatch runs in smaller slabs). -- Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 262144) built on the +- Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 65536) built on the background `xcl-pso*` workers take turns in the driver's compiler: `XCL_HUGE_PSO_CONCURRENCY` - at once (default 1, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so + at once (default 2, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so they cannot occupy the ordinary huge-pipeline slot; one of them can therefore run next to the ordinary ones, and each gated compile starts only with 3 GB of commit free. Smaller pipelines and those a game thread waits for never wait. `xcl.log` shows each huge one as a numbered diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 279e2c0362..94acc4cb71 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6074,14 +6074,16 @@ unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { /// A compute pipeline with a console CS: `None` = not a console shader, `Some(Err)` = console /// shader the recompiler could not take, `Some(Ok(hr))` = translated pipeline created (or the /// driver's verdict on it). -/// DXIL size from which a pipeline's driver compile is "huge" (default 256 KB, `XCL_HUGE_PSO_BYTES`): +/// DXIL size from which a pipeline's driver compile is "huge" (default 64 KB, `XCL_HUGE_PSO_BYTES`; +/// 256 KB before: on an RX 9070 XT a retail title's cold 90 – 260 KB compute programs took 1 – 38 s +/// and up to 5.5 GB each, four at a time, and its run was ended for RAM): /// a compute one goes to the background, and any of them built on an `xcl-pso*` worker waits /// for one of the `XCL_HUGE_PSO_CONCURRENCY` slots. NVIDIA's compiler (nvgpucomp64) takes /// minutes and ~1 GB for a 1 – 2 MB program; ~20 of them at once (one per worker) were slower /// in total than 1 – 2 at a time. Small programs (ms each) never wait. pub(super) fn huge_pso_bytes() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); - *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_BYTES").ok().as_deref(), 256 << 10, 1, usize::MAX)) + *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_BYTES").ok().as_deref(), 64 << 10, 1, usize::MAX)) } /// `XCL_SKIP_CS_KB=`: the DXIL size in bytes from which a compute program gets no pipeline @@ -6106,13 +6108,14 @@ mod skip_cs_tests { } } -/// Huge driver compiles at once on the workers (default 1, `XCL_HUGE_PSO_CONCURRENCY`). +/// Huge driver compiles at once on the workers (default 2, `XCL_HUGE_PSO_CONCURRENCY`; 2 with the +/// 64 KB threshold is what the measured retail runs used: one at a time left its loading waiting). fn huge_pso_concurrency() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); - *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 1, 1, 64)) + *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 2, 1, 64)) } -/// Hard cap on concurrent huge (`>= 256 KB`) driver compiles even when wanted by a title bind +/// Hard cap on concurrent huge (`>= huge_pso_bytes()`) driver compiles even when wanted by a title bind /// (`XCL_HUGE_PSO_WANTED_CONCURRENCY`, default 2, always `>= huge_pso_concurrency()`). Prevents a /// burst of lazy compute binds from launching 10+ huge driver compiles simultaneously and spiking /// process commit into OOM, while still letting a wanted build overtake 1 background build. From 978b8139c4d8d69fe3205da206dd2b8ffcb467c7 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:01:59 +0100 Subject: [PATCH 136/175] D3D12.X: a PC Reset clears the recording's poison without predication too The main merge took amd-dev's early return in on_pc_reset (return unless predication was ever used) in front of main's body, which also clears the recording's poison and drops its native-pipeline generations. A list Reset in a run that never used predication kept both: a recording poisoned by an unavailable pipeline bind stayed poisoned after a successful Reset, so its later ExecuteCommandLists were refused, and the pinned generations were kept until the list went away. Only the null check returns early now; amd-dev's format-alias reset stays in front. Test: bind::tests::prepared_initial_pipeline_commits_only_after_create_or_reset_success (failed on 3277acaf with !recording_poisoned after the successful Reset). --- crates/xcl/src/hle/d3d12x/list_x.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index aac49d09fd..d86f2ebb75 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5360,7 +5360,7 @@ pub(super) unsafe fn before_close(list: *mut c_void) { pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); super::format_alias::list_reset(list as usize); - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + if list.is_null() { return; } let clear_predication = PREDICATION_USED.load(Ordering::Acquire); From ae15ff7f6e75736e894ac31492794455020c3253 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:01:59 +0100 Subject: [PATCH 137/175] Tests: read the symbol table of abbreviated DXIL bitcode dead_aggregate_does_not_retain_unused_global_while_live_global_init_is_kept (main, 09a65d63) parses the bitcode with a reader of unabbreviated records only and panicked with "unexpected abbrev 2": amd-dev's module writer (f089a9df) abbreviates constants and instructions with block-local DEFINE_ABBREVs. symtab_names now walks the block tree of the test reader (bitreader_tests::parse), which decodes those records; the assertions are unchanged. --- crates/xcl/src/gpu/dxil/module.rs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index c4677fd2f4..0176d61bad 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -1810,25 +1810,20 @@ mod tests { } fn symtab_names(bc: &[u8]) -> Vec { - assert!(bc.starts_with(&[b'B', b'C', 0xC0, 0xDE])); - let (mut bit, mut w, mut blk, mut stack, mut out) = (32usize, 2u32, 0u32, Vec::new(), Vec::new()); - let bits = |bit: &mut usize, n: u32| (0..n).fold(0u64, |v, k| { let b = (bc[*bit / 8] >> (*bit % 8)) & 1; *bit += 1; v | ((b as u64) << k) }); - let vbr = |bit: &mut usize, n: u32| { - let (mut o, mut s, hi) = (0u64, 0u32, 1u64 << (n - 1)); - loop { let c = bits(bit, n); o |= (c & (hi - 1)) << s; if c & hi == 0 { return o; } s += n - 1; } - }; - while bit + w as usize <= bc.len() * 8 { - match bits(&mut bit, w) { - 0 => { bit = (bit + 31) & !31; if let Some((pw, pb)) = stack.pop() { w = pw; blk = pb; } else { break; } } - 1 => { let (id, nw) = (vbr(&mut bit, 8) as u32, vbr(&mut bit, 4) as u32); bit = ((bit + 31) & !31) + 32; stack.push((w, blk)); w = nw; blk = id; } - 3 => { - let (code, n) = (vbr(&mut bit, 6) as u32, vbr(&mut bit, 6) as usize); - let ops: Vec = (0..n).map(|_| vbr(&mut bit, 6)).collect(); - if blk == BLOCK_VALUE_SYMTAB && code == VST_CODE_ENTRY { out.push(String::from_utf8(ops[1..].iter().map(|&x| x as u8).collect()).unwrap()); } + // the writer abbreviates constants and instructions (`define_abbrev`): the test reader + // decodes those records too + fn walk(block: &super::super::bitreader_tests::Block, out: &mut Vec) { + if block.id == BLOCK_VALUE_SYMTAB { + for ops in block.records_with(VST_CODE_ENTRY) { + out.push(String::from_utf8(ops[1..].iter().map(|&x| x as u8).collect()).unwrap()); } - other => panic!("unexpected abbrev {other}"), + } + for sub in &block.blocks { + walk(sub, out); } } + let mut out = Vec::new(); + walk(&super::super::bitreader_tests::parse(bc), &mut out); out } From 125e9531e4bc893a80741d22e3fba80b6ba9840d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:01:59 +0100 Subject: [PATCH 138/175] Shaders: give workers_for_commit the RAM available as an argument preparation_workers_take_the_commit_left_in_bytes (main) expects 12 workers for 16 logical processors and 64 GiB of commit, and got 4: the merge put amd-dev's RAM limit (2 GB a worker above 4 GB, read from ram_budget::available inside workers_for_commit) under main's bytes wrapper, so the result followed the test machine's free RAM. prepare_workers passes the RAM available in bytes, like the commit; the test gives plenty of it for main's cases and checks that 10 GiB of RAM limits 64 GiB of commit to three workers. --- crates/xcl/src/shaders.rs | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 282c7a20c9..a41e3ae00f 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -3426,13 +3426,14 @@ fn prepare_workers() -> usize { let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); // (`system_commit` is in bytes) let (used, limit) = crate::host::system_commit(); - workers_for_commit(cores, used, limit) + workers_for_commit(cores, used, limit, crate::ram_budget::available()) } -/// The workers for `cores` logical processors and the system's commit charge `used` and its -/// `limit`, both in bytes as `host::system_commit` gives them. -fn workers_for_commit(cores: usize, used: u64, limit: u64) -> usize { - workers_for(cores, limit.saturating_sub(used) >> 20, crate::ram_budget::available() >> 20) +/// The workers for `cores` logical processors, the system's commit charge `used` and its +/// `limit`, and `ram` available, all in bytes as `host::system_commit` and +/// `ram_budget::available` give them. +fn workers_for_commit(cores: usize, used: u64, limit: u64, ram: u64) -> usize { + workers_for(cores, limit.saturating_sub(used) >> 20, ram >> 20) } /// The workers for `cores` logical processors (threads, not cores), `free_mb` of commit left @@ -4689,14 +4690,17 @@ mod tests { } /// The commit figures come in bytes: 6 GiB left on 16 logical processors is room for two - /// workers, not twelve; a commit that is not known (0, 0) gives one. + /// workers, not twelve; a commit that is not known (0, 0) gives one. The RAM available is in + /// bytes too (with plenty of it the commit decides). #[test] fn preparation_workers_take_the_commit_left_in_bytes() { const GIB: u64 = 1 << 30; - assert_eq!(workers_for_commit(16, 10 * GIB, 16 * GIB), 2); - assert_eq!(workers_for_commit(16, 0, 64 * GIB), 12); - assert_eq!(workers_for_commit(16, 0, 0), 1); - assert_eq!(workers_for_commit(16, 20 * GIB, 16 * GIB), 1); + const RAM: u64 = 64 * GIB; + assert_eq!(workers_for_commit(16, 10 * GIB, 16 * GIB, RAM), 2); + assert_eq!(workers_for_commit(16, 0, 64 * GIB, RAM), 12); + assert_eq!(workers_for_commit(16, 0, 0, RAM), 1); + assert_eq!(workers_for_commit(16, 20 * GIB, 16 * GIB, RAM), 1); + assert_eq!(workers_for_commit(16, 0, 64 * GIB, 10 * GIB), 3); } /// A builder's progress line gives its record count; its other lines give none. From 4b927e1fefc1f62f23016e034387869414c1aeac Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:01:59 +0100 Subject: [PATCH 139/175] Tests: keep amd-dev's form of the PS mask SCC live-lane ballot test direct_ps_mask_and_scc_counts_live_lanes_only counted one live ballot where it wants two: the merge took main's version of the test, whose skipped instruction is an unexported s_add. This tree's optimizer (amd-dev's DXIL shrink series) merges that block into its join, and the two identical WaveActiveBallot(true) then share a block and are CSE'd. amd-dev's 942072bc adapted the test for exactly this: the skipped write is an exported v_mov and the select fold is off for the translation. That form is restored; the expected counts are unchanged. --- crates/xcl/src/gpu/dxil/lanes.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 9484d6940f..e9ace328f7 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -1323,17 +1323,22 @@ mod ps_ballot_tests { ins(if wave64 { "S_MOV_B64" } else { "S_MOV_B32" }, "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)]), ins(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)]), ins("V_CMP_LT_F32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 2)]), - // Split basic block so block-local CSE keeps `op`'s live-lane ballot distinct from entry EXEC. + // Split basic block so block-local CSE keeps `op`'s live-lane ballot distinct from entry EXEC + // (the skipped write is exported and the select fold is off: the optimizer merges an + // empty or folded block into its join) ins("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 10), ("SSRC1", 128)]), ins("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), - ins("S_ADD_U32", "ENC_SOP2", &[("SDST", 14), ("SSRC0", 14), ("SSRC1", 129)]), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 242)]), ins(op, "ENC_SOP2", &[("SDST", dst), ("SSRC0", s0), ("SSRC1", s1)]), ins("S_CSELECT_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 129), ("SSRC1", 128)]), ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 11)]), - ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 3), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1), ("VM", 1)]), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 3), ("VSRC2", 2), ("VSRC3", 5), ("DONE", 1), ("VM", 1)]), ins("S_ENDPGM", "ENC_SOPP", &[]), ].concat(); - let k = kernel::translate_pixel(&c, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi).expect("translate PS"); + crate::gpu::dxil::module::NO_SELECT_FOLD.with(|c| c.set(true)); + let k = kernel::translate_pixel(&c, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, &psi); + crate::gpu::dxil::module::NO_SELECT_FOLD.with(|c| c.set(false)); + let k = k.expect("translate PS"); validate::validate(&k.dxil).expect("validate PS"); let dis = validate::disassemble(&k.dxil).expect("disassemble PS"); assert_eq!(ballots(&dis), want, "wave64 {wave64} {op} dst={dst} s1={s1}:\n{dis}"); From 5b238c86cdfc9ccc54944a7bd106a3632d3506e0 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:01:59 +0100 Subject: [PATCH 140/175] Tests: let the PS NaN guard wrap RT0 in the 32-bit target pkrtz test ps_32bit_rt_export_patches_pkrtz_in_both_backends (main) looked for the exact text `xo.t0[0] = f16tof32(`. amd-dev's NaN guard (XCL_NAN_GUARD, on by default) clamps float colour exports in the HLSL path, so RT0's line is `xo.t0[0] = select(..., f16tof32((v0 & 0xFFFFu)))`: still the compressed export the test asks for. The check now looks for the f16 unpack of v0 on RT0's line. --- crates/xcl/src/gpu/dxil/core_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 006820e9db..0ae32a81bf 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -194,7 +194,9 @@ fn ps_32bit_rt_export_patches_pkrtz_in_both_backends() { assert!(unpatched.hlsl.contains("xo.t1[0] = (v6 & 0xFFFFu);"), "unpatched HLSL:\n{}", unpatched.hlsl); let patched = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: false, ps_rt32_mask: 1 << 1, ..Default::default() }).unwrap(); - assert!(patched.hlsl.contains("xo.t0[0] = f16tof32("), "RT0 must remain compressed:\n{}", patched.hlsl); + // (the PS NaN guard, `XCL_NAN_GUARD`, may wrap the unpacked value in a select) + let rt0 = patched.hlsl.lines().find(|l| l.contains("xo.t0[0] = ")).unwrap_or_default(); + assert!(rt0.contains("f16tof32((v0 & 0xFFFFu))"), "RT0 must remain compressed:\n{}", patched.hlsl); assert!(patched.hlsl.contains("xo.t1[0] = v6;"), "RT1 must export raw 32-bit v6:\n{}", patched.hlsl); assert!(!patched.hlsl.contains("v6 = f16_rtz("), "RT1 pkrtz must be NOPed so v6 keeps its bits:\n{}", patched.hlsl); From 9a3d4e0be21b0de35ef7159dda048acdbd7cb122 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:03:55 +0100 Subject: [PATCH 141/175] Recompiler: key XCL_DXIL_NO_OPT into the translated caches again amd-dev's 5c5ee83f (XCL_DXIL_NO_OPT's passes, sorted, in both translated identities beside XCL_DIRECT_FORMS_ONLY's list) was left out of the main merge, because main keeps runs with the switch out of the shader caches (cache_allowed). That covers console_to_dxil_in_with, but not the identities themselves, which the prepared warm library and the driver blob replay key on (translation_cache_identity). Ported onto main's identity_from_source and direct_output_identity, with its test. DXIL: unchanged. Identity: changes only when XCL_DXIL_NO_OPT is set. --- crates/xcl/src/gpu/recomp/pso.rs | 35 +++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 36975ce016..ec224979c3 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -403,9 +403,10 @@ mod translated { let id = if Backend::current() != Backend::Hlsl && crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; - // `XCL_DIRECT_FORMS_ONLY`: the newer forms for these programs only - let id = match super::forms_only_tag() { - Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag), + // `XCL_DIRECT_FORMS_ONLY`: the newer forms for these programs only; `XCL_DXIL_NO_OPT`: + // the passes left out + let id = match super::forms_only_tag().into_iter().chain(super::no_opt_tag()).collect::>() { + tags if Backend::current() != Backend::Hlsl && !tags.is_empty() => identity_for(&id.to_string(), &tags.join(";")), _ => id, }; // `XCL_NAN_GUARD=0`: disabling PS float NaN/Inf sanitization changes pixel DXIL @@ -730,9 +731,9 @@ mod translated { let id = if crate::gpu::dxil::kernel::declared_lds_enabled() { identity_for(&id.to_string(), "xcl-declared-lds") } else { id }; let id = if crate::gpu::dxil::kernel::coherent_per_access() { identity_for(&id.to_string(), "xcl-coherent-per-access") } else { id }; let id = if crate::gpu::dxil::kernel::one_wave_group_ids() { identity_for(&id.to_string(), "xcl-one-wave-group-ids") } else { id }; - let id = match super::forms_only_tag() { - Some(tag) => identity_for(&id.to_string(), &tag), - None => id, + let id = match super::forms_only_tag().into_iter().chain(super::no_opt_tag()).collect::>() { + tags if !tags.is_empty() => identity_for(&id.to_string(), &tags.join(";")), + _ => id, }; let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}")); // `XCL_DOT_OP_SEL=0` (as in `identity`) @@ -887,6 +888,17 @@ fn forms_only_tag() -> Option { forms_only().map(|set| format!("xcl-direct-forms-only-{}", set.iter().map(|h| format!("{h:016x}")).collect::>().join(","))) } +/// The translated caches' tag of `XCL_DXIL_NO_OPT` (the direct translator's passes left out; +/// None: unset or empty): the DXIL is another one without them. +fn no_opt_tag() -> Option { + no_opt_tag_of(std::env::var("XCL_DXIL_NO_OPT").ok().as_deref()) +} + +fn no_opt_tag_of(v: Option<&str>) -> Option { + let passes: std::collections::BTreeSet<&str> = v?.split(',').map(str::trim).filter(|p| !p.is_empty()).collect(); + (!passes.is_empty()).then(|| format!("xcl-dxil-no-opt-{}", passes.into_iter().collect::>().join(","))) +} + fn compile_console_shader_formed(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, rt32_mask: u8) -> Result<(Compiled, bool), String> { // `XCL_DEBUG_CS_SUB` names this compute shader: the HLSL path, whatever its size let cs_subs = cs_subs(blob, stage); @@ -2081,7 +2093,7 @@ mod slab_tests { #[cfg(test)] mod forms_only_tests { - use super::forms_only_of; + use super::{forms_only_of, no_opt_tag_of}; /// `XCL_DIRECT_FORMS_ONLY`: hex records with or without `0x`, spaces allowed; `none` (or no /// valid record) names none of them; `all` leaves every program its forms; unset names the @@ -2094,6 +2106,15 @@ mod forms_only_tests { assert_eq!(set.into_iter().collect::>(), vec![0x3cd8c0e62e7072c8, 0xa3c0b8a98beee431]); assert!(forms_only_of(Some("none")).unwrap().is_empty()); } + + /// `XCL_DXIL_NO_OPT` keys the translated caches by the passes it names, in any order. + #[test] + fn the_passes_left_out_are_a_cache_tag() { + assert_eq!(no_opt_tag_of(None), None); + assert_eq!(no_opt_tag_of(Some(" , ")), None); + assert_eq!(no_opt_tag_of(Some("select")).as_deref(), Some("xcl-dxil-no-opt-select")); + assert_eq!(no_opt_tag_of(Some("select, dce")), no_opt_tag_of(Some("dce,select"))); + } } #[cfg(test)] From 8ebae57570ab5a7b08d8025b950ddf25cd202fea Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:06:38 +0100 Subject: [PATCH 142/175] Recompiler: a reduction's row mirror may set BOUND_CTRL gpu_ps_wave32_reductions_count_live_lanes_only (amd-dev 8c79f57e) had 105 of 1024 pixels wrong in the HLSL form, all along the shared diagonal: the merge replaced amd-dev's wave32_reductions with main's graphics_reductions, which refuses a row mirror with BOUND_CTRL or FI set, and the test's program, the form of a retail clustered-lighting shader's light-list reduction, sets BOUND_CTRL. Unrecognised, the DPP and permlane steps ran one by one and passed helper and unlaunched lanes' zeros into the min (the small dark triangles along the tiles' diagonals, visual defect 9). Both translators take this recogniser, so the direct form had the same fault. Neither bit changes a row mirror there: it reads inside its own row, and every lane is on between the s_or_saveexec -1 and the readlane. amd-dev did not check them; the other checks of main stay. Test: gpu_ps_wave32_reductions_count_live_lanes_only (HLSL and direct DXIL, RX 9070 XT), graphics_whole_reductions_use_wave_ops, gpu_wave64_ps_whole_wave_reductions. --- crates/xcl/src/gpu/recomp/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 6b9ca01d80..d918d604bb 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1497,14 +1497,15 @@ pub(crate) fn graphics_reductions(insts: &[Decoded], leaders: &std::collections: && f(cross, "SRC1") == Some(128) && f(cross, "SRC2") == Some(128); let last_exact = crossed && same(last, rdna2::Variant::Plain) && lr.len() == 2 && lr.contains(&v) && lr.contains(&cw[0]); + // (BOUND_CTRL and FI of the mirror change nothing: a row mirror reads inside its row, and + // every lane is on in the section; `tests::wave32_reductions_ps`, the form of a retail + // clustered-lighting shader, sets BOUND_CTRL) if !dpp8 || !same(mirror, rdna2::Variant::Dpp16) || !reads_only_v(mirror) || ext(mirror, "DPP_CTRL") != Some(0x140) || ext(mirror, "ROW_MASK") != Some(0xf) || ext(mirror, "BANK_MASK") != Some(0xf) - || ext(mirror, "BOUND_CTRL").unwrap_or(0) != 0 - || ext(mirror, "FI").unwrap_or(0) != 0 || !crossed || !last_exact { From 8f01e42aeb805a014848ab9a167eee6b3135fe94 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:06:38 +0100 Subject: [PATCH 143/175] Tests: the pipeline library's own tests turn it on on AMD too builder_deduplicates_names_and_atomically_replaces_output and cold_publish_makes_an_unchanged_corpus_reusable (main) failed on the RX 9070 XT at `assert!(begin(..))`, and the round-trip tests with a PoisonError of the lock that panic left: the merge put amd-dev's default (f33df5a7: the pipeline library off on AMD, XCL_PSO_LIBRARY=1 forces it on) in front of main's library, and Pipelines::new records the vendor, so begin() and activate() did nothing there. The library's tests, while they hold BUILD_TEST, now turn it on as XCL_PSO_LIBRARY=1 would (force_on_for_test); the vendor default and its test (vendor_default_disables_pipeline_library_on_amd_unless_overridden) are unchanged. Main's BUILD_TEST (2c003dd6) already keeps one panic from poisoning the others. --- crates/xcl/src/shaders/pipeline_library.rs | 22 ++++++++++++++++++++++ crates/xcl/src/shaders/warm_library.rs | 1 + 2 files changed, 23 insertions(+) diff --git a/crates/xcl/src/shaders/pipeline_library.rs b/crates/xcl/src/shaders/pipeline_library.rs index 5170fe3f2d..a279100376 100644 --- a/crates/xcl/src/shaders/pipeline_library.rs +++ b/crates/xcl/src/shaders/pipeline_library.rs @@ -61,6 +61,10 @@ pub(crate) fn note_vendor(vendor: u32) { /// Whether the native pipeline library is used (`XCL_PSO_LIBRARY=0` disables, `XCL_PSO_LIBRARY=1` /// forces on; defaults off on AMD `0x1002` and on for other vendors). pub(crate) fn enabled() -> bool { + #[cfg(test)] + if FORCED_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { + return true; + } enabled_for(env_override(), AMD_VENDOR.load(std::sync::atomic::Ordering::Relaxed)) } @@ -194,6 +198,21 @@ pub(crate) fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Res #[cfg(test)] pub(crate) static BUILD_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(()); +#[cfg(test)] +static FORCED_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// The tests of the library itself, holding `BUILD_TEST`: the library is on (as with +/// `XCL_PSO_LIBRARY=1`) until this is dropped, also on AMD, where it is off by default. +#[cfg(test)] +pub(crate) fn force_on_for_test() -> impl Drop { + struct On; + impl Drop for On { + fn drop(&mut self) { FORCED_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); } + } + FORCED_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + On +} + pub(crate) struct NativeLibrary { library: ID3D12PipelineLibrary1, _serialized: std::sync::Arc<[u8]>, @@ -430,6 +449,7 @@ void main() {{ output.Store(0, {n}); }} #[test] fn builder_deduplicates_names_and_atomically_replaces_output() { let _serial = BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let _on = super::force_on_for_test(); let Some((pipelines, dxil, root)) = fixture() else { return }; let desc = compute_desc(&dxil, &root); let pso = unsafe { pipelines.dev.CreateComputePipelineState::(&desc) } @@ -472,6 +492,7 @@ void main() {{ output.Store(0, {n}); }} #[test] fn graphics_pipeline_round_trips_through_serialized_library() { let _serial = BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let _on = super::force_on_for_test(); let Some((pipelines, _, _)) = fixture() else { return }; let source = r#" #define RS "" @@ -536,6 +557,7 @@ struct V { float4 p : SV_Position; }; #[test] fn mesh_pipeline_round_trips_through_serialized_library() { let _serial = BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let _on = super::force_on_for_test(); let Some((pipelines, _, _)) = fixture() else { return }; let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); if unsafe { diff --git a/crates/xcl/src/shaders/warm_library.rs b/crates/xcl/src/shaders/warm_library.rs index 657ace839b..e03d7733b0 100644 --- a/crates/xcl/src/shaders/warm_library.rs +++ b/crates/xcl/src/shaders/warm_library.rs @@ -454,6 +454,7 @@ mod tests { }; let pso = unsafe { pipelines.dev.CreateComputePipelineState::(&desc) }.unwrap(); let _serial = super::super::pipeline_library::BUILD_TEST.lock().unwrap_or_else(|e| e.into_inner()); + let _on = super::super::pipeline_library::force_on_for_test(); super::super::pipeline_library::abort(); assert!(super::super::pipeline_library::begin(&pipelines.dev, None).unwrap()); super::super::pipeline_library::store("fixture.pso".into(), &pso).unwrap(); From eec5cbc1ea388f0a7106072e1c15b99df07c1ccd Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:06:38 +0100 Subject: [PATCH 144/175] Shaders: key amd-dev's translation switches into the warm settings Main's stable identities (e62a02ff) hash an allowlist of pipeline switches instead of every XCL_ variable but a denylist, as amd-dev's warm_settings did. amd-dev's own translation switches are not on that list: XCL_DOT_OP_SEL, XCL_DIRECT_FORMS_ONLY, XCL_DIRECT_COMPACT_MIN, XCL_DECLARED_LDS, XCL_COHERENT_PER_ACCESS, XCL_ONE_WAVE_GROUP_IDS, XCL_NAN_GUARD, XCL_PS_QUAD_READS and XCL_RT_GATE. They are in the translated identity too, but with XCL_TRANSLATED_CACHE=0 that is 0, and XCL_NAN_GUARD is tagged there for the direct backends only although the HLSL path takes it as well. They now key the prepared library and the driver-blob replay as main's own translation switches do. --- crates/xcl/src/shaders.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index a41e3ae00f..3124eca393 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -38,7 +38,11 @@ fn semantic_pipeline_setting(name: &str) -> bool { "XCL_RECOMP_DXIL" | "XCL_RECOMP_NO_STRUCTURED" | "XCL_SAFE_BARRIER" | "XCL_SPLIT_WAVE64" | "XCL_WAVE64_SPIN" | "XCL_WT" | "XCL_X64_ALL_MASKS" | "XCL_XC" | "XCL_XS" | "XCL_XW" | "XCL_X_FAIL" | "XCL_X_LDS_ORDER" | - "XCL_X_LDS_TOP" | "XCL_X_SLOT" | "XCL_X_SPIN" | "XCL_X_THREADS" | "XCL_X_WAVES") + "XCL_X_LDS_TOP" | "XCL_X_SLOT" | "XCL_X_SPIN" | "XCL_X_THREADS" | "XCL_X_WAVES" | + // amd-dev's translation switches (also in `pso::translation_cache_identity`) + "XCL_COHERENT_PER_ACCESS" | "XCL_DECLARED_LDS" | "XCL_DIRECT_COMPACT_MIN" | + "XCL_DIRECT_FORMS_ONLY" | "XCL_DOT_OP_SEL" | "XCL_NAN_GUARD" | "XCL_ONE_WAVE_GROUP_IDS" | + "XCL_PS_QUAD_READS" | "XCL_RT_GATE") } fn warm_settings(vars: impl IntoIterator) -> u64 { @@ -136,6 +140,9 @@ fn warm_settings_ignore_waits_watchdogs_and_traces_but_keep_pipeline_switches() all.extend(left_out); assert_eq!(plain, key(&all)); assert_ne!(plain, key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_PAGE_ALIAS", "1")]), "page alias stays in the key"); + for knob in [("XCL_DOT_OP_SEL", "0"), ("XCL_DIRECT_FORMS_ONLY", "all"), ("XCL_DIRECT_COMPACT_MIN", "0"), ("XCL_PS_QUAD_READS", "0")] { + assert_ne!(plain, key(&[("XCL_DIRECT_DXIL", "1"), knob]), "{} stays in the key", knob.0); + } assert_eq!(plain, key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_TRACEX", "1")]), "unknown diagnostics stay cache-neutral until reviewed"); } From b9ffe63168ae6af5eabccc2b6ef3d9c73c6cfd25 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:08:27 +0100 Subject: [PATCH 145/175] D3D12.X: a released reserved texture is parked for reuse again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The main merge kept both sides' call of title_textures::forget in the resource Release hook: amd-dev's (its result unused there after the merge) and main's `let final_state = …` right after it. The first one removes the texture and its last state; the second found nothing, so final_state was always None and park_recyclable was never called: no reserved sampled texture reached the recycle pool, and each placement made a new reserved resource. The duplicate call is gone. Test: vram::tests::reserved_resource_with_private_data_is_excluded_from_recycle ("C did not reach the recycle queue" on 3277acaf; passes on RX 9070 XT). --- crates/xcl/src/hle/d3d12x/real.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 4e784a0f7d..b196593733 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2724,7 +2724,6 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::barrier_groups::forget(this as usize); super::format_alias::forget(this as usize); super::ambient::forget_resource(this as usize); - super::title_textures::forget(this as usize); let final_state = super::title_textures::forget(this as usize); super::lut3d::forget(this as usize); if !had_private_data { From 0481ad6c9cd1f2d03d83033f81c536b026d11488 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:01:53 +0100 Subject: [PATCH 146/175] Shaders: prepare split programs without whole forms the title cannot take Launch preparation's compute workers (the mandatory path, prepare_compiled_compute) built every split compute program's whole form twice besides its pieces: under the ABI root and under the direct chain root. The title takes the ABI-root whole form only from a kept driver blob or the pipeline library (ComputeBuild::CachedWhole), and builds the chain-root one only at an indirect dispatch (whole_ready). With both kept forms off (AMD's default: XCL_PSO_DISK_CACHE and XCL_PSO_LIBRARY off, the driver keeps its own cache) neither is used, yet their cold driver compiles are the largest of the pass. amd-dev's preparation built only the pieces. Now, without kept whole forms, a split program gets its pieces, and its whole forms only when an earlier run dispatched it indirectly, as make_selected (offline pso-precompile) already does. With either kept form on, the builds are unchanged. Measured offline on the PR tree (RX 9070 XT, retail pack, worker path, XCL_PIPELINE_THREADS=1, window counts no run had used, so cold): - 001714bfebb89dc6 (whole 421 KB, 7 pieces): 60 s for 9 pipelines before, 8 s for the 7 pieces alone; the two whole forms alone 54 s. - six split programs (whole 91 - 486 KB): 27 pieces in 33 s; their 12 whole forms another 122 s (XCL_PSO_LIBRARY=1 restores the old set). - warm (the driver's cache) 2 s either way. The retail title's used compute set has 49 split programs with 6.9 MB of whole forms: about 500 s of cold driver compiles, now left out. No DXIL changes: only which pipelines preparation asks the driver for. --- crates/xcl/src/shaders.rs | 66 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 3124eca393..52fbb2c4e4 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1816,6 +1816,41 @@ fn split_whole_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] { } } +/// A pipeline of a split program that native preparation builds: its pieces, or its whole form, +/// under a root signature. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SplitBuild { + Pieces(PipelineRoot), + Whole(PipelineRoot), +} + +/// What `prepare_compiled_compute` builds of a split program, in order. The title runs its pieces +/// (`dispatch_chain::build`); it takes the whole form under the ABI root only from a kept driver +/// blob or the pipeline library (`ComputeBuild::CachedWhole`), and builds the one under the chain +/// root only at an indirect dispatch (`dispatch_chain::whole_ready`). So without that keeping +/// (`whole_kept` false: AMD by default) the whole forms are built only for the programs earlier +/// runs dispatched indirectly, as `make_selected` builds them: a retail title's 49 split programs +/// had whole forms of 64 – 486 KB of DXIL, whose cold driver compiles took 53 of the 60 s one +/// such program cost (RX 9070 XT), for pipelines the title never asked the driver for. +fn split_builds(prewarm_indirect: bool, whole_kept: bool) -> Vec { + let mut builds = Vec::new(); + if whole_kept { builds.push(SplitBuild::Whole(PipelineRoot::Whole)); } + for &root in split_piece_roots(prewarm_indirect) { + builds.push(SplitBuild::Pieces(root)); + if whole_kept || split_whole_roots(prewarm_indirect).contains(&root) { + builds.push(SplitBuild::Whole(root)); + } + } + builds +} + +/// Whether the title can take a split program's whole form without the driver compiling it: from +/// XCL's driver-blob files or its pipeline library (`XCL_PSO_DISK_CACHE`, `XCL_PSO_LIBRARY`; both +/// off on AMD by default, where the driver keeps its own cache). +fn whole_form_kept() -> bool { + crate::hle::d3d12x::real::driver_cache::enabled() || pipeline_library::enabled() +} + fn required_piece_workers(piece_count: usize, root: PipelineRoot) -> usize { if root == PipelineRoot::IndirectChain { piece_count.min(2) } else { 1 } } @@ -1924,6 +1959,25 @@ mod inflight_build_tests { ); } + /// Without kept whole forms (AMD by default), native preparation builds a split program's + /// pieces and no whole form the title would not use: the whole ones only for a program earlier + /// runs dispatched indirectly, as `make_selected` does. With them it builds all, as before. + #[test] + fn split_programs_get_whole_forms_only_where_the_title_takes_them() { + use super::SplitBuild::{Pieces, Whole}; + use PipelineRoot::{DirectChain, IndirectChain}; + assert_eq!(super::split_builds(false, false), [Pieces(DirectChain)]); + assert_eq!( + super::split_builds(true, false), + [Pieces(DirectChain), Whole(DirectChain), Pieces(IndirectChain), Whole(IndirectChain)], + ); + assert_eq!(super::split_builds(false, true), [Whole(PipelineRoot::Whole), Pieces(DirectChain), Whole(DirectChain)]); + assert_eq!( + super::split_builds(true, true), + [Whole(PipelineRoot::Whole), Pieces(DirectChain), Whole(DirectChain), Pieces(IndirectChain), Whole(IndirectChain)], + ); + } + #[test] fn required_indirect_piece_preparation_is_capped_at_two_workers() { assert_eq!(super::required_piece_workers(0, PipelineRoot::IndirectChain), 0); @@ -2550,11 +2604,13 @@ impl Pipelines { let make = |dxil: &[u8], root| { self.make_required(dxil, &program.samplers, root, None, true) }; - make(&program.dxil, PipelineRoot::Whole)?; - if let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) { - for &root in split_piece_roots(prewarm_indirect) { - self.make_chain_pieces_required(&chain.pieces, &program.samplers, root)?; - make(&program.dxil, root)?; + let Some(chain) = program.dispatch_chain.as_deref().filter(|c| c.pieces.len() >= 2) else { + return make(&program.dxil, PipelineRoot::Whole); + }; + for build in split_builds(prewarm_indirect, whole_form_kept()) { + match build { + SplitBuild::Pieces(root) => self.make_chain_pieces_required(&chain.pieces, &program.samplers, root)?, + SplitBuild::Whole(root) => make(&program.dxil, root)?, } } Ok(()) From c427af0fb75b31135a2901438093c5ed78da4c8f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:06:17 +0100 Subject: [PATCH 147/175] Shaders: compute preparation workers get the window count without HEAP_FLAT pipeline_worker_command cleared only HEAP_WINDOWS from the title's windows, so with XCL_HEAP_FLAT=1 (and heap windows) a compute worker was started with `--windows 528` (16 | HEAP_FLAT). The worker's argument check (valid_window_count) refuses that count, every worker exits with 2, and pipelines_in_workers fails the launch's preparation. The graphics workers and amd-dev's compute workers already clear both flags; the worker puts them back as the title takes them (runtime_windows). Test: pipeline_worker_command_passes_the_window_count_without_heap_flags (fails before: "528" for "16"). --- crates/xcl/src/shaders.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 52fbb2c4e4..be3304d8d0 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -3543,7 +3543,8 @@ fn pipelines_in_workers(pack: &Path, windows: u32, workers: usize, records: usiz /// that profile's used-pipeline list (`used_pipelines_name`). fn pipeline_worker_command(me: &Path, pack: &Path, windows: u32, used_only: bool, slice: &str, series_s: bool) -> std::process::Command { let mut c = worker_command(me); - c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !recomp::HEAP_WINDOWS).to_string()); + // (the count alone: the worker adds the heap flags as the title takes them, `runtime_windows`) + c.arg("shaders").arg(pack).args(["--precompile", "--only", "cs", "--pipelines", "--windows"]).arg((windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT)).to_string()); if used_only { c.arg("--used-only"); } c.env("XCL_PRECOMPILE_SLICE", slice); c.env("XCL_DEVICE_TYPE", if series_s { "lockhart" } else { "anaconda" }); @@ -4960,6 +4961,18 @@ mod tests { assert_eq!(dev_env(false).as_deref(), Some("anaconda")); } + /// A compute worker gets the title's window count alone: with `XCL_HEAP_FLAT=1` the flat bit + /// made `--windows 528`, which the worker refused (`valid_window_count`), and every worker + /// failed the launch's preparation. + #[test] + fn pipeline_worker_command_passes_the_window_count_without_heap_flags() { + let windows = 16 | crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT; + let cmd = super::pipeline_worker_command(Path::new("xcl.exe"), Path::new("shaders.rpf"), windows, false, "0/2", true); + let args: Vec<_> = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let at = args.iter().position(|a| a == "--windows").expect("--windows"); + assert_eq!(args[at + 1], "16"); + } + use super::*; use crate::gpu::xbox::tests::{fssm, sample, CODE}; From 5ef4a38cc94ae979f65c4861afb75109c302dc0c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:46:13 +0100 Subject: [PATCH 148/175] D3D12.X: title submits wait for tile mappings on the CPU again Restores amd-dev's XCL_SPARSE_CPU_WAIT_MS (1000 ms by default, 0: off) from 6fa964de, which the main -> amd-dev merge (#3444) dropped with main's sparse.rs: a title submit whose wait for the sparse fence covers tile mappings, and every wait for the texture page queue's mappings, waits for the fence on the CPU before the title's lists go, and only past the limit has the title's queue wait for it on the GPU (logged). On amd-dev this was the RX 9070 device-removal fix: with every title queue holding its work behind the mapping queue's fence, the fence stopped short for 15 s and the device was removed. It also fixes the two debug-layer e2e tests, which fail the same way on plain main (1bd9cee1) and pass on amd-dev (6bab0c53): with the GPU wait, the debug layer's synchronized command queue validation holds a queue's calls after a Wait for an unreached value on its own thread, and the test title's copies and fence Signal after a tile mapping did not run for more than 5 s ("GPU fence 1 not reached" in the sparse buffer heap, depth bias, raytracing and streamed texture sections), though the CPU wait finds the mapping done within 1 ms. With synchronized validation turned off (experiment) the GPU wait passed those sections too. Which waits cover mappings is tracked as on amd-dev: map_tiles, unmap_tiles and poison_all set mapping_queued, the next signal records mapped_value. Waits for uploads alone stay on the GPU. The CPU wait holds no queue's submit lease (title_textures::refresh runs before the lease is taken) and lets the upload gate go; it keeps the queue's wait gate, so another submit on that queue still sees the wait done first. amd-dev's wait_pending_mappings is not restored: main records the put-off dispatches before the submit's refresh, so no mapping of theirs comes between the refresh and the lists. --- crates/xcl/src/hle/d3d12x/sparse.rs | 141 +++++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/vram.rs | 7 +- 2 files changed, 144 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 2c689a8386..ce17ba81e2 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -2568,6 +2568,11 @@ struct State { rb_last_fence: u64, /// the fence value each title queue last waited for waited: FxHashMap, + /// tile mappings were queued since the last `signal` (`map_tiles` / `unmap_tiles` / + /// `poison_all`) + mapping_queued: AtomicBool, + /// the fence value of the last `signal` that came after tile mappings + mapped_value: u64, /// `mapped` as runs of neighbouring tiles (start -> end), kept with it: sorted out of all of /// them again (a retail title has 150,000) for each look behind a commit runs: BTreeMap, @@ -3375,6 +3380,8 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -3643,6 +3650,7 @@ impl State { if tiles.is_empty() { return; } + self.mapping_queued.store(true, Ordering::Relaxed); let mut by_heap: FxHashMap> = FxHashMap::default(); debug_assert!(tiles.iter().all(|t| t.1 != LAZY), "a tile with no video memory is mapped nowhere"); for &(a, (h, t)) in tiles { @@ -3694,6 +3702,7 @@ impl State { if tiles.is_empty() { return; } + self.mapping_queued.store(true, Ordering::Relaxed); let mut xs: Vec = tiles.iter().map(|&a| ((a - res_base) / TILE) as u32).collect(); xs.sort_unstable(); let mut coords: Vec = Vec::with_capacity(xs.len()); @@ -3738,6 +3747,7 @@ impl State { if tiles == 0 { return; } + self.mapping_queued.store(true, Ordering::Relaxed); let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: tiles, UseBox: false.into(), ..Default::default() }; let (flag, off) = (D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE, 0u32); @@ -3988,6 +3998,9 @@ impl State { unsafe fn signal(&mut self) { self.value += 1; let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + if self.mapping_queued.swap(false, Ordering::Relaxed) { + self.mapped_value = self.value; + } } #[inline] @@ -8373,13 +8386,21 @@ unsafe fn before_execute_locked( // the queue waits for the uploads and tile mappings (outside the lock; given back if it fails) let value = s.value; let previous = s.waited.get(&q).copied(); - let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value, previous)); + let mappings = waits_for_mappings(s.mapped_value, previous); + let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value, previous, s.dev.clone())); drop(held); drop(g); drop(observed); // (recycled copy-back jobs past the pool's cap drop outside all locks) drop(excess); - if let Some((fence, value, previous)) = wait { + if let Some((fence, value, previous, dev)) = wait { + // tile mappings among them: waited for here, with the upload gate let go, and the queue + // holds none of its work behind them (`XCL_SPARSE_CPU_WAIT_MS`). This thread holds no + // queue's submit turn: the title's lists go out after this (`prepare_title_submission`). + if mappings && timing.with_released(uploads, || cpu_waited_for_mappings(&fence, value, &dev, "sparse uploads and tile mappings")) { + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::Ready; + } if super::real::native_queue_wait(queue, &fence, value).is_err() { let mut g = lock_state(); if let Some(s) = g.as_mut().filter(|s| s.fence.as_raw() == fence.as_raw() && s.waited.get(&q) == Some(&value)) { @@ -8395,6 +8416,74 @@ unsafe fn before_execute_locked( } } +/// Whether a title queue's wait for the sparse fence, from `previous` (the value it waited for +/// last) to the fence's value now, covers tile mappings: a `signal` after them gave +/// `mapped_value`. +fn waits_for_mappings(mapped_value: u64, previous: Option) -> bool { + mapped_value > previous.unwrap_or(0) +} + +/// `XCL_SPARSE_CPU_WAIT_MS` (1 000 by default, 0: off): how long a title submit waits on the +/// CPU for a mapping queue's tile mappings (the sparse windows', the video memory pages') before +/// its lists go, instead of the title's queue waiting for them on the GPU. +/// +/// With the GPU wait every queue of a retail title held its queued work behind the sparse +/// queue's tile mappings. On an AMD RX 9070 (16 GB, at its memory budget) the sparse queue's +/// fence then stopped short of the value they waited for, for 15 s – while AMD's crash analysis +/// found no command buffer in flight – and the device was removed (five runs in a row, 63–140 s +/// into the world). A tile mapping is the video memory manager's work: it can have to evict, and +/// it cannot take memory from queues whose work is already queued behind that very mapping. With +/// the wait on the CPU no queue holds work behind a mapping; past the limit the GPU wait is used +/// as before (logged). +/// +/// Under the D3D12 debug layer the GPU wait held the title's next lists too: with synchronized +/// command queue validation (on by default) the layer keeps a queue's calls after a `Wait` for a +/// value the fence has not reached on its own thread, and the test title's lists and its fence +/// `Signal` after a tile mapping did not run for more than 5 s, though the mapping was done +/// within a millisecond (`e2e`: `test_title_*_under_the_debug_layer*`). +fn sparse_cpu_wait_ms() -> u32 { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + *MS.get_or_init(|| std::env::var("XCL_SPARSE_CPU_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1000)) +} + +/// Whether `fence` (of the mapping queue `what`) reached `value` within `sparse_cpu_wait_ms`, +/// waited for on the CPU. False at once with the wait off, and past the limit (logged): the +/// caller then has the queue wait for it on the GPU. +pub(super) unsafe fn cpu_waited_for_mappings(fence: &ID3D12Fence, value: u64, dev: &ID3D12Device, what: &str) -> bool { + cpu_waited_within(fence, value, dev, what, sparse_cpu_wait_ms()) +} + +unsafe fn cpu_waited_within(fence: &ID3D12Fence, value: u64, dev: &ID3D12Device, what: &str, ms: u32) -> bool { + if ms == 0 { + return false; + } + thread_local! { + static EVENT: HANDLE = unsafe { windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap_or_default() }; + } + let t = std::time::Instant::now(); + // (one event for this thread's waits: `fence::wait` takes a wake for an earlier registration + // that gave up as no completion) + let waited = EVENT.with(|&ev| crate::gpu::fence::wait(fence, value, dev, (!ev.is_invalid()).then_some(ev), ms)); + let took = t.elapsed(); + static SLOW: AtomicU64 = AtomicU64::new(0); + match waited { + Ok(()) => { + if took >= std::time::Duration::from_millis(200) && SLOW.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: {what} waited {} ms on the CPU for fence {value}", took.as_millis()); + } + true + } + Err(e) => { + crate::xlog_warn!( + "D3D12.X: {what} did not reach {value} in {} ms (at {}: {e}): the title's queue waits for it on the GPU", + took.as_millis(), + super::real::fence_completed(fence) + ); + false + } + } +} + /// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC /// description): a reserved resource over the window's tiles there, starting at the 64 KiB /// below `va` (returned: its distance from there). @@ -9030,6 +9119,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -10531,6 +10622,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -10950,6 +11043,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -11084,6 +11179,8 @@ mod tests { rb_list, rb_last_fence: 0, waited: FxHashMap::default(), + mapping_queued: AtomicBool::new(false), + mapped_value: 0, runs: BTreeMap::new(), scratch_runs: Vec::new(), own_pages: Vec::new(), @@ -11275,6 +11372,46 @@ mod tests { (base, s) } + /// The signal after tile mappings is the one a title queue's wait for them is told by + /// (`mapped_value`): a wait across it is waited for on the CPU, one for uploads alone stays + /// on the GPU. The CPU wait returns once the fence is there, and gives up at its limit (and + /// at once with the limit 0) for the GPU wait to take over. + #[test] + fn a_wait_across_tile_mappings_is_waited_for_on_the_cpu() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + s.commit_range(base, TILE); + // (as before the title's submit: the tile's mapping and the signal after it) + s.flush_pending(); + assert!(s.value > 0 && s.mapped_value == s.value, "value {} mapped {}", s.value, s.mapped_value); + assert!(!s.mapping_queued.load(Ordering::Relaxed)); + assert!(waits_for_mappings(s.mapped_value, None)); + assert!(waits_for_mappings(s.mapped_value, Some(s.mapped_value - 1))); + let mapped = s.mapped_value; + // a signal with no mapping before it (uploads alone) + s.signal(); + assert_eq!(s.mapped_value, mapped); + assert!(!waits_for_mappings(s.mapped_value, Some(mapped)), "a queue past the mapping waits for uploads alone"); + + assert!(cpu_waited_within(&s.fence, s.value, &s.dev, "test mappings", 5000), "the sparse queue's fence was not reached"); + let never: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let t = std::time::Instant::now(); + assert!(!cpu_waited_within(&never, 1, &s.dev, "test mappings", 50)); + assert!(t.elapsed() >= std::time::Duration::from_millis(45), "gave up after {:?}", t.elapsed()); + let t = std::time::Instant::now(); + assert!(!cpu_waited_within(&never, 1, &s.dev, "test mappings", 0)); + assert!(t.elapsed() < std::time::Duration::from_millis(45), "the wait is off at 0"); + // a later fence value reached after a wait that gave up on the same event + never.Signal(1).expect("CPU signal"); + assert!(cpu_waited_within(&never, 1, &s.dev, "test mappings", 50)); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + unsafe fn add_upload_slot(s: &mut State, fence_val: u64, close: bool) { let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("upload allocator"); let list: ID3D12GraphicsCommandList = s.dev diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 97a464d1aa..56efcb40e7 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2799,8 +2799,11 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { } let queue_wait_started = measure.then(std::time::Instant::now); if let Some((fence, value)) = wait { - let _ = super::real::native_queue_wait(queue, &fence, value); - super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); + // (on the CPU first, as the sparse windows' mappings: `sparse::cpu_waited_for_mappings`) + if !super::sparse::cpu_waited_for_mappings(&fence, value, &dev, "texture page mappings") { + let _ = super::real::native_queue_wait(queue, &fence, value); + super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); + } } if let Some(started) = queue_wait_started { measured.queue_wait = started.elapsed(); From e03446c7b3ccbef5d6a9e408f05938252beb953f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:55:52 +0100 Subject: [PATCH 149/175] D3D12.X: recycled texture pages are zeroed before a new texture uses them Restores amd-dev's XCL_ZERO_TARGET_PAGES (on by default, 0: off) from 6fa964de, which the main -> amd-dev merge (#3444) dropped with main's vram.rs. Our run environment still sets XCL_ZERO_TARGET_PAGES=1; the merged tree did not know the switch, so a pool tile given back by one texture went to the next with the old texture's bytes in it (#505, #1833: stale render-target, depth and UAV bytes in new targets). As on amd-dev: the tile pool keeps a bit per tile that came back (TilePool::dirty_bits), set when a tile cools back into the pool and taken when it is handed out; the recycled tiles of a bind are zeroed on the mapping queue through a buffer placed over the whole pool heap (no extra video memory), from a 1 MiB zeroed upload buffer, in a ring of 4 command lists, followed by an aliasing barrier and the mapping fence's signal. They are flushed at 256 tiles and in before_execute before the wait value is read, so every queue that waits for the page mappings (title queues, texture uploads) waits for the zero-fill too. Fitted to main: the list goes through native_queue_execute and the signal through native_queue_signal, as Pages::map's do (the PAGES lock, then the mapping queue's lease); a ring slot still on the GPU is waited for at most 5 s, then that batch is skipped (logged) instead of resetting an allocator in use; a reclaimed heap's zero alias goes with it in PoolHeaps::take_heap (made in own_work, it has no Release hook). Deferred unmap batches are not restored: main defers superseded texture unmaps behind every queue's completion mark itself (held_unmaps, c22c0ac2). --- crates/xcl/src/hle/d3d12x/vram.rs | 460 +++++++++++++++++++++++++++++- 1 file changed, 454 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 56efcb40e7..bda3470f90 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -998,6 +998,8 @@ unsafe fn arena_heap(dev: &ID3D12Device, va: usize, size: usize, align: usize) - const PAGE: usize = 0x1_0000; /// pages of a video-memory pool heap (64 MiB) const POOL_PAGES: u32 = 1024; +/// words of a pool heap's recycled-tile bits (`TilePool::dirty_bits`) +const DIRTY_WORDS: usize = (POOL_PAGES as usize).div_ceil(64); /// a page no target uses any more is kept this long for the next target at its address (with /// what it holds – a title may make a target again over memory it rendered to) const IDLE: std::time::Duration = std::time::Duration::from_secs(2); @@ -1400,6 +1402,10 @@ struct TilePool { free_by_heap: Vec>, /// Whether `free_by_heap[h]` must be sorted descending before popping. dirty_sort: Vec, + /// Per-heap bitmap of recycled tiles (`1` = previously allocated & returned, holds stale VRAM + /// contents that must be zeroed before handing to a new texture under `XCL_ZERO_TARGET_PAGES`). + /// Freshly created heaps start all `0` (already zeroed by D3D12). + dirty_bits: Vec<[u64; DIRTY_WORDS]>, /// Fresh-allocation packing class for heap `h`. Shared address pages may give either class /// live owners here, so this is never proof that a heap is safe to evict. heap_evictable: Vec, @@ -1417,6 +1423,7 @@ impl TilePool { TilePool { free_by_heap: Vec::new(), dirty_sort: Vec::new(), + dirty_bits: Vec::new(), heap_evictable: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::new(), @@ -1424,17 +1431,39 @@ impl TilePool { } } + #[inline] + fn mark_dirty(&mut self, h: usize, t: u32) { + let word = (t as usize) >> 6; + if let Some(w) = self.dirty_bits.get_mut(h).and_then(|bits| bits.get_mut(word)) { + *w |= 1u64 << (t & 63); + } + } + + #[inline] + fn take_dirty(&mut self, h: usize, t: u32) -> bool { + let word = (t as usize) >> 6; + if let Some(w) = self.dirty_bits.get_mut(h).and_then(|bits| bits.get_mut(word)) { + let mask = 1u64 << (t & 63); + let was = (*w & mask) != 0; + *w &= !mask; + return was; + } + false + } + fn add_heap_at(&mut self, slot: u32, pool_pages: u32, evictable: bool) { let idx = slot as usize; if idx >= self.free_by_heap.len() { self.free_by_heap.resize_with(idx + 1, Vec::new); self.dirty_sort.resize(idx + 1, false); + self.dirty_bits.resize(idx + 1, [0u64; DIRTY_WORDS]); self.live.resize(idx + 1, false); self.heap_evictable.resize(idx + 1, false); } debug_assert!(self.free_by_heap[idx].is_empty()); self.free_by_heap[idx] = (0..pool_pages).rev().collect(); self.dirty_sort[idx] = false; + self.dirty_bits[idx] = [0u64; DIRTY_WORDS]; self.live[idx] = true; self.heap_evictable[idx] = evictable; self.free_total += pool_pages as usize; @@ -1461,6 +1490,7 @@ impl TilePool { self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; + self.dirty_bits[h] = [0u64; DIRTY_WORDS]; self.live[h] = false; self.heap_evictable[h] = false; self.free_total -= full; @@ -1482,12 +1512,28 @@ impl TilePool { if idx < self.free_by_heap.len() && self.live[idx] { self.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); self.free_total += 1; } } } + #[cfg(test)] fn return_tiles(&mut self, tiles: &[Tile]) { + for &(h, t) in tiles { + let idx = h as usize; + if idx < self.free_by_heap.len() && self.live[idx] { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); + self.free_total += 1; + } + } + } + + /// Tiles a failed `take_batch_recycled` took, back untouched: the recycled ones of them + /// (`dirty`) still need their zero-fill. + fn return_rollback_tiles(&mut self, tiles: &[Tile], dirty: &[Tile]) { for &(h, t) in tiles { let idx = h as usize; if idx < self.free_by_heap.len() && self.live[idx] { @@ -1496,6 +1542,9 @@ impl TilePool { self.free_total += 1; } } + for &(h, t) in dirty { + self.mark_dirty(h as usize, t); + } } /// Pick a pool heap in the requested allocation class to take up to `rem` tiles from: @@ -1539,6 +1588,7 @@ impl TilePool { /// Allocate `count` tiles in one allocation class, preferring a single heap and ascending /// contiguous offsets. `make_heap` allocates a new backing pool heap when the class has no /// free tiles. On failure, any tiles already taken are returned untouched. + #[cfg(test)] fn take_batch( &mut self, count: usize, @@ -1546,6 +1596,23 @@ impl TilePool { evictable: bool, now: std::time::Instant, pool_pages: u32, + make_heap: impl FnMut() -> Option, + ) -> Option> { + let mut ignored = Vec::new(); + self.take_batch_recycled(count, preferred, evictable, now, pool_pages, &mut ignored, make_heap) + } + + /// `take_batch`, the recycled tiles among those taken (they hold another texture's bytes) + /// added to `recycled_out` for their zero-fill (`Pages::flush_zero_tiles`). + #[allow(clippy::too_many_arguments)] + fn take_batch_recycled( + &mut self, + count: usize, + preferred: Option, + evictable: bool, + now: std::time::Instant, + pool_pages: u32, + recycled_out: &mut Vec, mut make_heap: impl FnMut() -> Option, ) -> Option> { if count == 0 { @@ -1553,13 +1620,15 @@ impl TilePool { } self.drain_cooling(now); let mut out = Vec::with_capacity(count); + let recycled_start = recycled_out.len(); while out.len() < count { let rem = count - out.len(); let h = match self.pick_heap(rem, preferred, evictable) { Some(h) => h, None => { let Some(new_h) = make_heap() else { - self.return_tiles(&out); + let rolled_dirty = recycled_out.split_off(recycled_start); + self.return_rollback_tiles(&out, &rolled_dirty); return None; }; self.add_heap_at(new_h, pool_pages, evictable); @@ -1570,10 +1639,12 @@ impl TilePool { self.free_by_heap[h].sort_unstable_by(|a, b| b.cmp(a)); self.dirty_sort[h] = false; } - let free = &mut self.free_by_heap[h]; - let take = rem.min(free.len()); + let take = rem.min(self.free_by_heap[h].len()); for _ in 0..take { - let t = free.pop().unwrap(); + let t = self.free_by_heap[h].pop().unwrap(); + if self.take_dirty(h, t) { + recycled_out.push((h as u32, t)); + } out.push((h as u32, t)); } self.free_total -= take; @@ -1582,6 +1653,32 @@ impl TilePool { } } +/// Coalesce recycled `(heap, tile_idx)` pairs into sorted, deduplicated `(heap, start_tile, count)` +/// runs so GPU zero-fills issue one `CopyBufferRegion` per contiguous tile span. +fn coalesce_tile_runs(tiles: &mut Vec) -> Vec<(u32, u32, u32)> { + if tiles.is_empty() { + return Vec::new(); + } + tiles.sort_unstable(); + tiles.dedup(); + let mut runs: Vec<(u32, u32, u32)> = Vec::new(); + for &(h, t) in tiles.iter() { + match runs.last_mut() { + Some(last) if last.0 == h && last.1 + last.2 == t => last.2 += 1, + _ => runs.push((h, t, 1)), + } + } + runs +} + +/// Zero recycled page-pool tiles on the mapping queue before handing them to newly mapped +/// textures so stale render-target/depth/UAV bytes never bleed into new targets (`#505`/`#1833`). +/// Enabled by default (`XCL_ZERO_TARGET_PAGES=0` disables). +fn zero_target_pages() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").map_or(true, |v| v.trim() != "0")) +} + /// Allocate one 64 MiB default heap for `Pages`. unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { let desc = D3D12_HEAP_DESC { @@ -1603,13 +1700,17 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { /// are reclaimed back to local VRAM. `len()` reports the count of live heaps. struct PoolHeaps { slots: Vec>, + /// Aliased 64 MiB `BUFFER` placed at offset 0 of each pool heap for GPU zero-fills of recycled + /// tiles (0 bytes of extra VRAM; lazily created on first recycled tile in that heap). Made in + /// `own_work`: a plain PC object, its `Release` reaches none of XCL's hooks. + zero_bufs: Vec>, free_slots: Vec, live: usize, } impl PoolHeaps { fn new() -> Self { - Self { slots: Vec::new(), free_slots: Vec::new(), live: 0 } + Self { slots: Vec::new(), zero_bufs: Vec::new(), free_slots: Vec::new(), live: 0 } } fn len(&self) -> usize { @@ -1621,21 +1722,57 @@ impl PoolHeaps { if let Some(idx) = self.free_slots.pop() { debug_assert!(self.slots[idx as usize].is_none()); self.slots[idx as usize] = Some(heap); + self.zero_bufs[idx as usize] = None; idx } else { let idx = self.slots.len() as u32; self.slots.push(Some(heap)); + self.zero_bufs.push(None); idx } } + /// The heap at `idx` out of the pool. Its zero-fill alias goes with it (a zero-fill still on + /// the GPU keeps its own reference in its `ZeroSlot`), so the heap's memory can be freed. fn take_heap(&mut self, idx: u32) -> Option { + drop(self.zero_bufs.get_mut(idx as usize).and_then(Option::take)); let h = self.slots.get_mut(idx as usize)?.take()?; self.live -= 1; self.free_slots.push(idx); Some(h) } + unsafe fn zero_buffer(&mut self, dev: &ID3D12Device, idx: usize) -> Option { + if let Some(b) = self.zero_bufs.get(idx)?.as_ref() { + return Some(b.clone()); + } + let heap = self.slots.get(idx)?.as_ref()?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: POOL_PAGES as u64 * PAGE as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let mut res: Option = None; + let ok = super::title_textures::own_work(|| { + dev.CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res) + }) + .is_ok(); + if !ok { + return None; + } + let buf = res?; + let _ = buf.SetName(windows::core::w!("xcl vram zero_alias")); + self.zero_bufs[idx] = Some(buf.clone()); + Some(buf) + } + /// The live heap at `idx` (None: reclaimed or never made). fn get(&self, idx: usize) -> Option<&ID3D12Heap> { self.slots.get(idx).and_then(Option::as_ref) @@ -1649,6 +1786,63 @@ impl std::ops::Index for PoolHeaps { } } +/// Reusable 4-slot command ring + 1 MiB pre-zeroed upload buffer for asynchronous GPU zero-fills +/// of recycled VRAM pool tiles on `Pages::queue`. +const ZERO_BUF_BYTES: u64 = 1 << 20; +const ZERO_SLOTS: usize = 4; + +struct ZeroSlot { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence_val: u64, + kept_bufs: Vec, +} + +struct ZeroRing { + zero_src: ID3D12Resource, + slots: Vec, +} + +impl ZeroRing { + unsafe fn new(dev: &ID3D12Device) -> Option { + let mut src: Option = None; + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: ZERO_BUF_BYTES, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + super::title_textures::own_work(|| { + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut src) + }) + .ok()?; + let zero_src = src?; + let mut mapped = std::ptr::null_mut(); + zero_src.Map(0, None, Some(&mut mapped)).ok()?; + std::ptr::write_bytes(mapped as *mut u8, 0, ZERO_BUF_BYTES as usize); + zero_src.Unmap(0, None); + let mut slots = Vec::with_capacity(ZERO_SLOTS); + for _ in 0..ZERO_SLOTS { + let (alloc, list) = super::title_textures::own_work(|| -> windows::core::Result<_> { + let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None)?; + l.Close()?; + Ok((a, l)) + }) + .ok()?; + slots.push(ZeroSlot { alloc, list, fence_val: 0, kept_bufs: Vec::new() }); + } + Some(ZeroRing { zero_src, slots }) + } +} + fn keep_spare_pools() -> usize { static N: std::sync::OnceLock = std::sync::OnceLock::new(); *N.get_or_init(|| { @@ -1714,6 +1908,12 @@ struct Pages { scratch_flags: Vec, scratch_offsets: Vec, scratch_counts: Vec, + /// recycled tiles awaiting batched GPU zero-fill on `self.queue` before next `before_execute` + pending_zero_tiles: Vec, + /// lazily initialized command ring + 1 MiB zero source for `flush_zero_tiles` + zero_ring: Option, + /// true once `ZeroRing::new` failed so we don't retry every submit + zero_ring_failed: bool, } // D3D12 objects are free-threaded @@ -1860,7 +2060,112 @@ impl Pages { scratch_flags: Vec::new(), scratch_offsets: Vec::new(), scratch_counts: Vec::new(), + pending_zero_tiles: Vec::new(), + zero_ring: None, + zero_ring_failed: false, + }) + } + + /// Asynchronously zero all queued recycled pool tiles on `self.queue` in one batched command + /// list, then emit an aliasing barrier + `self.fence` signal so any title queue waiting in + /// `before_execute` sees zeroed tiles before reading or writing newly mapped textures. + unsafe fn flush_zero_tiles(&mut self, dev: &ID3D12Device) { + if self.pending_zero_tiles.is_empty() { + return; + } + if !zero_target_pages() || self.zero_ring_failed { + self.pending_zero_tiles.clear(); + return; + } + let runs = coalesce_tile_runs(&mut self.pending_zero_tiles); + self.pending_zero_tiles.clear(); + if runs.is_empty() { + return; + } + if self.zero_ring.is_none() { + match ZeroRing::new(dev) { + Some(r) => self.zero_ring = Some(r), + None => { + crate::xlog_warn!("D3D12.X: no zero-fill ring for recycled texture pages: they keep what they held"); + self.zero_ring_failed = true; + return; + } + } + } + let mut heap_bufs: std::collections::HashMap = std::collections::HashMap::new(); + for &(h, _, _) in &runs { + if let std::collections::hash_map::Entry::Vacant(e) = heap_bufs.entry(h) { + if let Some(buf) = self.pools.zero_buffer(dev, h as usize) { + e.insert(buf); + } + } + } + if heap_bufs.is_empty() { + return; + } + // (XCL's own fence: not through the title's GetCompletedValue hook) + let done = super::real::fence_completed(&self.fence); + let ring = self.zero_ring.as_mut().unwrap(); + let slot_idx = match ring.slots.iter().position(|s| s.fence_val <= done) { + Some(i) => i, + None => { + let (oldest_idx, oldest_val) = + ring.slots.iter().enumerate().min_by_key(|(_, s)| s.fence_val).map(|(i, s)| (i, s.fence_val)).unwrap(); + // (the mapping queue waits for nothing of the title's: its work gets done) + if let Err(e) = crate::gpu::fence::wait(&self.fence, oldest_val, dev, None, 5_000) { + crate::xlog_warn!("D3D12.X: zero-fill of recycled texture pages skipped: its ring slot is still on the GPU ({e})"); + return; + } + oldest_idx + } + }; + let zero_src = ring.zero_src.clone(); + let slot = &mut ring.slots[slot_idx]; + slot.kept_bufs.clear(); + let queue = self.queue.clone(); + let ok = super::title_textures::own_work(|| -> windows::core::Result<()> { + slot.alloc.Reset()?; + slot.list.Reset(&slot.alloc, None)?; + for &(h, start, count) in &runs { + let Some(dst) = heap_bufs.get(&h) else { continue }; + let mut offset = start as u64 * PAGE as u64; + let mut rem = count as u64 * PAGE as u64; + while rem > 0 { + let chunk = rem.min(ZERO_BUF_BYTES); + slot.list.CopyBufferRegion(dst, offset, &zero_src, 0, chunk); + offset += chunk; + rem -= chunk; + } + } + let mut barriers: Vec = Vec::with_capacity(heap_bufs.len()); + for buf in heap_bufs.values() { + slot.kept_bufs.push(buf.clone()); + barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::transmute_copy(buf), + pResourceAfter: std::mem::zeroed(), + }), + }, + }); + } + if !barriers.is_empty() { + slot.list.ResourceBarrier(&barriers); + } + slot.list.Close()?; + let cmd: ID3D12CommandList = slot.list.cast()?; + // (through the PC queue slot in the queue's turn, as `map`'s signal) + super::real::native_queue_execute(&queue, &cmd); + Ok(()) }) + .is_ok(); + if ok { + self.value += 1; + let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + slot.fence_val = self.value; + } } /// Pages no resource used for `IDLE` go back to the pools. @@ -2119,7 +2424,8 @@ impl Pages { let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, evictable, now, POOL_PAGES, || { + let pending_zero = &mut self.pending_zero_tiles; + let fresh = pool.take_batch_recycled(missing, preferred, evictable, now, POOL_PAGES, pending_zero, || { let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; @@ -2165,6 +2471,9 @@ impl Pages { tiles.push(tile); } self.map(res, sub, &tiles); + if self.pending_zero_tiles.len() >= 256 { + self.flush_zero_tiles(dev); + } Some((used, used_extra)) } } @@ -2778,6 +3087,8 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { completed_unmaps = pages.release_held_unmaps(now, |fence| { observed_completion(&unmap_completions, fence, |known, current| known.as_raw() == current.as_raw()) }); + // (the recycled tiles of textures mapped since: zeroed before the queue's work uses them) + pages.flush_zero_tiles(&dev); let value = pages.value; if reserve_page_wait(&mut pages.waited, queue_key, value) { wait = Some((pages.fence.clone(), value)); @@ -4327,6 +4638,143 @@ mod tests { assert_eq!(pool.free_total, P as usize - 2); } + #[test] + fn tile_pool_tracks_dirty_bits_only_for_recycled_tiles() { + let mut pool = TilePool::new(); + let now = Instant::now(); + let mut recycled = Vec::new(); + let mut next_h = 0u32; + + // Fresh heap tiles are never marked recycled (D3D12 guarantees fresh heaps are zeroed). + let first = pool + .take_batch_recycled(4, None, false, now, POOL_PAGES, &mut recycled, || { + let h = next_h; + next_h += 1; + Some(h) + }) + .unwrap(); + assert_eq!(first, vec![(0, 0), (0, 1), (0, 2), (0, 3)]); + assert!(recycled.is_empty(), "freshly allocated heap tiles must not need GPU zeroing"); + + // Returned tiles are marked dirty and reported in `recycled` when re-taken. + pool.return_tiles(&[(0, 1), (0, 2)]); + let again = pool.take_batch_recycled(3, Some(0), false, now, POOL_PAGES, &mut recycled, || None).unwrap(); + assert_eq!(again, vec![(0, 1), (0, 2), (0, 4)]); + assert_eq!(recycled, vec![(0, 1), (0, 2)], "only previously returned tiles require zeroing"); + + // Cooled tiles also mark dirty when drained back into free_by_heap. + recycled.clear(); + pool.push_cooling((0, 0), now); + let later = now + COOL + Duration::from_millis(1); + let cooled = pool.take_batch_recycled(1, Some(0), false, later, POOL_PAGES, &mut recycled, || None).unwrap(); + assert_eq!(cooled, vec![(0, 0)]); + assert_eq!(recycled, vec![(0, 0)]); + + // A take that fails gives its tiles back with the recycled ones still recycled. + recycled.clear(); + pool.push_cooling((0, 3), now); + let free = pool.free_total; + assert!(pool.take_batch_recycled(free + 2, Some(0), false, later, POOL_PAGES, &mut recycled, || None).is_none()); + assert!(recycled.is_empty(), "a failed take reports nothing to zero"); + assert_eq!(pool.free_total, free + 1); + let back = pool.take_batch_recycled(1, Some(0), false, later, POOL_PAGES, &mut recycled, || None).unwrap(); + assert_eq!(back, vec![(0, 3)]); + assert_eq!(recycled, vec![(0, 3)], "the rolled-back recycled tile still needs zeroing"); + } + + #[test] + fn coalesce_tile_runs_merges_adjacent_tiles_per_heap() { + let mut tiles = vec![(1, 5), (0, 3), (0, 2), (1, 6), (0, 3), (0, 10), (1, 4)]; + assert_eq!(coalesce_tile_runs(&mut tiles), vec![(0, 2, 2), (0, 10, 1), (1, 4, 3)]); + let mut empty = Vec::new(); + assert!(coalesce_tile_runs(&mut empty).is_empty()); + } + + /// A pool tile given back holds what its last texture had; the next texture mapped onto it + /// gets it zeroed on the mapping queue first (`XCL_ZERO_TARGET_PAGES`, on by default), so a + /// queue that waits for the mappings reads zeros there, not the old texture's bytes. + #[test] + fn a_recycled_page_is_zeroed_before_a_new_texture_uses_it() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: PAGE as u64, + 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, + ..Default::default() + }; + let reserved = || { + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).expect("reserved buffer"); + r.unwrap() + }; + let committed = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut r) + .expect("committed buffer"); + r.unwrap() + }; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + // (a copy on the title's queue after its wait for the mappings, then waited for) + let copy = |pages: &Pages, dst: &ID3D12Resource, src: &ID3D12Resource, v: u64| { + alloc.Reset().unwrap(); + list.Reset(&alloc, None).unwrap(); + list.CopyBufferRegion(dst, 0, src, 0, PAGE as u64); + list.Close().unwrap(); + queue.Wait(&pages.fence, pages.value).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + queue.Signal(&done, v).unwrap(); + crate::gpu::fence::wait(&done, v, &dev, None, 5000).expect("the copy"); + }; + + // the first texture's page gets its bytes + let first = reserved(); + let (used, extra) = pages.bind(&dev, &first, 0x2000_0000, Some(PAGE as u64), 1).expect("bind"); + assert!(pages.pending_zero_tiles.is_empty(), "a fresh heap's tile needs no zero-fill"); + let up = committed(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0xab, PAGE); + copy(&pages, &first, &up, 1); + + // given back (cooled already), and taken by the next texture + pages.unmap(&first, 1); + let past = Instant::now().checked_sub(COOL + Duration::from_millis(10)).expect("an earlier instant"); + pages.release_tiles(used, extra, past, true); + let second = reserved(); + let (used2, extra2) = pages.bind(&dev, &second, 0x2010_0000, Some(PAGE as u64), 1).expect("bind again"); + assert_eq!(pages.pending_zero_tiles, vec![(0, 0)], "the second texture got the first one's page"); + pages.flush_zero_tiles(&dev); + assert!(pages.pending_zero_tiles.is_empty()); + + let rb = committed(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + copy(&pages, &rb, &second, 2); + let mut r = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut r)).unwrap(); + let bytes = std::slice::from_raw_parts(r as *const u8, PAGE); + let left = bytes.iter().filter(|&&b| b != 0).count(); + rb.Unmap(0, None); + assert_eq!(left, 0, "{left} bytes of the first texture showed in the second"); + + pages.unmap(&second, 1); + pages.release_tiles(used2, extra2, Instant::now(), true); + crate::gpu::fence::wait(&pages.fence, pages.value, &dev, None, 5000).expect("the mapping queue"); + } + } + #[test] fn tile_pool_keeps_evictable_and_pinned_tiles_in_separate_heaps() { let t0 = Instant::now(); From aeefef106d6ca573a3accd87742f08ff09808281 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:00:54 +0100 Subject: [PATCH 150/175] D3D12.X: small sampled textures go to 4 KiB blocks of shared heaps again Wires vram_small back in, as on amd-dev (6fa964de; XCL_VRAM_SMALL, on by default, 0: off). The main -> amd-dev merge (#3444) kept the module but not its calls in vram.rs, and dropped its tests, so every sampled texture under 64 KiB took a whole 64 KiB page of a reserved resource again: up to 16x the video memory of a mip tail, icon or LUT, plus a CreateReservedResource and UpdateTileMappings for each placement. As on amd-dev: place_pages puts a texture under 64 KiB that does not alias a live 64 KiB page (has_live_page: a sampled view over a render target stays on the target's pages) into a block of a 16 MiB heap; forget_for_recycle gives its block back before the pages are asked; page_bytes counts the small pools for the activity log. vram_small.rs is amd-dev's again, tests included; the GPU test now checks that the 4 KiB textures took no 64 KiB page, as main's page_bytes_for counts pages alone. --- crates/xcl/src/hle/d3d12x/vram.rs | 49 +++- crates/xcl/src/hle/d3d12x/vram_small.rs | 310 ++++++++++++++++++++++++ 2 files changed, 357 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index bda3470f90..f268af0419 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -921,7 +921,7 @@ pub(super) fn forget_for_recycle(resource: usize, held: bool) -> Option String { ) } +/// Whether `va` already has a live (or still within `IDLE`) 64 KiB page on `device` (e.g., an +/// existing GPU-owned render target that a sampled view at the same 64 KiB-aligned address should +/// alias). +fn has_live_page(device: usize, va: usize) -> bool { + let g = PAGES.lock().unwrap(); + let now = std::time::Instant::now(); + g.get(&device) + .and_then(|p| p.as_ref()) + .is_some_and(|p| p.pages.get(&va).is_some_and(|pg| pg.idle_since.is_none_or(|s| now.duration_since(s) < IDLE))) +} + +/// Immediately evict all unreferenced idle pages and small-pool slots on `device` so GPU tests +/// sharing the process's singleton `ID3D12Device` do not observe stale `IDLE` expiries mid-test. +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + super::vram_small::flush_idle_for(device); + let mut g = PAGES.lock().unwrap(); + if let Some(Some(p)) = g.get_mut(&device) { + let now = std::time::Instant::now(); + while let Some((key, since)) = p.idle.pop_front() { + let still_idle = |pg: &Page| pg.idle_since == Some(since); + let page = match key { + PageKey::Own(a) if p.pages.get(&a).is_some_and(still_idle) => p.pages.remove(&a), + PageKey::Extra(va, i) if p.extra_pages.get(&(va, i)).is_some_and(still_idle) => p.extra_pages.remove(&(va, i)), + _ => None, + }; + if let Some(pg) = page { + p.pool.push_cooling(pg.tile, now); + } + } + } +} + +/// (bytes of pages in use by tiled textures and small-pool blocks, bytes of pool heaps and small +/// pools) – `XCL_ACTIVITY` pub fn page_bytes() -> (usize, usize) { + let (su, sp) = super::vram_small::bytes(); let g = PAGES.lock().unwrap(); - g.values().flatten().fold((0, 0), |(used, pools), p| { + g.values().flatten().fold((su, sp), |(used, pools), p| { (used + (p.pages.len() + p.extra_pages.len()) * PAGE, pools + p.pools.len() * POOL_PAGES as usize * PAGE) }) } @@ -3290,6 +3326,15 @@ pub unsafe fn place_pages( if console_has_packed_3d_mips(desc) { return None; } + // a texture of less than 64 KiB that does not alias a live page: a block of a shared heap + // (`vram_small`), with no reserved resource and no tile mappings of its own + let aliases_live = va % PAGE == 0 && has_live_page(dev.as_raw() as usize, canonical_va(va)); + if !aliases_live { + if let Some(hr) = super::vram_small::place(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { + PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + return Some(hr); + } + } // (one slice: the tiles of an array's packed levels are not asked about here) let lazy = level_pages() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.DepthOrArraySize == 1 && desc.SampleDesc.Count == 1 && desc.Flags == D3D12_RESOURCE_FLAG_NONE; // (as `place`: without a size every PC tile went on the title's pages from `va` on) diff --git a/crates/xcl/src/hle/d3d12x/vram_small.rs b/crates/xcl/src/hle/d3d12x/vram_small.rs index 79df43a8ba..807eed4c21 100644 --- a/crates/xcl/src/hle/d3d12x/vram_small.rs +++ b/crates/xcl/src/hle/d3d12x/vram_small.rs @@ -366,3 +366,313 @@ pub(super) fn flush_idle_for(device: usize) { p.flush_idle(Instant::now()); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn small_pool_packs_shares_and_recycles_by_size_class() { + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let mut p: SmallPools = SmallPools::new(); + let alloc = |p: &mut SmallPools, va: usize, units: u32, res: usize, now: Instant| -> (u32, u32) { + let got = p.try_acquire((va, units), now).unwrap_or_else(|| { + let id = p.pools.len() as u32; + p.add_pool_and_acquire(id, (va, units), now) + }); + p.note_resource(res, (va, units)); + got + }; + + // Sixteen 4 KiB textures pack into 64 KiB (not 16 * 64 KiB = 1 MiB). + for i in 0..16usize { + let (h, off) = alloc(&mut p, 0x10_0000 + i * UNIT, 1, 100 + i, at(0)); + assert_eq!((h, off), (0, i as u32)); + } + assert_eq!(p.bytes(), (16 * UNIT, POOL_UNITS as usize * UNIT)); + + // Re-placing the exact same (va, units) shares the exact same (heap, offset) with zero growth. + let (h_dup, off_dup) = alloc(&mut p, 0x10_4000, 1, 200, at(10)); + assert_eq!((h_dup, off_dup), (0, 4)); + assert_eq!(p.bytes().0, 16 * UNIT); + + // Releasing one of the two aliases keeps the slot alive; releasing both makes it idle. + assert!(p.forget(200, at(20))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 1); + assert!(p.forget(104, at(30))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 0); + + // Re-acquiring within IDLE reuses the exact same slot. + let (h_re, off_re) = alloc(&mut p, 0x10_4000, 1, 201, at(1000)); + assert_eq!((h_re, off_re), (0, 4)); + assert!(p.forget(201, at(1100))); + + // After IDLE (2 s) + COOL (2 s), the 4 KiB block is recycled for a new address. + let (h_wait, off_wait) = alloc(&mut p, 0x20_0000, 1, 202, at(3200)); + assert_eq!((h_wait, off_wait), (0, 16), "still cooling at +2.1s, must not reuse yet"); + let (h_rec, off_rec) = alloc(&mut p, 0x20_1000, 1, 203, at(5300)); + assert_eq!((h_rec, off_rec), (0, 4), "block (0, 4) recycled after IDLE + COOL"); + + // Rollback on creation failure immediately returns the block to the free list. + let (h_fail, off_fail) = p.try_acquire((0x30_0000, 4), at(5400)).unwrap(); + assert_eq!((h_fail, off_fail), (0, 17)); + p.release_key((0x30_0000, 4), at(5400), true); + let (h_next, off_next) = alloc(&mut p, 0x30_4000, 4, 204, at(5400)); + assert_eq!((h_next, off_next), (0, 17)); + + // Concurrent CreateHeap race: if room already exists in pool 0, `add_pool_and_acquire` + // must reuse existing room instead of pushing a redundant empty 16 MiB pool. + let pools_before = p.pools.len(); + let (h_raced, _) = p.add_pool_and_acquire(999, (0x40_0000, 1), at(5500)); + assert_eq!(h_raced, 0); + assert_eq!(p.pools.len(), pools_before, "must not push redundant pool when room already exists"); + + // `flush_idle` clears unreferenced idle slots while keeping live (`users > 0`) slots intact. + let used_before_flush = p.bytes().0; + let _ = alloc(&mut p, 0x50_0000, 2, 205, at(5600)); + assert!(p.forget(205, at(5610))); + assert_eq!(p.bytes().0, used_before_flush + 2 * UNIT); + p.flush_idle(at(5620)); + assert_eq!(p.bytes().0, used_before_flush, "flush_idle must reclaim unreferenced slots immediately"); + } + + #[test] + fn candidate_filters_large_gpu_owned_and_msaa_textures() { + let mut d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(candidate(&d, Some(16 * 1024))); + assert!(!candidate(&d, Some(64 * 1024)), "64 KiB stays on vram::Pages"); + assert!(!candidate(&d, None)); + assert!(!candidate(&d, Some(0))); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + assert!(!candidate(&d, Some(16 * 1024))); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + d.SampleDesc.Count = 4; + assert!(!candidate(&d, Some(16 * 1024))); + d.SampleDesc.Count = 1; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + assert!(!candidate(&d, Some(16 * 1024))); + } + + /// On the GPU: 512 small 4 KiB (64x64 BC1) and 16 KiB (64x64 RGBA8) sampled textures pack at + /// 4 KiB granularity inside a single 16 MiB heap (16x and 4x smaller than 64 KiB tiles), + /// same-address placements alias their pixels on hardware, adjacent 4 KiB textures have zero + /// crosstalk, and a small sampled texture over an existing 64 KiB GPU target falls back to + /// `vram::Pages` so target aliasing is preserved. + #[test] + fn gpu_small_textures_pack_at_4k_granularity_and_preserve_pixels() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().expect("DXGI factory"); + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let mut dev: Option = None; + for (adapter, _) in crate::gpu::adapter::candidates(&factory, &sel) { + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() && dev.is_some() { + break; + } + } + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.ResourceHeapTier.0 < 2 + { + crate::gpu::recomp::runner::skip_test(&format!("resource heap tier {} < 2", opts.ResourceHeapTier.0)); + return; + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + + let desc_of = |w: u64, h: u32, fmt: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + ..Default::default() + }; + let place_sampled = |va: usize, d: &D3D12_RESOURCE_DESC, cbytes: u64| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::vram::place_pages(dev.as_raw(), va, d, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(cbytes), riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "place_pages at {va:#x} failed: {hr:x?}"); + assert!(super::super::vram::is_placed_texture(p as usize)); + ID3D12Resource::from_raw(p) + }; + + // 1. 512 x 64x64 BC1 (2 KiB on console -> 4 KiB small resource on PC): must pack into + // 2 MiB (16x smaller than 512 x 64 KiB = 32 MiB!) inside a single 16 MiB heap. + super::super::vram::flush_idle_for(dev_key); + let bc1 = desc_of(64, 64, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE); + let bc1_info = dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..bc1 }]); + if bc1_info.SizeInBytes == u64::MAX || bc1_info.SizeInBytes == 0 || bc1_info.Alignment != UNIT as u64 || bc1_info.SizeInBytes >= 0x1_0000 { + crate::gpu::recomp::runner::skip_test(&format!( + "adapter does not support 4 KiB small-resource placement for 64x64 BC1 (align={}, size={})", + bc1_info.Alignment, bc1_info.SizeInBytes + )); + return; + } + let (small0, _) = bytes_for(dev_key); + let (pages0, _) = super::super::vram::page_bytes_for(dev_key); + let bc1_base = 0x60_0000_0000usize; + let mut bc1_res = Vec::with_capacity(512); + for k in 0..512usize { + bc1_res.push(place_sampled(bc1_base + k * 0x1000, &bc1, 2048)); + } + let (small_after_bc1, small_pool_after_bc1) = bytes_for(dev_key); + let bc1_small_delta = small_after_bc1 - small0; + // (`vram::page_bytes_for` counts the 64 KiB pages alone on this branch) + let bc1_page_delta = super::super::vram::page_bytes_for(dev_key).0 - pages0; + println!("512 x 64x64 BC1: +{bc1_small_delta} B in small pools (pool={small_pool_after_bc1} B), +{bc1_page_delta} B of 64 KiB pages (vs 33554432 B as 64 KiB tiles)"); + assert_eq!(bc1_small_delta, 512 * UNIT, "each 64x64 BC1 must take 4 KiB in small pool"); + assert_eq!(bc1_page_delta, 0, "zero 64 KiB Pages tiles allocated for 4 KiB BC1 textures"); + drop(bc1_res); + + // 2. Hardware upload + readback: two adjacent 64x64 RGBA8 (16 KiB) textures and a + // same-address alias verify zero crosstalk and exact pixel sharing on the GPU. + super::super::vram::flush_idle_for(dev_key); + let rgba = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + let rgba_info = dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..rgba }]); + if rgba_info.SizeInBytes != 16384 || rgba_info.Alignment != UNIT as u64 { + crate::gpu::recomp::runner::skip_test(&format!( + "step 2: adapter does not support 4 KiB 16 KiB placement for 64x64 RGBA8 (align={}, size={})", + rgba_info.Alignment, rgba_info.SizeInBytes + )); + return; + } + let va_a = 0x61_0000_1000usize; + let va_b = 0x61_0000_5000usize; + let a1 = place_sampled(va_a, &rgba, 16384); + let (small_after_a1, _) = bytes_for(dev_key); + let a2 = place_sampled(va_a, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_after_a1, "same-va small texture must share slot"); + let b = place_sampled(va_b, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0 - small_after_a1, 16384, "64x64 RGBA8 must take 16 KiB"); + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fill_a = vec![0x3Cu8; 64 * 64 * 4]; + let fill_b = vec![0xA5u8; 64 * 64 * 4]; + let sub = |data: Vec| crate::gpu::texture::Subresource { rows: 64, row_bytes: 64 * 4, depth: 1, data }; + // (this branch has no `texture::upload_batch`: one upload each) + for (res, fill) in [(&a2, &fill_a), (&b, &fill_b)] { + crate::gpu::texture::upload(&dev, &queue, res, &[sub(fill.clone())], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COMMON).expect("upload failed"); + } + + let readback_tex = |r: &ID3D12Resource| -> Vec { + let rd = r.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb, + ).unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + }; + + assert_eq!(readback_tex(&a1), fill_a, "same-va alias a1 must see pixels uploaded to a2"); + assert_eq!(readback_tex(&b), fill_b, "adjacent 4 KiB texture b must not crosstalk with a"); + drop((b, a2, a1)); + + // 3. A small sampled texture at a 64 KiB-aligned va occupied by an existing GPU-owned + // render target must stay on vram::Pages (not vram_small) so it aliases the target. + if opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 { + crate::gpu::recomp::runner::skip_test(&format!("step 3: tiled resources tier {} < 2", opts.TiledResourcesTier.0)); + return; + } + super::super::vram::flush_idle_for(dev_key); + let rt_va = 0x62_0000_0000usize; + let rt_desc = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let mut rt_raw = std::ptr::null_mut(); + let hr = super::super::vram::place(dev.as_raw(), rt_va, &rt_desc, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), Some(16384), riid, &mut rt_raw); + assert!(hr.is_some_and(|h| h >= 0) && !rt_raw.is_null()); + let rt = ID3D12Resource::from_raw(rt_raw); + let small_before_alias = bytes_for(dev_key).0; + let sampled_view = place_sampled(rt_va, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_before_alias, "sampled view over live GPU target must alias vram::Pages, not vram_small"); + drop((sampled_view, rt)); + } + } + + #[test] + fn small_pool_blocks_recycle_until_gpu_fence_completes_even_after_cool() { + use std::sync::{atomic::{AtomicBool, Ordering}, Arc}; + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let gpu_done = Arc::new(AtomicBool::new(false)); + let mut p: SmallPools> = SmallPools::new(); + + let (h0, off0) = p.add_pool_and_acquire_with(1, (0x1000, 2), at(0), || gpu_done.clone(), |d| d.load(Ordering::Acquire)); + assert_eq!((h0, off0), (1, 0)); + p.note_resource(0x2001, (0x1000, 2)); + assert!(p.forget(0x2001, at(10))); + + p.sweep_idle_with(at(2_500), || gpu_done.clone()); + let (h1, off1) = p.try_acquire_with((0x2000, 2), at(12_500), || gpu_done.clone(), |d| d.load(Ordering::Acquire)).unwrap(); + assert_eq!((h1, off1), (1, 2), "must not alias cooling small-pool block before GPU fence completes"); + + gpu_done.store(true, Ordering::Release); + let (h2, off2) = p.try_acquire_with((0x3000, 2), at(12_600), || gpu_done.clone(), |d| d.load(Ordering::Acquire)).unwrap(); + assert_eq!((h2, off2), (1, 0)); + } + + #[test] + fn candidate_accepts_small_texture1d_for_4k_small_pool() { + let mut d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE1D, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(candidate(&d, Some(4096)), "small sampled TEXTURE1D must qualify for 4 KiB SmallPools"); + assert!(!candidate(&d, Some(64 * 1024)), "64 KiB TEXTURE1D stays on default placement"); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + assert!(!candidate(&d, Some(4096)), "UAV TEXTURE1D must not enter SmallPools"); + } +} From 8ea8524f347be583ed662b9a695521baa9bf8c45 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:04:37 +0100 Subject: [PATCH 151/175] Memory: level pages, small textures and 64 MB of upload buffers by default Restores amd-dev's memory defaults, which the main -> amd-dev merge (#3444) left at main's: - XCL_TEXTURE_LEVEL_PAGES: on unless 0 (amd-dev 8942a5b9; main: only with 1). A sampled texture's levels get pages when an upload first has texels for them: a retail title's 32,000 textures standing for 18 GB held 1.3 GB of pages with it. With it comes amd-dev's guard (6fa964de) that main did not have: a sampled view over a live 64 KiB page (a render target's, has_live_page) maps all of its levels at once, since its texels come from the GPU and no upload would ever map them (should_use_lazy_levels). - XCL_SMALL_TEXTURES: on unless set to something else than 1 (amd-dev 8942a5b9; main: only with 1), still off in unit tests unless a test asks for it. - XCL_UPLOAD_KEEP_MB: back, 64 MB of idle texture upload buffers kept by default (amd-dev a68f609f; main keeps 512 MB, with no switch). Upload heaps are commit and RAM while kept. README says so, in amd-dev's words. --- README.md | 17 +++-- crates/xcl/src/hle/d3d12x/small_tex.rs | 26 +++++-- crates/xcl/src/hle/d3d12x/texture_upload.rs | 23 +++++- crates/xcl/src/hle/d3d12x/vram.rs | 79 ++++++++++++++++----- 4 files changed, 115 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 393fbd7ff5..1f67ee7a60 100644 --- a/README.md +++ b/README.md @@ -404,8 +404,9 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. those on which the GPU completed at least one operation. For each, it names the translated pipeline bound at the last operation DRED saw complete and those bound after it, by their console shaders' hashes (`cs`, `vs` / `ps`, `ms` / `ps`, `vs` / `gs` / `ps`). -- `XCL_TEXTURE_LEVEL_PAGES=1` gives sampled title textures backing as their mip levels stream in. - Zero-filled mip uploads in a batch share one staging span and still clear any mapped tiles. +- Sampled title textures get backing as their mip levels stream in (`XCL_TEXTURE_LEVEL_PAGES=0`: + all levels at once). Zero-filled mip uploads in a batch share one staging span and still clear + any mapped tiles. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. @@ -420,11 +421,13 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. reduces avoidable backing, not the memory needed by live GPU mappings, and is not a VRAM budget cap. - Memory on 32 GB PCs: Windows charges every byte of video memory to the system's commit (RAM + - page file), so video memory XCL does not need counts like RAM. These keep it down (opt-in): a - streamed texture's levels get video memory when they are loaded (`XCL_TEXTURE_LEVEL_PAGES=1`), - and small sampled textures share 4 KiB placements (`XCL_SMALL_TEXTURES=1`). Shader preparation - starts no more workers than the RAM available holds (2 GB each, 4 GB left over) and the commit - left (3 GB each); `XCL_PREPARE_WORKERS=N` sets the number. + page file), so video memory XCL does not need counts like RAM. These are on by default to keep + it down: a streamed texture's levels get video memory when they are loaded + (`XCL_TEXTURE_LEVEL_PAGES=0` gives every level its memory at once), small sampled textures share + 4 KiB placements (`XCL_SMALL_TEXTURES=0`: a committed resource each), and 64 MB of idle texture + upload buffers are kept (`XCL_UPLOAD_KEEP_MB`). Shader preparation starts no more workers than + the RAM available holds (2 GB each, 4 GB left over) and the commit left (3 GB each); + `XCL_PREPARE_WORKERS=N` sets the number. - Every run writes `report.json` (called stubs, unknown D3D12.X slots and interfaces, XGameRuntime classes asked for, shader statistics, audio formats, crash). `d3d12.presents` counts presentations, not visible content. With `XCL_FRAME_DUMP=N` (`N > 1`), diff --git a/crates/xcl/src/hle/d3d12x/small_tex.rs b/crates/xcl/src/hle/d3d12x/small_tex.rs index 0a2ba2a855..e183918471 100644 --- a/crates/xcl/src/hle/d3d12x/small_tex.rs +++ b/crates/xcl/src/hle/d3d12x/small_tex.rs @@ -1,8 +1,8 @@ //! Small sampled textures of the title that get no shared pages (`vram::place_pages` refuses them: //! a 1D texture cannot be a reserved resource) on 4 KiB placements in heaps of XCL's own -//! (`XCL_SMALL_TEXTURES=1`), instead of a committed resource each: a committed resource takes at -//! least 64 KiB of video memory, and a title's thousands of tiny lookup textures (a few hundred -//! bytes each) took ~300 MiB that way. +//! (on by default, `XCL_SMALL_TEXTURES=0` turns it off), instead of a committed resource each: a +//! committed resource takes at least 64 KiB of video memory, and a title's thousands of tiny +//! lookup textures (a few hundred bytes each) took ~300 MiB that way. //! //! Only what the PC itself allows: no render target, depth or UAV flags, one sample, and //! `GetResourceAllocationInfo` giving `D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT` (4 KiB) for the @@ -29,10 +29,16 @@ const UNIT: u64 = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64; const HEAP_BYTES: u64 = 4 << 20; const UNITS: usize = (HEAP_BYTES / UNIT) as usize; -/// Whether small sampled textures go on 4 KiB placements (`XCL_SMALL_TEXTURES=1`). +/// Whether small sampled textures go on 4 KiB placements: on by default (`XCL_SMALL_TEXTURES=0` +/// turns it off), off in unit tests unless they ask for it. pub(super) fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_SMALL_TEXTURES").is_ok_and(|v| v.trim() == "1")) + *ON.get_or_init(|| switch_on(std::env::var("XCL_SMALL_TEXTURES").ok().as_deref(), !cfg!(test))) +} + +/// `XCL_SMALL_TEXTURES` as set (`1`: on, anything else: off), `unset` when it is not. +fn switch_on(v: Option<&str>, unset: bool) -> bool { + v.map_or(unset, |v| v.trim() == "1") } /// The units of one heap: first fit of a run of `n`. @@ -185,6 +191,16 @@ mod tests { use super::*; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_SAMPLE_DESC}; + /// On by default (amd-dev's default), `XCL_SMALL_TEXTURES=0` (or anything but `1`) turns it off. + #[test] + fn small_textures_are_on_unless_turned_off() { + assert!(switch_on(None, true), "unset outside unit tests: on"); + assert!(!switch_on(None, false), "unset in unit tests: off"); + assert!(switch_on(Some(" 1 "), false)); + assert!(!switch_on(Some("0"), true)); + assert!(!switch_on(Some("yes"), true)); + } + /// Units go first fit and come back: a freed run is taken again, a run longer than any gap is not. #[test] fn units_are_taken_first_fit_and_given_back() { diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index 5ed7b4e883..ae1b0a4590 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -860,7 +860,17 @@ fn capacity(bytes: u64) -> Option { } } -const FREE_BYTES: u64 = 512 << 20; +/// The most bytes of idle upload buffers kept for the next batches (`XCL_UPLOAD_KEEP_MB`, default +/// 64): memory of the system's (upload heaps), the process's commit and RAM while kept. (A +/// retail title's world ran with 64 MB kept: ~60 MB idle, a few MB in flight.) +fn free_bytes() -> u64 { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| keep_bytes_of(std::env::var("XCL_UPLOAD_KEEP_MB").ok().as_deref())) +} + +fn keep_bytes_of(v: Option<&str>) -> u64 { + v.and_then(|v| v.trim().parse::().ok()).map_or(64, |mb| mb.min(4096)) << 20 +} /// A job whose buffer takes `bytes` bytes. unsafe fn take(dev: &ID3D12Device, bytes: u64) -> Result { @@ -922,7 +932,7 @@ pub(super) fn give_back(job: Job) { let mut g = FREE.lock().unwrap(); g.push(job); // (the biggest goes first: one burst does not keep its buffers for good) - while g.iter().map(|j| j.bytes).sum::() > FREE_BYTES { + while g.iter().map(|j| j.bytes).sum::() > free_bytes() { let Some(i) = g.iter().enumerate().max_by_key(|(_, j)| j.bytes).map(|(i, _)| i) else { break }; gone.push(g.swap_remove(i)); } @@ -969,6 +979,15 @@ pub(super) unsafe fn submit(dev: &ID3D12Device, queue: &ID3D12CommandQueue, item mod tests { use super::*; + #[test] + fn the_idle_upload_buffers_kept_follow_the_switch() { + assert_eq!(keep_bytes_of(None), 64 << 20, "unset: 64 MB"); + assert_eq!(keep_bytes_of(Some(" 512 ")), 512 << 20); + assert_eq!(keep_bytes_of(Some("0")), 0, "none kept"); + assert_eq!(keep_bytes_of(Some("lots")), 64 << 20); + assert_eq!(keep_bytes_of(Some("100000")), 4096 << 20); + } + /// The written pages of a texture are compared one by one: a page never compared has changed, /// one that holds what it held has not, the bytes next to the texture on its first and last /// page are not the texture's, and a texture nothing is known of changed as a whole. diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index f268af0419..bd38da69ad 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1117,24 +1117,32 @@ fn take_level_tiles(levels: Option<&mut Levels>) -> Vec<(Vec, Vec<(usize, .unwrap_or_default() } -/// `XCL_TEXTURE_LEVEL_PAGES=1` (off by default): a sampled 2D texture of one slice on the -/// shared pages gets the pages of a level when an upload first has texels for it. A retail game -/// places its streamed textures at full size and maps memory under their levels as it loads -/// them, the small ones first; with a page for every 64 KiB a texture covers most of the pages -/// are for levels that are not loaded. +/// Level pages (on by default, `XCL_TEXTURE_LEVEL_PAGES=0` turns them off): a sampled 2D texture +/// of one slice on the shared pages gets the pages of a level when an upload first has texels for +/// it. A retail game places its streamed textures at full size and maps memory under their levels +/// as it loads them, the small ones first; with a page for every 64 KiB a texture covers most of +/// the pages are for levels that are not loaded (its world: 32,000 textures standing for 18 GB +/// held 1.3 GB of pages – and video memory is charged to the system's commit like RAM). pub(super) fn level_pages() -> bool { + // (a test chooses with `LEVEL_PAGES_FOR_TEST`) #[cfg(test)] - if LEVEL_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { - return true; + return LEVEL_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = level_pages_on(std::env::var("XCL_TEXTURE_LEVEL_PAGES").ok().as_deref()); + if !on { + crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=0 - a sampled texture gets video memory pages for all of its levels at once"); + } + on + }) } - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - let on = std::env::var("XCL_TEXTURE_LEVEL_PAGES").is_ok_and(|v| v.trim() == "1"); - if on { - crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=1 - a sampled texture's levels get their video memory pages when an upload first has texels for them"); - } - on - }) +} + +/// `XCL_TEXTURE_LEVEL_PAGES` as set: on unless it is `0`. +fn level_pages_on(v: Option<&str>) -> bool { + v.is_none_or(|v| v.trim() != "0") } /// `level_pages` for a test (under `VRAM_TEST_LOCK`) @@ -3305,6 +3313,20 @@ fn tier2(dev: &ID3D12Device) -> bool { unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.ResourceHeapTier.0 >= 2 } } +/// Whether a sampled reserved texture should defer tile mapping per mip level (`level_pages`). +/// Sampled views aliasing an already-live 64 KiB GPU page (`aliases_live`, e.g., an SRV placed +/// over a render target, depth buffer, or Hi-Z UAV pyramid) must map immediately onto those live +/// pages rather than staying lazy: their CPU memory is zeros so upload-driven level mapping +/// would leave every tile unmapped. +fn should_use_lazy_levels(level_pages_on: bool, aliases_live: bool, desc: &D3D12_RESOURCE_DESC) -> bool { + !aliases_live + && level_pages_on + && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && desc.DepthOrArraySize == 1 + && desc.SampleDesc.Count == 1 + && desc.Flags == D3D12_RESOURCE_FLAG_NONE +} + /// A sampled texture of the title at `va` (`desc`: the PC description, `console_bytes` its size on /// the console) backed by shared 64 KiB video-memory pages; None when reserved placement is not /// available (the caller falls back to a committed resource). @@ -3336,7 +3358,7 @@ pub unsafe fn place_pages( } } // (one slice: the tiles of an array's packed levels are not asked about here) - let lazy = level_pages() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.DepthOrArraySize == 1 && desc.SampleDesc.Count == 1 && desc.Flags == D3D12_RESOURCE_FLAG_NONE; + let lazy = should_use_lazy_levels(level_pages(), aliases_live, desc); // (as `place`: without a size every PC tile went on the title's pages from `va` on) let console_bytes = console_bytes.or_else(|| { let least = least_texture_bytes(desc); @@ -4727,6 +4749,31 @@ mod tests { assert_eq!(recycled, vec![(0, 3)], "the rolled-back recycled tile still needs zeroing"); } + /// Level pages are on unless `XCL_TEXTURE_LEVEL_PAGES=0`, and a sampled view over a live page + /// (a render target's) maps all of its levels at once: its texels come from the GPU. + #[test] + fn level_pages_are_on_by_default_but_not_for_a_view_over_a_live_page() { + assert!(level_pages_on(None), "unset: on"); + assert!(level_pages_on(Some("1"))); + assert!(!level_pages_on(Some(" 0 ")), "0: off"); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 512, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 10, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(should_use_lazy_levels(true, false, &desc)); + assert!(!should_use_lazy_levels(true, true, &desc), "a view over a live page maps at once"); + assert!(!should_use_lazy_levels(false, false, &desc)); + let target = D3D12_RESOURCE_DESC { Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..desc }; + assert!(!should_use_lazy_levels(true, false, &target)); + let array = D3D12_RESOURCE_DESC { DepthOrArraySize: 6, ..desc }; + assert!(!should_use_lazy_levels(true, false, &array)); + } + #[test] fn coalesce_tile_runs_merges_adjacent_tiles_per_heap() { let mut tiles = vec![(1, 5), (0, 3), (0, 2), (1, 6), (0, 3), (0, 10), (1, 4)]; From 737588b88a856de1532e1fc2225d771a531238b9 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:33:59 +0100 Subject: [PATCH 152/175] Recompiler: heap windows read without a branch in every stage again The main merge took main's limit of HEAP_FLAT (one-path heap-window reads) to compute programs (2f523330, e8f7164b); amd-dev read every stage flat. With a branch per memory access in a pixel shader, AMD's compiler ran the S#-index arithmetic (`& 0x7FF`) for the live lanes only and then took the quad helper lanes into the sampler waterfall: their stale index (0xf99aec80) read a sampler past the heap. Page fault and TDR on world entry (RX 9070 XT, Radeon GPU Detective dump of sync-r12; the same shader was cached as ..._Pixel_0_784_1 by amd-dev and ..._Pixel_0_272_1 by the merge). Every stage reads the heap windows flat with HEAP_FLAT again, and the flag stays in every stage's translation cache key. --- crates/xcl/src/gpu/dxil/kernel.rs | 22 +++++++++++++--------- crates/xcl/src/gpu/recomp/pso.rs | 15 ++++++++------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index e1cffb851f..458bb53ca2 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -306,24 +306,28 @@ pub(crate) fn translate_geometry_unrefused(code: &[u8], o: KernelOptions, g: &Gs translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None) } -/// Whether `entry` uses the measured, one-path heap-window read form. Graphics, mesh and -/// geometry stages retain the guarded form until they have stage-specific measurements. -fn reads_heap_flat(entry: &Entry, heap: bool, mem_windows: u32) -> bool { - heap && matches!(entry, Entry::Kernel | Entry::Compute(_)) && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0 +/// Whether `entry` uses the one-path heap-window read form: every stage with `HEAP_FLAT`. +/// The guarded form (a branch per access) in a pixel shader let AMD's compiler run the +/// S#-index arithmetic for the live lanes alone and then take helper lanes into the sampler +/// waterfall: their stale index read a sampler past the heap, a page fault and a TDR on world +/// entry (RX 9070 XT, sync-r12). amd-dev ran every stage flat. +fn reads_heap_flat(_entry: &Entry, heap: bool, mem_windows: u32) -> bool { + heap && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0 } #[cfg(test)] #[test] -fn only_compute_programs_read_heap_windows_flat() { +fn every_stage_reads_heap_windows_flat() { use crate::gpu::recomp::{GsInterface, MsInterface, HEAP_FLAT, HEAP_WINDOWS}; let flat = 4 | HEAP_WINDOWS | HEAP_FLAT; assert!(reads_heap_flat(&Entry::Kernel, true, flat)); assert!(reads_heap_flat(&Entry::Compute(CsInterface::default()), true, flat)); - assert!(!reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat)); - assert!(!reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat)); - assert!(!reads_heap_flat(&Entry::Vertex(VsInterface::default()), true, flat)); - assert!(!reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, flat)); + assert!(reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat)); + assert!(reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat)); + assert!(reads_heap_flat(&Entry::Vertex(VsInterface::default()), true, flat)); + assert!(reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, flat)); assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), true, 4 | HEAP_WINDOWS)); + assert!(!reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, 4 | HEAP_WINDOWS)); assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), false, flat)); } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ec224979c3..4228ee3e3e 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -157,9 +157,11 @@ fn windows_for_mode(n: u32, heap: bool) -> u32 { } } -/// `HEAP_FLAT` changes only compute translation; other stages keep their existing cache identity. -fn windows_for_stage(windows: u32, stage: Stage) -> u32 { - if stage == Stage::Compute { windows } else { windows & !super::HEAP_FLAT } +/// The windows `stage` translates with: `HEAP_FLAT` reaches every stage (the direct DXIL +/// translator reads the heap windows of all of them without a branch: `reads_heap_flat`), so +/// it stays in every stage's cache keys. +fn windows_for_stage(windows: u32, _stage: Stage) -> u32 { + windows } thread_local! { @@ -2180,11 +2182,10 @@ mod shader_cache_tests { } #[test] - fn heap_flat_partitions_only_compute_cache_keys() { + fn heap_flat_stays_in_every_stage_cache_key() { let windows = 4 | super::super::HEAP_WINDOWS | super::super::HEAP_FLAT; - assert_eq!(windows_for_stage(windows, Stage::Compute), windows); - for stage in [Stage::Vertex, Stage::Pixel, Stage::Mesh] { - assert_eq!(windows_for_stage(windows, stage), windows & !super::super::HEAP_FLAT); + for stage in [Stage::Compute, Stage::Vertex, Stage::Pixel, Stage::Mesh] { + assert_eq!(windows_for_stage(windows, stage), windows); } } From 859e8ad2d0218de246986245ff9653d82cb4d13e Mon Sep 17 00:00:00 2001 From: lucsoft Date: Mon, 30 Nov 2026 17:50:53 +0100 Subject: [PATCH 153/175] ambient: find the stand-in's passes and build its helpers under Wine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The stand-in lighting (XCL_RT_GATE=miss + XCL_AMBIENT) never applied on this merge: no "captured … sky dome" or "applied" line in any run, so every missed ray brought the sky's light indoors (overexposure, sparkles in hair and skin, white specks). Three causes: - Merge regression: main's ExecuteIndirect runs split programs through dispatch_chain::execute_indirect and returns before the ambient hook; amd-dev had no such branch. The chain path now calls the hook too. - Roles were looked up by the resolved PC pipeline, which lazy and background builds replace with other objects. Roles are now noted at the title's own CreatePipelineState, looked up by the bound pipeline and, failing that, by the console record (fnv64 of the CS). - The helper programs (SKY_REDUCE, AMBIENT_FILL, LIGHT_PLACE, …) were compiled with D3DCompile, which under Wine is vkd3d-shader and refuses them, so get_device made no device and every pass returned silently. They, and the depth UAV twins', present compositor's and mirror's helpers, now compile with DXC first (dxc::compile_sm6_first, x_5_x as x_6_0), D3DCompile as the fallback, and a refusal is logged. scatter's program stays on D3DCompile: built with DXC it scattered the title's writes to the wrong places. XCL_AMBIENT_DIAG=1 logs the path and role each lighting pass takes. --- crates/xcl/src/gpu/recomp/dxc.rs | 15 ++++ crates/xcl/src/hle/d3d12x/ambient.rs | 101 ++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/bind.rs | 20 +++-- crates/xcl/src/hle/d3d12x/depth_uav.rs | 3 + crates/xcl/src/hle/d3d12x/mirror.rs | 3 + crates/xcl/src/hle/d3d12x/present.rs | 3 + crates/xcl/src/hle/d3d12x/pso_async.rs | 5 ++ crates/xcl/src/hle/d3d12x/real.rs | 23 ++++++ 8 files changed, 164 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 782bb1710d..fc5606bbc6 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -875,6 +875,21 @@ fn pool() -> &'static Arc { } /// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments. +/// A helper program XCL used to give `D3DCompile` (`x_5_0`): compiled with DXC as `x_6_0`. +/// Under Wine `D3DCompile` is vkd3d-shader's HLSL compiler, which refuses several of them, and +/// each caller then switched its feature off without a word. None: DXC refused it too (the +/// caller tries `D3DCompile`). +pub fn compile_sm6_first(src: &str, entry: &str, target: &str) -> Option> { + let t = target.replacen("_5_0", "_6_0", 1).replacen("_5_1", "_6_0", 1); + match compile(src, entry, &t, &[]) { + Ok(b) => Some(b), + Err(e) => { + crate::xlog_warn!("DXC: a helper program ({entry}, {t}) does not compile: {e}; trying D3DCompile"); + None + } + } +} + pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let (reply, rx) = std::sync::mpsc::channel(); let job = Job { diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 3e510ca48f..b8287f2987 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -358,16 +358,20 @@ pub(super) fn is_ambient_compute(blob: &[u8]) -> bool { classify_cs(blob).is_some() } +/// roles by the console record (`fnv64` of the CS), for pipelines whose pointer was never noted +static RECORD_ROLES: RwLock>> = RwLock::new(None); + pub(super) fn note_compute_pso(pso: usize, cs: &[u8]) { if pso == 0 || !enabled() { return; } if let Some(role) = classify_cs(cs) { + RECORD_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(crate::gpu::shader::fnv64(cs), role); PSO_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, role); HAS_CS_PSO.store(true, Ordering::Release); static LOGGED: AtomicU64 = AtomicU64::new(0); - if LOGGED.fetch_add(1, Ordering::Relaxed) < 8 { - crate::xlog_info!("D3D12.X: ambient: tracked {role:?} compute PSO {pso:#x}"); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 64 { + crate::xlog_info!("D3D12.X: ambient: tracked {role:?} compute PSO {pso:#x} (record {:016x})", crate::gpu::shader::fnv64(cs)); } } } @@ -389,6 +393,60 @@ fn role_of(pso: usize) -> Option { PSO_ROLES.read().unwrap().as_ref()?.get(&pso).copied() } +/// (local, `XCL_AMBIENT_DIAG`) a dispatch of one of the stand-in's passes reached `path`: logged +/// before any of the hook's conditions, to see which path the passes take +pub(super) fn diag_path(path: &str, resolved: usize, bound: usize, count_buf: usize, max: u32) { + static DIAG: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*DIAG.get_or_init(|| std::env::var_os("XCL_AMBIENT_DIAG").is_some()) { + return; + } + let by_record = |r: u64| RECORD_ROLES.read().unwrap().as_ref()?.get(&r).copied(); + let role = role_of(resolved).or(role_of(bound)).or_else(|| super::real::pso_record(resolved).and_then(by_record)).or_else(|| super::pso_async::record_of(bound).and_then(by_record)); + let Some(role) = role else { return }; + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed) + 1; + if k <= 32 || k.is_power_of_two() { + crate::xlog_info!("D3D12.X: ambient path #{k}: {role:?} via {path} (resolved {resolved:#x}, bound {bound:#x}, count buffer {count_buf:#x}, max {max})"); + } +} + +/// The pipeline a hook should look the role up by: `resolved` (the PC pipeline the work +/// runs with) when its role was noted, else `bound` (the title's pipeline). With lazy and +/// background builds the two differ, and roles were noted for one or the other: looking up only +/// the resolved one found no role at all, so the stand-in never ran. +pub(super) fn role_pso(resolved: usize, bound: usize) -> usize { + static DIAG: std::sync::OnceLock = std::sync::OnceLock::new(); + if *DIAG.get_or_init(|| std::env::var_os("XCL_AMBIENT_DIAG").is_some()) { + static CALLS: AtomicU64 = AtomicU64::new(0); + let k = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + if k <= 40 || k.is_power_of_two() { + let roles = PSO_ROLES.read().unwrap().as_ref().map_or(0, |m| m.len()); + crate::xlog_info!("D3D12.X: ambient diag #{k}: resolved {resolved:#x} role {:?} record {:x?}, bound {bound:#x} role {:?}, {roles} roles noted, active {}", role_of(resolved), super::real::pso_record(resolved), role_of(bound), active()); + } + } + if role_of(resolved).is_none() && role_of(bound).is_none() { + // neither pointer was noted: the console record of the resolved pipeline names it + let by_record = |r: u64| RECORD_ROLES.read().unwrap().as_ref()?.get(&r).copied().map(|role| (r, role)); + let role = super::real::pso_record(resolved).and_then(by_record).or_else(|| super::pso_async::record_of(bound).and_then(by_record)); + if let Some((record, role)) = role { + PSO_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(resolved, role); + static L: AtomicU64 = AtomicU64::new(0); + if L.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: ambient: {role:?} found by record {record:016x} for pipeline {resolved:#x}"); + } + } + return resolved; + } + if role_of(resolved).is_some() { + return resolved; + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: ambient: role found by the bound pipeline {bound:#x}, not the resolved {resolved:#x}"); + } + bound +} + /// Descriptor-heap view metadata indexed by BOTH console slot UMA address (`slot.at`, globally /// unique across all shader-visible and CPU-only heaps) and `GLOBAL` heap descriptor index /// (`slot.index` when hosted in `GLOBAL`) so both `CopyDescriptors*` and inline title `memcpy` @@ -689,7 +747,30 @@ unsafe impl Sync for AmbientDevice {} static DEVICES: Mutex>>>> = Mutex::new(None); +/// A helper program: DXC first (`cs_6_0`), then `D3DCompile`. Under Wine `D3DCompile` is +/// vkd3d-shader's HLSL compiler, which refuses some of these programs; a refused one left +/// `get_device` without a device and every pass of the stand-in returned without a word. fn compile_cs_sm5(src: &str) -> Option> { + match crate::gpu::recomp::dxc::compile(src, "main", "cs_6_0", &[]) { + Ok(dxil) => return Some(dxil), + Err(e) => { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ambient: a helper program does not compile with DXC ({e}); trying D3DCompile"); + } + } + } + let fxc = compile_cs_fxc(src); + if fxc.is_none() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ambient: a helper program compiles with neither DXC nor D3DCompile: no stand-in lighting"); + } + } + fxc +} + +fn compile_cs_fxc(src: &str) -> Option> { unsafe { let mut blob = None; let r = D3DCompile( @@ -1736,7 +1817,13 @@ pub(super) unsafe fn after_draw(list: *mut c_void, pso_resolved: usize) { return; } let Some(dev) = dev else { return }; - let Some(ad) = get_device(&dev) else { return }; + let Some(ad) = get_device(&dev) else { + static NO_DEV: AtomicU64 = AtomicU64::new(0); + if NO_DEV.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_warn!("D3D12.X: ambient: no stand-in device (its helper pipelines could not be made): pass left as it is"); + } + return; + }; let sky_raw = ad.sky_copy.as_raw() as usize; list_x::transition(list, rt0, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); @@ -2216,7 +2303,13 @@ pub(super) unsafe fn after_compute_dispatch( return; } let Some(dev) = dev else { return }; - let Some(ad) = get_device(&dev) else { return }; + let Some(ad) = get_device(&dev) else { + static NO_DEV: AtomicU64 = AtomicU64::new(0); + if NO_DEV.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_warn!("D3D12.X: ambient: no stand-in device (its helper pipelines could not be made): pass left as it is"); + } + return; + }; let sky_ready = ad.sky_ready.load(Ordering::Acquire); // (keeping the frame's light needs no sky) if !sky_ready && role != PassRole::Radiance { diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 722c9eb1a2..8771550554 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -4438,6 +4438,7 @@ unsafe fn execute_indirect_snapshot( if gfx && super::present::trace_frame() { trace_ui_draw(this, raw_pso, pso, true); } + super::ambient::diag_path("ExecuteIndirect", pso, raw_pso, count_buf, max); // a split compute program's one Dispatch-only command runs its chain (`dispatch_chain`) if compute && max == 1 && count_buf == 0 && signature.dispatch_only().is_some() { let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { @@ -4448,6 +4449,13 @@ unsafe fn execute_indirect_snapshot( Ok(true) => { ei_work(this, dispatches, super::targets::RAN); count(DISPATCHES); + // a split program's chain is the title's pass too: the stand-in lighting follows it + // as it follows the plain ExecuteIndirect below (main's chain path returned before + // that hook, so split lighting passes never got the stand-in) + if compute && super::ambient::has_compute_psos() && count_buf == 0 && max == 1 { + let (layout, root_args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, super::ambient::role_pso(pso, raw_pso), [0, 0, 0], layout.as_deref(), &root_args, view_heap, None); + } return; } Ok(false) => {} @@ -4556,7 +4564,7 @@ unsafe fn execute_indirect_snapshot( (b, off as u32) }); let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); - super::ambient::after_compute_dispatch(this, pso, [0, 0, 0], layout.as_deref(), &args, view_heap, indirect_args); + super::ambient::after_compute_dispatch(this, super::ambient::role_pso(pso, raw_pso), [0, 0, 0], layout.as_deref(), &args, view_heap, indirect_args); } } Err(e) => { @@ -4765,7 +4773,7 @@ pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: super::gpu_profile::end(this, t); if super::ambient::has_sky_psos() { let pso = super::pso_async::resolve(bound_pso); - super::ambient::after_draw(this, pso); + super::ambient::after_draw(this, super::ambient::role_pso(pso, bound_pso)); } } } @@ -4793,8 +4801,9 @@ pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, i super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); if super::ambient::has_sky_psos() { - let pso = super::pso_async::resolve(with(this, |s| s.pso)); - super::ambient::after_draw(this, pso); + let bound = with(this, |s| s.pso); + let pso = super::pso_async::resolve(bound); + super::ambient::after_draw(this, super::ambient::role_pso(pso, bound)); } } } @@ -5667,6 +5676,7 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f } } super::targets::note_dispatch(); + super::ambient::diag_path("Dispatch", super::pso_async::peek(bound_pso), bound_pso, 0, 1); let Some(pso) = resolve_pipeline(this as usize, bound_pso, resolution) else { super::targets::note_compute(bound_pso, super::targets::Dispatched::Direct([0; 3])); skip_untranslated_dispatch(bound_pso); @@ -5714,7 +5724,7 @@ pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, f count(DISPATCHES); if super::ambient::has_compute_psos() && groups[0] > 0 && groups[1] > 0 && groups[2] > 0 { let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); - super::ambient::after_compute_dispatch(this, pso, groups, layout.as_deref(), &args, view_heap, None); + super::ambient::after_compute_dispatch(this, super::ambient::role_pso(pso, bound_pso), groups, layout.as_deref(), &args, view_heap, None); } } Err(e) => { diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index c47bb55fa2..b4e08757db 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -1032,6 +1032,9 @@ unsafe impl Sync for SyncPipelines {} static SYNC_PIPELINES: Mutex>>> = Mutex::new(None); fn compile_sm5(src: &str, target: &str) -> Option> { + if let Some(b) = crate::gpu::recomp::dxc::compile_sm6_first(src, "main", target) { + return Some(b); + } unsafe { let mut blob = None; let t = format!("{target}\0"); diff --git a/crates/xcl/src/hle/d3d12x/mirror.rs b/crates/xcl/src/hle/d3d12x/mirror.rs index e4cf3f9211..b47448116c 100644 --- a/crates/xcl/src/hle/d3d12x/mirror.rs +++ b/crates/xcl/src/hle/d3d12x/mirror.rs @@ -293,6 +293,9 @@ float4 light(Corner at) : SV_Target { "#; fn compile(entry: &str, target: &str) -> Option> { + if let Some(b) = crate::gpu::recomp::dxc::compile_sm6_first(SOURCE, entry, target) { + return Some(b); + } unsafe { let mut blob = None; let (e, t) = (format!("{entry}\0"), format!("{target}\0")); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 60ec215f2a..b81280f6a2 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1133,6 +1133,9 @@ fn mark_pipe_drained(p: &mut Presenter) { } fn compile_fx(src: &str, target: &str) -> Option> { + if let Some(b) = crate::gpu::recomp::dxc::compile_sm6_first(src, "main", target) { + return Some(b); + } unsafe { let mut blob: Option = None; let t = format!("{target}\0"); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 00c05a4c49..901e6c1b13 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -10974,6 +10974,11 @@ fn resolve_pending(p: &Pending, pso: usize) -> usize { } } +/// the console record (`fnv64` of its CS) of the pipeline the title made as `pso`, when known +pub(super) fn record_of(pso: usize) -> Option { + entry(pso).map(|p| p.build.record).filter(|&r| r != 0) +} + /// `resolve` with no side effects (for a report): the real pipeline behind `pso` once built, /// else `pso` itself – no use noted, nothing sent to the workers. pub(super) fn peek(pso: usize) -> usize { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 279e2c0362..61f85fd167 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2815,6 +2815,12 @@ static TRANSLATED_GRAPHICS: Sharded<()> = Sharded::new(); /// `XCL_TRACE_FRAME`: the console VS and PS (their dump names' hashes) of a translated PSO. static PSO_SHADERS: Mutex>> = Mutex::new(None); +/// The console record of the compute pipeline `pso`, when XCL translated it (the stand-in +/// lighting finds a pass's role by it). +pub(super) fn pso_record(pso: usize) -> Option { + PSO_SHADERS.lock().unwrap().as_ref().and_then(|m| m.get(&pso)).map(|&(record, _)| record) +} + /// translated pipeline → its input layout as text (`XCL_TRACE_FRAME`) static PSO_LAYOUTS: Mutex>> = Mutex::new(None); @@ -5693,6 +5699,9 @@ fn dummy_mesh() -> Option<&'static (Vec, Vec)> { } pub(super) fn compile(src: &str, target: &str) -> Vec { + // D3DCompile only, unlike the other helpers (`dxc::compile_sm6_first`): built with DXC, + // scatter.rs's program put the title's writes in the wrong places (stretched triangles in the + // G-buffer); Wine's D3DCompile refuses it and its correct copy fallback runs unsafe { let mut blob = None; let t = format!("{target}\0"); @@ -9532,6 +9541,20 @@ unsafe fn go_background( let lazy = super::pso_async::lazy(); // one of the BVH builder's programs while its passes are left out: binds go on without it too let image_only = image_only || compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| super::bvh_spare::spared(b, desc))); + // the stand-in lighting's passes by the pipeline the title binds: the PC pipelines + // built for them later are other objects, so roles noted only there were never found + match &owned { + OwnedDesc::Compute(_, b) => { + if let Some(cs) = b.first() { + super::ambient::note_compute_pso(*ppv as usize, cs); + } + } + OwnedDesc::Graphics(_, b, ..) | OwnedDesc::Stream(_, _, b) => { + for blob in b.iter() { + super::ambient::note_graphics_pso(*ppv as usize, Some(&blob[..])); + } + } + } // (a graphics pipeline's shaders by name: one that draws once and is kept is waited for) let names = match &owned { OwnedDesc::Graphics(_, b, ..) | OwnedDesc::Stream(_, _, b) => stage_names(b, &parts), From 2f3d11351d5fc61786d62a1845cab8127f905728 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Mon, 30 Nov 2026 17:51:01 +0100 Subject: [PATCH 154/175] d3d12x: zero recycled page-pool tiles before a new texture uses them amd-dev zeroed pool tiles that an evicted or freed texture had used before mapping them into a new texture (XCL_ZERO_TARGET_PAGES, on by default). Taking main's vram.rs in the merge dropped that, so new render targets such as the screen-probe light history start out with another image's bytes, which shows up as block garbage in the lighting. Bring it back on main's page pool: TilePool marks tiles that come back from cooling, take_batch_recycled reports the marked ones it hands out, and bind_range zeroes them on the tile-mapping queue right before the UpdateTileMappings that gives them to the texture. One CopyBufferRegion per contiguous run, from a 1 MiB zeroed upload buffer into a buffer placed over the whole pool heap. Title queues already wait for the mapping fence in before_execute, so the zeros land before any work on the texture. A new heap's tiles are zeros already and are left alone. XCL_ZERO_TARGET_PAGES=0 turns it off; the zeroed tile count is logged at powers of two. --- crates/xcl/src/hle/d3d12x/vram.rs | 351 ++++++++++++++++++++++++++++-- 1 file changed, 334 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index c1402dd310..7761e5e2be 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -998,6 +998,8 @@ unsafe fn arena_heap(dev: &ID3D12Device, va: usize, size: usize, align: usize) - const PAGE: usize = 0x1_0000; /// pages of a video-memory pool heap (64 MiB) const POOL_PAGES: u32 = 1024; +/// `TilePool::recycled` words per heap. +const RECYCLED_WORDS: usize = (POOL_PAGES as usize).div_ceil(64); /// a page no target uses any more is kept this long for the next target at its address (with /// what it holds – a title may make a target again over memory it rendered to) const IDLE: std::time::Duration = std::time::Duration::from_secs(2); @@ -1400,6 +1402,9 @@ struct TilePool { free_by_heap: Vec>, /// Whether `free_by_heap[h]` must be sorted descending before popping. dirty_sort: Vec, + /// Per heap, the free tiles some texture used before: they hold its bytes and are zeroed + /// before a new texture gets them (`Pages::zero_recycled`). A new heap's tiles are zeros. + recycled: Vec<[u64; RECYCLED_WORDS]>, /// Fresh-allocation packing class for heap `h`. Shared address pages may give either class /// live owners here, so this is never proof that a heap is safe to evict. heap_evictable: Vec, @@ -1417,6 +1422,7 @@ impl TilePool { TilePool { free_by_heap: Vec::new(), dirty_sort: Vec::new(), + recycled: Vec::new(), heap_evictable: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::new(), @@ -1429,12 +1435,14 @@ impl TilePool { if idx >= self.free_by_heap.len() { self.free_by_heap.resize_with(idx + 1, Vec::new); self.dirty_sort.resize(idx + 1, false); + self.recycled.resize(idx + 1, [0; RECYCLED_WORDS]); self.live.resize(idx + 1, false); self.heap_evictable.resize(idx + 1, false); } debug_assert!(self.free_by_heap[idx].is_empty()); self.free_by_heap[idx] = (0..pool_pages).rev().collect(); self.dirty_sort[idx] = false; + self.recycled[idx] = [0; RECYCLED_WORDS]; self.live[idx] = true; self.heap_evictable[idx] = evictable; self.free_total += pool_pages as usize; @@ -1461,6 +1469,7 @@ impl TilePool { self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; + self.recycled[h] = [0; RECYCLED_WORDS]; self.live[h] = false; self.heap_evictable[h] = false; self.free_total -= full; @@ -1478,26 +1487,40 @@ impl TilePool { fn drain_cooling(&mut self, now: std::time::Instant) { while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { let Some(((h, t), _)) = self.cooling.pop_front() else { break }; - let idx = h as usize; - if idx < self.free_by_heap.len() && self.live[idx] { - self.free_by_heap[idx].push(t); - self.dirty_sort[idx] = true; - self.free_total += 1; - } + self.give_back(h, t, true); } } + /// Tiles a texture used go back to the free lists. + #[cfg(test)] fn return_tiles(&mut self, tiles: &[Tile]) { for &(h, t) in tiles { - let idx = h as usize; - if idx < self.free_by_heap.len() && self.live[idx] { - self.free_by_heap[idx].push(t); - self.dirty_sort[idx] = true; - self.free_total += 1; + self.give_back(h, t, true); + } + } + + /// Put tile `t` of heap `h` back on its free list; `used`: it holds some texture's bytes. + fn give_back(&mut self, h: u32, t: u32, used: bool) { + let idx = h as usize; + if idx < self.free_by_heap.len() && self.live[idx] { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + if used { + self.recycled[idx][t as usize / 64] |= 1 << (t % 64); } + self.free_total += 1; } } + /// Whether tile `t` of heap `h` held a texture's bytes, clearing the mark. + fn take_recycled(&mut self, h: usize, t: u32) -> bool { + let Some(word) = self.recycled.get_mut(h).and_then(|w| w.get_mut(t as usize / 64)) else { return false }; + let bit = 1u64 << (t % 64); + let was = *word & bit != 0; + *word &= !bit; + was + } + /// Pick a pool heap in the requested allocation class to take up to `rem` tiles from: /// 1. `preferred` if it fits all `rem` tiles (keeps partial-overlap placements on 1 heap), /// 2. otherwise best-fit heap with `len >= rem` (fits the whole texture in 1 heap without @@ -1539,6 +1562,7 @@ impl TilePool { /// Allocate `count` tiles in one allocation class, preferring a single heap and ascending /// contiguous offsets. `make_heap` allocates a new backing pool heap when the class has no /// free tiles. On failure, any tiles already taken are returned untouched. + #[cfg(test)] fn take_batch( &mut self, count: usize, @@ -1546,6 +1570,21 @@ impl TilePool { evictable: bool, now: std::time::Instant, pool_pages: u32, + make_heap: impl FnMut() -> Option, + ) -> Option> { + self.take_batch_recycled(count, preferred, evictable, now, pool_pages, &mut Vec::new(), make_heap) + } + + /// `take_batch`, adding the tiles taken that held another texture's bytes to `recycled`. + #[allow(clippy::too_many_arguments)] + fn take_batch_recycled( + &mut self, + count: usize, + preferred: Option, + evictable: bool, + now: std::time::Instant, + pool_pages: u32, + recycled: &mut Vec, mut make_heap: impl FnMut() -> Option, ) -> Option> { if count == 0 { @@ -1553,13 +1592,18 @@ impl TilePool { } self.drain_cooling(now); let mut out = Vec::with_capacity(count); + let recycled_from = recycled.len(); while out.len() < count { let rem = count - out.len(); let h = match self.pick_heap(rem, preferred, evictable) { Some(h) => h, None => { let Some(new_h) = make_heap() else { - self.return_tiles(&out); + // (back as they were: only the recycled ones still need zeroing) + let taken_recycled = recycled.split_off(recycled_from); + for &(h, t) in &out { + self.give_back(h, t, taken_recycled.contains(&(h, t))); + } return None; }; self.add_heap_at(new_h, pool_pages, evictable); @@ -1570,10 +1614,12 @@ impl TilePool { self.free_by_heap[h].sort_unstable_by(|a, b| b.cmp(a)); self.dirty_sort[h] = false; } - let free = &mut self.free_by_heap[h]; - let take = rem.min(free.len()); + let take = rem.min(self.free_by_heap[h].len()); for _ in 0..take { - let t = free.pop().unwrap(); + let t = self.free_by_heap[h].pop().unwrap(); + if self.take_recycled(h, t) { + recycled.push((h as u32, t)); + } out.push((h as u32, t)); } self.free_total -= take; @@ -1603,13 +1649,16 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { /// are reclaimed back to local VRAM. `len()` reports the count of live heaps. struct PoolHeaps { slots: Vec>, + /// A buffer over all of heap `idx`, placed once a recycled tile of it is zeroed + /// (`Pages::zero_recycled`); it takes no memory of its own. + zero_bufs: Vec>, free_slots: Vec, live: usize, } impl PoolHeaps { fn new() -> Self { - Self { slots: Vec::new(), free_slots: Vec::new(), live: 0 } + Self { slots: Vec::new(), zero_bufs: Vec::new(), free_slots: Vec::new(), live: 0 } } fn len(&self) -> usize { @@ -1621,15 +1670,22 @@ impl PoolHeaps { if let Some(idx) = self.free_slots.pop() { debug_assert!(self.slots[idx as usize].is_none()); self.slots[idx as usize] = Some(heap); + self.zero_bufs[idx as usize] = None; idx } else { let idx = self.slots.len() as u32; self.slots.push(Some(heap)); + self.zero_bufs.push(None); idx } } fn take_heap(&mut self, idx: u32) -> Option { + // (a placed resource holds its heap, and the zero-fills that used it are long done: every + // tile of the heap was given back and cooled since) + if let Some(buf) = self.zero_bufs.get_mut(idx as usize) { + *buf = None; + } let h = self.slots.get_mut(idx as usize)?.take()?; self.live -= 1; self.free_slots.push(idx); @@ -1640,6 +1696,135 @@ impl PoolHeaps { fn get(&self, idx: usize) -> Option<&ID3D12Heap> { self.slots.get(idx).and_then(Option::as_ref) } + + /// The buffer over all of live heap `idx`, placed on first use. + unsafe fn zero_buffer(&mut self, dev: &ID3D12Device, idx: usize) -> Option { + if let Some(buf) = self.zero_bufs.get(idx)?.as_ref() { + return Some(buf.clone()); + } + let heap = self.slots.get(idx)?.as_ref()?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: POOL_PAGES as u64 * PAGE as u64, + 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, + ..Default::default() + }; + let mut buf: Option = None; + super::title_textures::own_work(|| dev.CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buf)).ok()?; + let buf = buf?; + let _ = buf.SetName(windows::core::w!("xcl vram pool zero-fill alias")); + self.zero_bufs[idx] = Some(buf.clone()); + Some(buf) + } +} + +/// Zero recycled pool tiles before a new texture gets them (`XCL_ZERO_TARGET_PAGES=0`: no), so a +/// new render target starts from zeros rather than from some evicted texture's bytes. +fn zero_target_pages() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").map_or(true, |v| v.trim() != "0")) +} + +/// Bytes of zeros the zero-fill copies come from; one copy per run of this size at most. +const ZERO_BUF_BYTES: u64 = 1 << 20; +/// Zero-fill lists in flight on the mapping queue before a new one waits for the oldest. +const ZERO_SLOTS: usize = 8; + +struct ZeroSlot { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + /// `Pages::fence` value after this slot's last submission + done_at: u64, + /// zero buffers its last submission wrote + kept: Vec, +} + +/// Command lists and the source of zeros for `Pages::zero_recycled`, made on first use. +struct ZeroRing { + zeros: ID3D12Resource, + slots: Vec, +} + +impl ZeroRing { + unsafe fn new(dev: &ID3D12Device) -> Option { + let mut zeros: Option = None; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: ZERO_BUF_BYTES, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }; + super::title_textures::own_work(|| { + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut zeros) + }) + .ok()?; + let zeros = zeros?; + let mut p = std::ptr::null_mut(); + zeros.Map(0, None, Some(&mut p)).ok()?; + std::ptr::write_bytes(p as *mut u8, 0, ZERO_BUF_BYTES as usize); + zeros.Unmap(0, None); + let _ = zeros.SetName(windows::core::w!("xcl vram zero-fill source")); + Some(ZeroRing { zeros, slots: Vec::new() }) + } + + /// A slot whose last submission is done, a new one, or the oldest once it is done. + unsafe fn slot(&mut self, dev: &ID3D12Device, fence: &ID3D12Fence) -> Option<&mut ZeroSlot> { + let done = super::real::fence_completed(fence); + if let Some(i) = self.slots.iter().position(|s| s.done_at <= done) { + return Some(&mut self.slots[i]); + } + if self.slots.len() < ZERO_SLOTS { + let (alloc, list) = super::title_textures::own_work(|| -> windows::core::Result<_> { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; + list.Close()?; + Ok((alloc, list)) + }) + .ok()?; + self.slots.push(ZeroSlot { alloc, list, done_at: 0, kept: Vec::new() }); + return self.slots.last_mut(); + } + let i = (0..self.slots.len()).min_by_key(|&i| self.slots[i].done_at)?; + crate::gpu::fence::wait(fence, self.slots[i].done_at, dev, None, 5_000).ok()?; + Some(&mut self.slots[i]) + } +} + +/// Sorted `(heap, first tile, count)` runs of consecutive tiles of `tiles`. +fn tile_runs(tiles: &mut [Tile]) -> Vec<(u32, u32, u32)> { + tiles.sort_unstable(); + let mut runs: Vec<(u32, u32, u32)> = Vec::new(); + for &(h, t) in tiles.iter() { + match runs.last_mut() { + Some(run) if run.0 == h && run.1 + run.2 == t => run.2 += 1, + Some(run) if run.0 == h && run.1 + run.2 > t => {} + _ => runs.push((h, t, 1)), + } + } + runs +} + +/// Count `tiles` zeroed, saying so at every power of two. +fn note_zeroed(tiles: u64, copies: u64) { + static N: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + let before = N[0].fetch_add(tiles, std::sync::atomic::Ordering::Relaxed); + let copies = N[1].fetch_add(copies, std::sync::atomic::Ordering::Relaxed) + copies; + let now = before + tiles; + if before == 0 || before.ilog2() != now.ilog2() { + crate::xlog_info!( + "D3D12.X: zeroed {now} recycled 64 KiB pool tiles ({} MiB, {copies} copies) before new textures got them", + now * PAGE as u64 >> 20 + ); + } } impl std::ops::Index for PoolHeaps { @@ -1714,6 +1899,10 @@ struct Pages { scratch_flags: Vec, scratch_offsets: Vec, scratch_counts: Vec, + /// zero-fills of recycled tiles (`zero_recycled`); None until the first + zero_ring: Option, + /// `ZeroRing::new` failed: recycled tiles are handed out as they are + zero_ring_failed: bool, } // D3D12 objects are free-threaded @@ -1860,9 +2049,89 @@ impl Pages { scratch_flags: Vec::new(), scratch_offsets: Vec::new(), scratch_counts: Vec::new(), + zero_ring: None, + zero_ring_failed: false, }) } + /// Zero `recycled` (tiles another texture used) on the mapping queue, ahead of the mapping + /// that hands them to a new texture: every queue waits for that mapping's fence value before + /// work that uses the texture (`before_execute`), so it sees zeros, never the old bytes. + /// Writes through a buffer placed over the whole pool heap, so no texture is involved. + unsafe fn zero_recycled(&mut self, dev: &ID3D12Device, recycled: &mut [Tile]) { + if recycled.is_empty() || !zero_target_pages() || self.zero_ring_failed { + return; + } + if self.zero_ring.is_none() { + self.zero_ring = ZeroRing::new(dev); + if self.zero_ring.is_none() { + self.zero_ring_failed = true; + crate::xlog_warn!("D3D12.X: no zero-fill source: recycled pool tiles go to new textures with their old bytes"); + return; + } + } + let runs = tile_runs(recycled); + let mut bufs: Vec<(u32, ID3D12Resource)> = Vec::new(); + for &(h, _, _) in &runs { + if bufs.last().is_none_or(|b| b.0 != h) { + if let Some(buf) = self.pools.zero_buffer(dev, h as usize) { + bufs.push((h, buf)); + } + } + } + if bufs.is_empty() { + return; + } + let ring = self.zero_ring.as_mut().unwrap(); + let zeros = ring.zeros.clone(); + let Some(slot) = ring.slot(dev, &self.fence) else { return }; + let mut copies = 0u64; + let mut tiles = 0u64; + let recorded = super::title_textures::own_work(|| -> windows::core::Result<()> { + slot.alloc.Reset()?; + slot.list.Reset(&slot.alloc, None)?; + slot.kept.clear(); + for &(h, first, count) in &runs { + let Some((_, dst)) = bufs.iter().find(|b| b.0 == h) else { continue }; + let (mut at, end) = (first as u64 * PAGE as u64, (first + count) as u64 * PAGE as u64); + while at < end { + let n = (end - at).min(ZERO_BUF_BYTES); + slot.list.CopyBufferRegion(dst, at, &zeros, 0, n); + at += n; + copies += 1; + } + tiles += count as u64; + } + // (the tiles' next accesses are through the new texture) + let barriers: Vec = bufs + .iter() + .map(|(_, buf)| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::transmute_copy(buf), + pResourceAfter: std::mem::ManuallyDrop::new(None), + }), + }, + }) + .collect(); + slot.list.ResourceBarrier(&barriers); + slot.list.Close()?; + let list: ID3D12CommandList = slot.list.cast()?; + super::real::native_queue_execute(&self.queue, &list); + Ok(()) + }); + if recorded.is_err() { + return; + } + slot.kept.extend(bufs.into_iter().map(|(_, buf)| buf)); + self.value += 1; + let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + slot.done_at = self.value; + note_zeroed(tiles, copies); + } + /// Pages no resource used for `IDLE` go back to the pools. fn sweep(&mut self, now: std::time::Instant) { sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.pool.cooling, now); @@ -2119,10 +2388,13 @@ impl Pages { let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, evictable, now, POOL_PAGES, || { + let mut recycled = Vec::new(); + let fresh = pool.take_batch_recycled(missing, preferred, evictable, now, POOL_PAGES, &mut recycled, || { let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; + // (before `map` below, on the same queue: no work sees the tiles through `res` before) + self.zero_recycled(dev, &mut recycled); let mut fresh_iter = fresh.into_iter(); let mut tiles = Vec::with_capacity(range.len()); @@ -4195,6 +4467,51 @@ mod tests { assert_eq!(heap_ranges(0, &[(0, 3), (0, 1), (0, 2)]), [(true, 3, 1), (true, 1, 2)]); } + /// Only tiles some texture used come back as recycled (to be zeroed), once each; a new heap's + /// tiles and a failed batch's untouched ones do not. + #[test] + fn tile_pool_reports_only_recycled_tiles_for_zeroing() { + const P: u32 = 8; + let t0 = Instant::now(); + let mut pool = TilePool::new(); + let mut next = 0u32; + let mut make = || { + next += 1; + Some(next - 1) + }; + let mut recycled = Vec::new(); + let a = pool.take_batch_recycled(4, None, false, t0, P, &mut recycled, &mut make).unwrap(); + assert!(recycled.is_empty(), "a new heap is zeros"); + + pool.push_cooling(a[1], t0); + pool.push_cooling(a[2], t0); + let t1 = t0 + COOL; + let b = pool.take_batch_recycled(6, Some(0), false, t1, P, &mut recycled, &mut make).unwrap(); + assert_eq!(b.len(), 6); + assert_eq!(recycled, [(0, 1), (0, 2)]); + + // taken once: zeroed once, then they belong to `b` + recycled.clear(); + pool.return_tiles(&b[2..]); + let c = pool.take_batch_recycled(4, Some(0), false, t1, P, &mut recycled, &mut make).unwrap(); + assert_eq!(c.len(), 4); + assert_eq!(recycled.len(), 4, "every tile `b` gave back held its bytes"); + + // a failed batch puts its tiles back as they were + recycled.clear(); + pool.push_cooling(a[0], t0); + let free_before = pool.free_total; + assert!(pool.take_batch_recycled(64, None, false, t1, P, &mut recycled, || None).is_none()); + assert!(recycled.is_empty()); + assert_eq!(pool.free_total, free_before + 1); + let d = pool.take_batch_recycled(1, Some(0), false, t1, P, &mut recycled, || None).unwrap(); + assert_eq!(d, [(0, 0)]); + assert_eq!(recycled, [(0, 0)], "still recycled after the failed batch"); + + let mut runs_in = vec![(1, 3), (0, 5), (0, 4), (0, 4), (0, 7), (1, 2)]; + assert_eq!(tile_runs(&mut runs_in), [(0, 4, 2), (0, 7, 1), (1, 2, 2)]); + } + /// Streaming churn across 100+ 64 MiB pool heaps: cooling tiles returned in interleaved /// cross-heap order are regrouped per heap and sorted into contiguous ascending runs, so new /// textures stay inside 1 pool heap (1 UpdateTileMappings call, 1 contiguous range) instead of From e3fae4ed3e8ffae792c8a50ba0807a638d5a1b77 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Mon, 30 Nov 2026 17:51:11 +0100 Subject: [PATCH 155/175] d3d12x: keep dispatch chain scratch until the GPU is done with it The title's final Release of a command allocator cleared RECORDINGS for it (alloc_release, real.rs) even when alloc_pool kept the allocator alive because a list still held a recording on it or the GPU had not passed its submits. The chains' scratch buffers, indirect command storage and pipelines then went through late_release, which only waits for work submitted before the release: a list submitted again (or a submit reserved but not yet on the queue) ran its chains on freed memory. Retail runs on Linux/RADV lost the device (0x887a0005) 2-4 min after world entry, each time after a gfxhub read fault (PERMISSION_FAULTS 0x3, client 10, thread vkd3d_queue) and a ring timeout. A local log of every buffer's GPU address range puts several of those fault addresses (0x8016d3c02000, 0x801736c00000.., 0x8016f76c1000, 0x80164e630000) in freed chain-scratch buffers of a run with the same address layout. A Quint model of the recordings' lifetime finds the same: a recording is freed at the final Release while a list can still submit it. RECORDINGS of a PC allocator now go at console_list::allocator_reset, which alloc_pool calls only for a backing it proved free (no list holds a recording on it, every submit passed): reset_pc_allocator, forget's free backings and sweep_release_owners. alloc_release clears them itself only when the pool does not keep the allocator. As a side effect, recordings on put-aside backings no longer wait for those backings' own Release. --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 38 ++++++ crates/xcl/src/hle/d3d12x/console_list.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 12 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 121 +++++++++++++----- 4 files changed, 140 insertions(+), 32 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 6e12d2e530..c5a4faf5d1 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -1262,6 +1262,13 @@ unsafe fn forget_in(s: &mut State, alloc: usize, free: &HashSet) -> (Vec< (made, removed) } +/// Whether the native allocator `raw` is still held here after its title's final Release +/// (`forget`): lists hold a recording on it or the GPU has not passed its submits. What those +/// recordings use then goes at `console_list::allocator_reset`, when it retires. +pub(super) fn retained(raw: usize) -> bool { + STATE.lock().unwrap().as_ref().is_some_and(|s| s.backings.contains_key(&raw)) +} + pub unsafe fn forget(alloc: usize) { let (made, removed, free) = loop { let (mine, probes) = { @@ -2089,6 +2096,37 @@ mod tests { } } + /// The title's final Release of an allocator a list still records on (and may submit again), + /// or whose submits the GPU has not passed, leaves it `retained`: `alloc_release` must not let + /// its dispatch chains' scratch go then (it faulted the GPU). A free one is not retained. + #[test] + fn a_final_release_retains_a_busy_allocator_and_not_a_free_one() { + let (busy, list, pinned, free) = (0x7ffe_6a00usize, 0x7ffe_6a10usize, 0x7ffe_6b00usize, 0x7ffe_6c00usize); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.backings.insert(busy, Backing { users: HashSet::from([list]), ..Default::default() }); + s.of_list.insert(list, busy); + s.backings.insert(pinned, Backing { submit_pins: 1, ..Default::default() }); + s.backings.insert(free, Backing::default()); + } + unsafe { + forget(busy); + forget(pinned); + forget(free); + } + assert!(retained(busy), "a list still holds a recording on it"); + assert!(retained(pinned), "a submit of it has not reached the GPU"); + assert!(!retained(free), "nothing holds it: it retired, and its recordings went with it"); + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.backings[&busy].retire_when_free && s.backings[&pinned].retire_when_free); + // (synthetic raws have no COM reference to sweep) + s.backings.remove(&busy); + s.backings.remove(&pinned); + s.of_list.remove(&list); + } + #[test] fn absent_free_made_backing_is_scheduled_for_release_once() { let (alloc, made) = (0x7ffe_6300usize, 0x7ffe_6400usize); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index aca56e5ecb..3ba7bc4f9e 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -454,6 +454,7 @@ pub fn allocator_reset(allocator: *mut c_void) { unsafe { free_uma(&b) }; } super::bind::release_allocator_res(allocator as usize); + super::real::dispatch_chain::allocator_reset(allocator as usize); } fn with_list(obj: usize, f: impl FnOnce(&mut ListState) -> R) -> Option { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 61f85fd167..2d749c3b06 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -12569,8 +12569,14 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { || super::alloc_pool::retain_release_probe(this), ); if n == 0 { - dispatch_chain::allocator_reset(this as usize); + // The dispatch chains recorded on it go when `console_list::allocator_reset` says the GPU + // is done with them, not here: `forget` may keep the allocator for lists that still hold + // (and may submit again) a recording on it, or for submits the GPU has not passed. super::alloc_pool::forget(this as usize); + if !super::alloc_pool::retained(this as usize) { + // (no pool, or it never knew this one: as before) + dispatch_chain::allocator_reset(this as usize); + } super::list_x::on_allocator_release(this as usize); } n @@ -12582,8 +12588,8 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { let f: F = std::mem::transmute(orig_fn(raw, slot!(raw, "Reset"))); let hr = f(raw); if hr >= 0 { - dispatch_chain::allocator_reset(raw as usize); - // The GPU is done with allocations owned by this exact native backing. + // The GPU is done with allocations owned by this exact native backing (and its dispatch + // chains' scratch). super::console_list::allocator_reset(raw); } hr diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index ed17b4df3a..97bd98ae3a 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -612,6 +612,8 @@ unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed: Some((s, false)) } +/// The GPU is done with what was recorded on the PC allocator `allocator` and no list holds it +/// (`console_list::allocator_reset`): its chains' scratch, indirect commands and pipelines go. pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) { let recordings = RECORDINGS.lock().unwrap().remove(&allocator); drop(recordings); @@ -955,38 +957,47 @@ mod tests { assert_eq!(calls, 2, "the successful retry is retained"); } - #[test] - fn failed_binding_keeps_indirect_commands_until_allocator_reset() { + /// A split program whose indirect set is ready, under its first piece's address, and its plan + /// (which the chain holds only weakly). `None`: no GPU or no DXC. + unsafe fn ready_indirect_chain() -> Option<(ID3D12Device, usize, Arc)> { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; unsafe extern "system" fn never(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return None; + } + let dev: ID3D12Device = dev.unwrap(); + let Ok(dxil) = crate::gpu::recomp::dxc::compile("[numthreads(1,1,1)] void main() {}", "main", "cs_6_0", &[]) else { + crate::gpu::recomp::runner::skip_test("no DXC"); + return None; + }; + let rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + 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 first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); + let whole = WholeBuild::new(); + whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap(); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain }); + let key = first.as_raw() as usize; + let plan = Arc::new(DispatchChain { pieces: vec![dxil.clone(), dxil.clone()], dwords_per_group: 4 }); + assert!(reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, 1, INDIRECT_VARIANT_BYTES)); + let indirect = Arc::new(IndirectChain { signature: rs.clone(), whole: first.clone(), + pieces: vec![first.clone(), first.clone()], _charge: IndirectCharge(1) }); + let indirect_build = IndirectBuild::new(); + indirect_build.requested.store(true, Ordering::Relaxed); + indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!()); + CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, + whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build, + indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) })); + Some((dev, key, plan)) + } + + #[test] + fn failed_binding_keeps_indirect_commands_until_allocator_reset() { unsafe { - let mut dev = 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 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 first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); - let whole = WholeBuild::new(); - whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap(); - let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(), - flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain }); - let key = first.as_raw() as usize; - let plan = Arc::new(DispatchChain { pieces: vec![dxil.clone(), dxil.clone()], dwords_per_group: 4 }); - assert!(reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, 1, INDIRECT_VARIANT_BYTES)); - let indirect = Arc::new(IndirectChain { signature: rs.clone(), whole: first.clone(), - pieces: vec![first.clone(), first.clone()], _charge: IndirectCharge(1) }); - let indirect_build = IndirectBuild::new(); - indirect_build.requested.store(true, Ordering::Relaxed); - indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!()); - CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, - whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build, - indirect_noted: AtomicBool::new(false), whole_sent: AtomicBool::new(false) })); + let Some((dev, key, _plan)) = ready_indirect_chain() else { return }; let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); @@ -1008,6 +1019,58 @@ mod tests { } } + /// The title releases its allocator while a list still holds a chain recorded on it and the + /// GPU has not run that list: the recording (scratch, indirect commands, pipelines) stays + /// until the GPU is done and no list holds it, and goes then. (It went at the Release, and the + /// GPU read the freed scratch: a page fault, then the device was lost.) + #[test] + fn a_released_allocator_keeps_its_chains_until_the_gpu_is_done() { + use super::super::super::alloc_pool; + unsafe { + let Some((dev, key, _plan)) = ready_indirect_chain() else { return }; + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + if !super::super::is_adopted(alloc.as_raw()) { + super::super::adopt(alloc.as_raw(), super::super::Kind::CommandAllocator); + } + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); + alloc_pool::created_on(raw_list, allocator, ty.0); + let args = pso::chain_commands_buffer(&dev, 1).unwrap(); + // (a failed binding records no ExecuteIndirect, but keeps the recording as a run would) + let _ = execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into())); + assert!(RECORDINGS.lock().unwrap().contains_key(&allocator)); + list.Close().unwrap(); + // the queue runs the list only once `gate` is signalled + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + alloc_pool::executed(queue.as_raw(), &[raw_list as *mut c_void]); + + drop(alloc); + assert!(RECORDINGS.lock().unwrap().contains_key(&allocator), "the title's final Release left the recording in flight"); + + gate.Signal(1).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&done, 1).unwrap(); + let start = std::time::Instant::now(); + while done.GetCompletedValue() < 1 && start.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(done.GetCompletedValue() >= 1, "the queue finishes"); + assert!(RECORDINGS.lock().unwrap().contains_key(&allocator), "the list still holds the recording"); + // the list's recording ends: the allocator retires, and its chains with it + alloc_pool::forget_list(raw_list); + list_reset(raw_list); + drop(list); + alloc_pool::sweep_release_owners(); + assert!(!alloc_pool::retained(allocator)); + assert!(!RECORDINGS.lock().unwrap().contains_key(&allocator), "the GPU is done and no list holds it: it goes"); + forget(key); + } + } + #[test] fn remap_compile_oom_retries_but_deterministic_failure_is_final() { let at = std::time::Instant::now(); From 4da33e2644b0d8b55597832003aefc20b4b5acd8 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:24:58 +0100 Subject: [PATCH 156/175] Benches: initialize PsInterface::early_depth in gpu_cpu bench Fixes the missing field E0063 compile error that broke cargo bench --test in CI after merging main's early_depth field. --- crates/xcl/benches/gpu_cpu.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/xcl/benches/gpu_cpu.rs b/crates/xcl/benches/gpu_cpu.rs index e249d9d434..624d3a1bee 100644 --- a/crates/xcl/benches/gpu_cpu.rs +++ b/crates/xcl/benches/gpu_cpu.rs @@ -87,6 +87,7 @@ fn graphics_options(split_wave64: bool) -> recomp::Options { outputs: Vec::new(), input_ena: 0, attrs: None, + early_depth: false, }), wave64: true, split_wave64, From f9e31720073817e7d328f5fd47e3d911b875aa32 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:24:58 +0100 Subject: [PATCH 157/175] D3D12.X, loader, kernelx: bake-at-submit, ambient refinements, upscaler patch, unlocked CPU readback, and two-pass reuse Visual, memory, and performance fixes validated in next-r14 on RX 9070 XT: - Bake-at-submit (XCL_BAKE_AT_SUBMIT, on by default): re-uncover and upload bake source textures at list submit (title_textures, bind, list_x, real) so textures shadowed between draw recording and submit do not bake zeros into character skin/heads. - Ambient stand-in refinements (ambient.rs): XCL_AMBIENT_ONCE (one-bounce tracking), XCL_AMBIENT_MEAN_CLEAN (default on), XCL_AMBIENT_DITHER (frame-moving noise, default on), XCL_AMBIENT_SPECULAR_ALPHA. - Upscaler controls (title_patch.rs, loader.rs, kernelx.rs): opt-in XCL_UPSCALER=6|7 exact-byte title patch with +512 MB Series S heap #2 growth when forcing the title's own upscaler, plus XCL_FFX_UPSCALER=0 DLL refusal toggle. Credits recorded in THIRD_PARTY.md. - Unlocked CPU readback (sparse.rs, XCL_CPU_READ_UNLOCKED, on by default): release sparse STATE and UPLOAD_GATE while waiting for CPU readback GPU copies, tracking concurrent modifications so title submits are not blocked behind CPU readbacks. - Two-pass ExecuteIndirect reuse & cold cap (bind.rs, indirect_guard.rs): XCL_TWO_PASS_COLD_MB (default 4 MiB) caps cold indirect record allocations to prevent draw skips at world entry, and exact-fence buffer returns avoid unnecessary retire holds. - Late-release runtime caller guard (real.rs, late_release.rs): defer D3D12 runtime-internal last releases to the late-release thread. - Recompiler (pso.rs): XCL_HEAP_FLAT defaults to on when heap windows are active. --- THIRD_PARTY.md | 1 + crates/xcl/src/gpu/recomp/pso.rs | 8 +- crates/xcl/src/hle/d3d12x/ambient.rs | 531 ++++++++++++++- crates/xcl/src/hle/d3d12x/bind.rs | 696 ++++++++++++++++++-- crates/xcl/src/hle/d3d12x/indirect_guard.rs | 6 + crates/xcl/src/hle/d3d12x/late_release.rs | 64 +- crates/xcl/src/hle/d3d12x/list_x.rs | 2 + crates/xcl/src/hle/d3d12x/real.rs | 67 ++ crates/xcl/src/hle/d3d12x/sparse.rs | 612 ++++++++++++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 194 +++++- crates/xcl/src/hle/kernelx.rs | 34 + crates/xcl/src/lib.rs | 1 + crates/xcl/src/loader.rs | 4 + crates/xcl/src/title_patch.rs | 216 ++++++ 14 files changed, 2358 insertions(+), 78 deletions(-) create mode 100644 crates/xcl/src/title_patch.rs diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index d34af92c67..4e04ecf123 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -13,6 +13,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0 | [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | | [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | `crates/xcl/src/gpu/rt_leave_out.rs` (the programs left out); `crates/xcl/src/hle/d3d12x/ambient.rs`: the cells and their slow mean, and the stand-in for the indirect light made in space – `LIGHT_PLACE_HLSL`, `LIGHT_GATHER_HLSL`, the depth path of `AMBIENT_FILL_R9G9B9E5_HLSL`, `AIR_CAP_HLSL` and the resolve's descriptor slots, after `place`, `gather`, `raise`, `clear_air`, `LIGHT` and `DEPTH` of its `ambient.rs` (commit 99a7f9b) | port of the HLSL into XCL's ambient pass (2026-11-28) | | [VIctory-Neo](https://github.com/KyleS98/VIctory-Neo) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/mirror.rs`: the light around a mirror's view – the programs' parts by name, `XCL_MIRROR_AMBIENT` and the pass and its programs, after its `crates/victory-gpu/src/mirror.rs` (commits a3af274, 9b61dc9); `crates/xcl/src/hle/d3d12x/depth_uav.rs`: a depth plane brought up to date from its twin before the draws that test against it, after 7da5c9d; `crates/xcl/src/hle/d3d12x/ambient.rs`: the reflections' hold to the light around and their resolve slots (3aca295), the bound on transparent surfaces' light (`CS_SpatialFilterAlpha`, a6e85c6) and the probes' blue garbage test, after its `crates/victory-gpu/src/ambient.rs` at bdc3f38; the stand-in for reflections that found nothing (`MISS_LIGHT_HLSL`, `XCL_AMBIENT_SPECULAR`, the `CS_RayMiss` slots and layers), after its `Role::Miss`, `reflect_light` and `VICTORY_AMBIENT_SPECULAR` at bdc3f38 | port adapted to XCL's passes and state (2026-11-29) | +| Whiplash (Belobug's lineage, VIctory PR #63; a snapshot, `Kalmarv/whiplash` 699f191) | GPL-3.0-or-later | `crates/xcl/src/hle/d3d12x/ambient.rs`: one bounce of the title's own light (`XCL_AMBIENT_ONCE`: the fill's notes at the places the keep reads, and the keep counting each place by them), after `VICTORY_AMBIENT_ONCE` in its `Whiplash-NVIDIA/crates/victory-gpu/src/ambient.rs`; the ideas of `XCL_AMBIENT_SPECULAR_ALPHA`, `XCL_AMBIENT_MEAN_CLEAN` and `XCL_AMBIENT_DITHER`, after its `VICTORY_AMBIENT_SPECULAR_ALPHA`, `VICTORY_AMBIENT_MEAN_CLEAN` and `VICTORY_AMBIENT_DITHER`; `crates/xcl/src/hle/d3d12x/title_textures.rs`: the idea of `XCL_BAKE_AT_SUBMIT`'s whole upload of a bake's sources as title memory has them just before the bake, after `early_budgets` and `bake_exact` in its `Whiplash-AMD/crates/victory-gpu/src/draw.rs`; `crates/xcl/src/title_patch.rs`: the title's upscaler picker (its offset and bytes, `mov eax, kind; ret`: `XCL_UPSCALER`), after `VICTORY_UPSCALER` in its `Whiplash-AMD/crates/victory-loader/src/resolution.rs` (VIctory PR #53) | re-implemented on XCL's passes; what the keep takes out is XCL's; the picker's bytes are the title's, applied only where they match (2026-11-30) | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 4228ee3e3e..3fd9b3dd89 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -194,11 +194,13 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } -/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap -/// windows without a branch per access (`HEAP_FLAT`). Opt-in while it is measured. +/// `XCL_HEAP_FLAT` (default on with heap windows; `=0` to disable): the direct DXIL translator +/// reads every stage's heap windows without a branch per access (`HEAP_FLAT`). With the branch, +/// AMD's compiler took a pixel shader's quad helper lanes into the sampler waterfall with a stale +/// index: a page fault at world entry (RX 9070 XT). pub fn heap_flat() -> bool { static ENV: OnceLock = OnceLock::new(); - *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").map_or(true, |v| v.trim() != "0")) } /// A static sampler of a translated program: (S#, comparison) – see `Translation`. diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index b8287f2987..3d9c303f79 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -13,7 +13,12 @@ //! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, //! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`, `XCL_AMBIENT_FRAME`, //! `XCL_AMBIENT_KEEP`, `XCL_AMBIENT_MOST`, `XCL_AMBIENT_SKY`, `XCL_AMBIENT_SPACE`, `XCL_AMBIENT_SPLIT`, -//! `XCL_AMBIENT_REFLECT_HOLD`, `XCL_AMBIENT_ALPHA`, `XCL_AMBIENT_SPECULAR`. +//! `XCL_AMBIENT_REFLECT_HOLD`, `XCL_AMBIENT_ALPHA`, `XCL_AMBIENT_SPECULAR`, `XCL_AMBIENT_ONCE`, +//! `XCL_AMBIENT_MEAN_CLEAN`, `XCL_AMBIENT_DITHER`, `XCL_AMBIENT_SPECULAR_ALPHA`. +//! +//! That a stand-in can be put after the screen probes' resolve, and in which of its images, is +//! Belobug's find (beloooo's VIctory-Belobug-AMD, GPL-3.0-or-later), which puts a constant there, +//! shaded in creases from the scene's depth. //! //! The sky alone leaves a night scene black wherever no lamp reaches. So the fill is also raised //! to an estimate taken from the frame itself: the light the visible surfaces send out, which the @@ -58,13 +63,27 @@ //! the light seen on screen, the others find nothing and `CS_RayMiss` gives each the sky's light //! from the sky's cube maps – indoors and at night far above the room's (a cutscene of VIctory-Neo: //! 10 to 30 against 0.01 to 0.1), the wet look of skin, the sparkles in hair and on car paint. -//! Right after that program (opaque and transparent surfaces; water is left) each texel of its +//! Right after that program (opaque surfaces; transparent ones only with +//! `XCL_AMBIENT_SPECULAR_ALPHA=estimate`; water is left) each texel of its //! image gets `XCL_AMBIENT_SPECULAR` (1 unless given, 0: off) of the light the gathered points //! send along the reflected direction instead (`MISS_LIGHT_HLSL`); what the screen-space resolve //! finds next is still written over it. Ported from VIctory-Neo //! (https://github.com/KyleS98/VIctory-Neo, GPL-3.0-or-later; its `Role::Miss`, `reflect_light`, //! `VICTORY_AMBIENT_SPECULAR`, 2026-11-29): the same estimate along the reflected direction, the //! slots the program writes and reads, which surfaces it acts on. +//! +//! After Whiplash (Belobug's lineage, VIctory PR #63; its `crates/victory-gpu/src/ambient.rs`, +//! GPL-3.0-or-later; THIRD_PARTY.md), re-implemented on XCL's passes (2026-11-30): +//! * `XCL_AMBIENT_ONCE=1` (off unless set, `once`): one bounce of the title's own light, the +//! fill's own light taken out of what comes back to the cells. The fill's notes at the places +//! the keep reads, and the keep counting each place by them, are adapted from its +//! `VICTORY_AMBIENT_ONCE`; what is taken out (no more than the fill added) is XCL's. +//! * `XCL_AMBIENT_SPECULAR_ALPHA` (`title` unless set, `specular_alpha`): the transparent layer's +//! missed reflections are left as the title has them, as its `VICTORY_AMBIENT_SPECULAR_ALPHA`. +//! * `XCL_AMBIENT_MEAN_CLEAN` (on unless `0`, `mean_clean`): the probes' garbage is left out of +//! the cells, as its `VICTORY_AMBIENT_MEAN_CLEAN`, with XCL's test of it. +//! * `XCL_AMBIENT_DITHER` (`frame` unless set, `dither`): the shade's noise moves with the frame +//! (the usual animated interleaved-gradient noise), as its `VICTORY_AMBIENT_DITHER=frame`. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; @@ -248,6 +267,88 @@ fn rays_find_nothing(traversal_allowed: bool, every_ray_misses: bool) -> bool { !traversal_allowed || every_ray_misses } +/// An on/off switch: `1` / `on` / `true` or `0` / `off` / `false`; anything else (or unset): `default`. +fn switch_on(raw: Option<&str>, default: bool) -> bool { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("1" | "on" | "true") => true, + Some("0" | "off" | "false") => false, + _ => default, + } +} + +/// `XCL_AMBIENT_ONCE=1`: the estimate is one bounce of the title's own light, not of the +/// stand-in's too. The cells are kept from the light surfaces sent out the frame before, which the +/// fill had raised: its own light comes back to it, and with `XCL_AMBIENT_FRAME` 0.8 and walls that +/// send out 0.6 of what they get it settles at 1 / (1 - 0.8 x 0.6) = 1.9 times one bounce (3.6 +/// times at 0.9, and no bound once the level times what walls send out reaches 1). With it the +/// fill notes, at the 25 places of each cell the keep reads, the luminance of the title's own +/// light it left there and of all it wrote, and the keep takes the fill's part out of what that +/// surface sent back: what the fill added times what the surface sends out of the light it got, +/// at most all of it (a surface sends out no more than it gets, so where a lamp or the sun lights +/// it too the rest is kept). Off unless set: where the stand-in is a room's main light the room +/// gets about half as much. +fn once() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch_on(std::env::var("XCL_AMBIENT_ONCE").ok().as_deref(), false)) +} + +/// `XCL_AMBIENT_MEAN_CLEAN`: the probes' garbage (magenta, and the bluer kind: what the fill drops +/// of the resolve's light) is counted as no light in the cells, still one of a cell's 25 places, +/// so neither the cells nor their slow mean take its hue. A few such texels in a dark room made its +/// mean violet. On unless `0`; a magenta or deep blue lamp counts as garbage too. +fn mean_clean() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| switch_on(std::env::var("XCL_AMBIENT_MEAN_CLEAN").ok().as_deref(), true)) +} + +/// `XCL_AMBIENT_DITHER`: `frame` (or on, the default) moves the interleaved-gradient noise that +/// turns the fill's shade samples (and picks its four points) by 5.588238 texels a frame over 64 +/// frames, so the title's temporal filter averages it out; `still` (or off) leaves it where it is +/// on screen, the pattern seen as dotted diagonal lines. +fn dither() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| dither_moves(std::env::var("XCL_AMBIENT_DITHER").ok().as_deref())) +} + +fn dither_moves(raw: Option<&str>) -> bool { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("frame") => true, + Some("still") => false, + other => switch_on(other, true), + } +} + +/// The dither's place for the frame `frame` shown: it moves a step a frame and comes back after 64. +fn dither_phase(frame: u64, moves: bool) -> u32 { + if moves { (frame % 64) as u32 } else { 0 } +} + +/// `XCL_AMBIENT_SPECULAR_ALPHA`: `estimate` (or on) gives the transparent layer's missed +/// reflections the estimate as the opaque one's; `title` (or off, the default) leaves them as the +/// title has them. Its depth there is of the opaque surface behind the glass, or the bottom under +/// the foam on water, and the estimate taken along it left dark patches; what the title gives +/// (the sky's light) is bounded after the transparent reflections' resolve, at +/// `XCL_AMBIENT_REFLECT_HOLD` times the light around. +fn specular_alpha() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| transparent_misses_estimated(std::env::var("XCL_AMBIENT_SPECULAR_ALPHA").ok().as_deref())) +} + +fn transparent_misses_estimated(raw: Option<&str>) -> bool { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("estimate") => true, + Some("title") => false, + other => switch_on(other, false), + } +} + +/// Whether a `CS_RayMiss` dispatch whose rays are of `layer` is given the estimate: the opaque +/// layer's always, the transparent one's with `transparent_too`, any other never. +fn miss_gets_estimate(layer: u32, transparent_too: bool) -> bool { + let [opaque, transparent] = MISS_LAYERS; + layer == opaque || layer == transparent && transparent_too +} + /// Role of a console shader identified from FSSM/container metadata. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum PassRole { @@ -284,9 +385,10 @@ const ALPHA_SLOT: (usize, usize) = (1, 24); const MISS_LIGHT_SLOT: (usize, usize) = (1, 104); const MISS_DEPTH_SLOT: (usize, usize) = (0, 1000); /// Which surfaces a `CS_RayMiss` dispatch's rays are of (its first root constant): the opaque ones -/// and the transparent ones are given the estimate; water's (the depth there is of what lies -/// under it) and any other are left as the title has them. From VIctory-Neo (`MISS_OPAQUE`, -/// `MISS_ALPHA`). +/// and the transparent ones can be given the estimate (the transparent ones with +/// `XCL_AMBIENT_SPECULAR_ALPHA=estimate`, `miss_gets_estimate`); water's (the depth there is of +/// what lies under it) and any other are left as the title has them. From VIctory-Neo +/// (`MISS_OPAQUE`, `MISS_ALPHA`). const MISS_LAYERS: [u32; 2] = [0, 1]; /// `CS_RayMiss_` and the eight hex digits of a variant's hash, then `_`: not `CS_RayMiss_Volumetrics` @@ -852,11 +954,32 @@ void main(uint3 gtid : SV_GroupThreadID, uint gidx : SV_GroupIndex) { const FRAME_CELLS: (u32, u32) = (64, 36); const GATHER_POINTS: (u32, u32) = (160, 90); const LEVEL_ELEMENTS: u32 = 2 + 2 * FRAME_CELLS.0 * FRAME_CELLS.1 + 3 * GATHER_POINTS.0 * GATHER_POINTS.1; +/// After those, `XCL_AMBIENT_ONCE`'s notes: a float4 for each of the 25 places of each cell the +/// keep reads – the luminance of the title's own light the fill left there and of all it wrote +/// (zero: nothing noted, nothing taken out). The level buffer holds them whether the switch is on +/// or not (0.9 MB). +const ONCE_AT: u32 = LEVEL_ELEMENTS; +const LEVEL_BUFFER_ELEMENTS: u32 = ONCE_AT + 25 * FRAME_CELLS.0 * FRAME_CELLS.1; /// A change of the cells' mean by more than this factor is taken at once (a cut, a new room). const FRAME_JUMP: f32 = 3.0; +/// The fill's seventh constant: bit 0 a sky was captured, bit 1 the title's own light is kept +/// (`XCL_AMBIENT_KEEP`), bit 2 the light is noted at the keep's places (`XCL_AMBIENT_ONCE`), bits 8 +/// to 13 the frame's place in the dither's round (`XCL_AMBIENT_DITHER`; 0: the still pattern). +fn fill_bits(sky_ready: bool, keeps: bool, once: bool, phase: u32) -> u32 { + sky_ready as u32 | (keeps as u32) << 1 | (once as u32) << 2 | (phase & 63) << 8 +} + +/// The keep's third constant: bit 0 the fill's own light is taken out (`XCL_AMBIENT_ONCE`), bit 1 +/// the probes' garbage is left out (`XCL_AMBIENT_MEAN_CLEAN`). +fn keep_bits(once: bool, clean: bool) -> u32 { + once as u32 | (clean as u32) << 1 +} + /// The light visible surfaces send out (`out_uav`, read only), averaged into the 64x36 cells of -/// the level buffer, `share` of it. Lamps and glints count, but not for everything. +/// the level buffer, `share` of it. Lamps and glints count, but not for everything. `flags` +/// (`keep_bits`): without the probes' garbage (`XCL_AMBIENT_MEAN_CLEAN`), and without the fill's +/// own light as each place sent it back (`XCL_AMBIENT_ONCE`, the fill's notes from `ONCE_AT` on). const FRAME_KEEP_HLSL: &str = r#" Texture2D _unused : register(t0); RWTexture2D out_uav : register(u0); @@ -864,13 +987,14 @@ RWStructuredBuffer sky_level : register(u1); cbuffer C : register(b0) { uint width; uint height; - uint _u2; + uint flags; uint _u3; uint _u4; float share; float _p6; float _p7; }; +#define ONCE_AT 47810 [numthreads(8, 8, 1)] void main(uint3 at : SV_DispatchThreadID) { if (at.x >= 64 || at.y >= 36 || width == 0 || height == 0) return; @@ -883,6 +1007,20 @@ void main(uint3 at : SV_DispatchThreadID) { uint2 p = min(uint2(at_texel), uint2(width - 1, height - 1)); float3 c = out_uav[p].rgb; c = all(isfinite(c)) ? max(c, 0.0) : float3(0.0, 0.0, 0.0); + // (bit 1) The probes' garbage, as the fill drops it from the resolve's light: no + // light, still one of the 25. + if ((flags & 2u) != 0u && ((c.g < 0.5 * min(c.r, c.b) && max(c.r, c.b) > 0.02) || (c.b > 2.5 * c.g && c.b > c.r && c.b > 0.02))) { + c = float3(0.0, 0.0, 0.0); + } + // (bit 0) Less the fill's own light as this place sent it back: what the fill added + // here (its note: the luminance of the title's light it left, of all it wrote) times + // what the place sends out of the light it got, at most all of what it added. + if ((flags & 1u) != 0u) { + float4 noted = sky_level[ONCE_AT + (at.y * 64 + at.x) * 25 + y * 5 + x]; + float added = max(noted.y - noted.x, 0.0); + float sent = dot(c, float3(0.2126, 0.7152, 0.0722)); + c *= saturate(1.0 - added / max(max(noted.y, sent), 1e-6)); + } sum += c / max(1.0, dot(c, float3(0.2126, 0.7152, 0.0722)) / 20.0); } } @@ -964,7 +1102,8 @@ float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { return 1.0; } - float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); + // (moved by 5.588238 texels for each frame of the dither's round: bits 8 to 13 of sky_ready) + float ign = frac(52.9829189 * frac(dot(float2(tid) + 5.588238 * float((sky_ready >> 8) & 63u), float2(0.06711056, 0.00583715)))); float base_ang = ign * 6.2831853; float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); float inv_d0 = 1.0 / max(d0, 1e-5); @@ -1046,6 +1185,7 @@ cbuffer C : register(b0) { #define CELL_AT 2 #define PLACE_AT 2306 #define POINT_AT 4610 +#define ONCE_AT 47810 static const float3 LUMA = float3(0.2126, 0.7152, 0.0722); // The point seen at a texel of the width x height picture, in metres from the eye (x right, y up, // z away). @@ -1173,6 +1313,8 @@ void main(uint3 at : SV_DispatchThreadID) { /// around the texel, those at its own depth first, along the normal the depth gives, shaded where /// the surroundings close over it within 0.6 m. Without it: the cells under the texel. The sky's /// level counts for `SKY_SHARE`, and what the title left for at most `MOST` times the estimate. +/// The shade's noise moves with the frame (`fill_bits`, `XCL_AMBIENT_DITHER`); with +/// `XCL_AMBIENT_ONCE` the light is noted where the keep reads (`ONCE_AT`). const AMBIENT_FILL_R9G9B9E5_HLSL: &str = r#" RWTexture2D out_uav : register(u0); float3 unpack_r9g9b9e5(uint v) { @@ -1206,6 +1348,18 @@ float3 frame_light(uint2 tid, float3 mean) { } return lerp(sum, mean, 0.2); } +// (`XCL_AMBIENT_ONCE`) Whether the keep reads texel `texel` of this width x height picture (place +// (x, y) of cell `at`, as FRAME_KEEP_HLSL finds it), and where that place's note is. +bool keep_reads(int2 texel, out uint noted) { + float2 g = (float2(texel) + 0.5) / float2(width, height) * float2(64.0, 36.0); + uint2 at = min(uint2(g), uint2(63u, 35u)); + uint x = min(uint((g.x - float(at.x)) * 5.0), 4u); + uint y = min(uint((g.y - float(at.y)) * 5.0), 4u); + float2 at_texel = (float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(width, height) / float2(64.0, 36.0); + uint2 p = min(uint2(at_texel), uint2(width - 1, height - 1)); + noted = ONCE_AT + (at.y * 64 + at.x) * 25 + y * 5 + x; + return all(p == uint2(texel)); +} [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { if (tid.x >= width || tid.y >= height) return; @@ -1230,7 +1384,8 @@ void main(uint3 tid : SV_DispatchThreadID) { // How open it is: what stands over the surface within 0.6 m shades it. const float radius = 0.6; float px = min(radius * size.y / (2.0 * 0.45 * c.z), 128.0); - float noise = frac(52.9829189 * frac(dot(float2(p), float2(0.06711056, 0.00583715)))); + // (moved by 5.588238 texels for each frame of the dither's round: bits 8 to 13 of sky_ready) + float noise = frac(52.9829189 * frac(dot(float2(p) + 5.588238 * float((sky_ready >> 8) & 63u), float2(0.06711056, 0.00583715)))); if (ao_strength > 0.0 && px >= 1.5 && c.z < 400.0) { float over_sum = 0.0; [loop] @@ -1285,7 +1440,12 @@ void main(uint3 tid : SV_DispatchThreadID) { // blocks of other memory. float top = max(dot(found, LUMA) * MOST, 1e-6); was *= min(1.0, top / max(dot(was, LUMA), 1e-6)); - out_uav[p] = pack_r9g9b9e5(max(was, found)); + float3 now = max(was, found); + out_uav[p] = pack_r9g9b9e5(now); + // (bit 2 of sky_ready, `XCL_AMBIENT_ONCE`) Where the next keep reads, how bright the title's own + // light is and all of it: the keep takes the rest out of what the place sends back. + uint noted = 0u; + if ((sky_ready & 4u) != 0u && keep_reads(p, noted)) sky_level[noted] = float4(dot(was, LUMA), dot(now, LUMA), 0.0, 0.0); } "#; @@ -1330,7 +1490,8 @@ float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { return 1.0; } - float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); + // (moved by 5.588238 texels for each frame of the dither's round: bits 8 to 13 of sky_ready) + float ign = frac(52.9829189 * frac(dot(float2(tid) + 5.588238 * float((sky_ready >> 8) & 63u), float2(0.06711056, 0.00583715)))); float base_ang = ign * 6.2831853; float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); float inv_d0 = 1.0 / max(d0, 1e-5); @@ -1674,7 +1835,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let sky_level = make_res( &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, - Width: (LEVEL_ELEMENTS as u64 * 16).next_multiple_of(256), + Width: (LEVEL_BUFFER_ELEMENTS as u64 * 16).next_multiple_of(256), Height: 1, DepthOrArraySize: 1, MipLevels: 1, @@ -2272,13 +2433,30 @@ pub(super) unsafe fn after_compute_dispatch( { return; } + static SWITCHES: std::sync::Once = std::sync::Once::new(); + SWITCHES.call_once(|| { + crate::xlog_info!( + "D3D12.X: ambient: one bounce {} (XCL_AMBIENT_ONCE), garbage left out of the cells {} (XCL_AMBIENT_MEAN_CLEAN), dither {} (XCL_AMBIENT_DITHER), the transparent layer's missed reflections {} (XCL_AMBIENT_SPECULAR_ALPHA)", + if once() { "on" } else { "off" }, + if mean_clean() { "on" } else { "off" }, + if dither() { "moving with the frame" } else { "still" }, + if specular_alpha() { "given the estimate" } else { "left as the title has them" } + ) + }); // (which surfaces the miss program's rays are of: its first root constant) if role == PassRole::RayMiss { let layer = layout.and_then(|l| l.params.iter().find_map(|p| match *p { Param::Constants { at, count } if count > 0 => args.get(at as usize..at as usize + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())), _ => None, })); - if !layer.is_some_and(|l| MISS_LAYERS.contains(&l)) { + if !layer.is_some_and(|l| miss_gets_estimate(l, specular_alpha())) { + if layer == Some(MISS_LAYERS[1]) { + static LEFT: AtomicU64 = AtomicU64::new(0); + let n = LEFT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 2 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: ambient: the transparent layer's missed reflections left as the title has them ({n} so far)"); + } + } return; } } @@ -2390,7 +2568,7 @@ pub(super) unsafe fn after_compute_dispatch( Format: DXGI_FORMAT_UNKNOWN, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_ELEMENTS, StructureByteStride: 16, ..Default::default() }, + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_BUFFER_ELEMENTS, StructureByteStride: 16, ..Default::default() }, }, }; if is_reflect_role { @@ -2441,7 +2619,7 @@ pub(super) unsafe fn after_compute_dispatch( } else { ad.fill_write_pso.as_raw() }, - [w, h, depth_w, depth_h, has_depth | (has_depth & split_screen() as u32) << 1, cfg.ao.to_bits(), sky_ready as u32 | (keeps_title_light() as u32) << 1, PRE_SKY_FALLBACK.to_bits()], + [w, h, depth_w, depth_h, has_depth | (has_depth & split_screen() as u32) << 1, cfg.ao.to_bits(), fill_bits(sky_ready, keeps_title_light(), once(), dither_phase(present::presents(), dither())), PRE_SKY_FALLBACK.to_bits()], (w.div_ceil(8), h.div_ceil(8), 1), ), PassRole::ReflectionHistory => ( @@ -2461,7 +2639,7 @@ pub(super) unsafe fn after_compute_dispatch( ), PassRole::Radiance => ( ad.keep_pso.as_raw(), - [w, h, 0, 0, 0, cfg.frame.to_bits(), 0, 0], + [w, h, keep_bits(once(), mean_clean()), 0, 0, cfg.frame.to_bits(), 0, 0], (FRAME_CELLS.0.div_ceil(8), FRAME_CELLS.1.div_ceil(8), 1), ), PassRole::AlphaLight => ( @@ -2511,6 +2689,10 @@ pub(super) unsafe fn after_compute_dispatch( } dispatch(list, disp.0, disp.1, disp.2); uav_barrier(list, uav_res); + if role == PassRole::TemporalResolve && once() { + // (the fill wrote its notes for the next keep) + uav_barrier(list, ad.sky_level.as_raw() as usize); + } if let Some((arg_buf, _)) = gated_indirect { list_x::transition(list, arg_buf, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); } @@ -2883,6 +3065,195 @@ mod tests { assert!(LIGHT_COMMON_HLSL.contains(&format!("#define POINT_AT {}", 2 + 2 * FRAME_CELLS.0 * FRAME_CELLS.1))); } + /// The switches after Whiplash take their words; any other word (or none) leaves the default. + #[test] + fn the_switches_after_whiplash_take_their_words() { + assert!(!switch_on(None, false) && switch_on(None, true), "unset: the default"); + assert!(switch_on(Some(" 1 "), false) && switch_on(Some("ON"), false) && switch_on(Some("true"), false)); + assert!(!switch_on(Some("0"), true) && !switch_on(Some("off"), true) && !switch_on(Some("False"), true)); + assert!(!switch_on(Some("yes"), false) && switch_on(Some("2"), true), "another word: the default"); + assert!(dither_moves(None) && dither_moves(Some("frame")) && dither_moves(Some(" Frame ")) && dither_moves(Some("1")) && dither_moves(Some("x"))); + assert!(!dither_moves(Some("still")) && !dither_moves(Some("0")) && !dither_moves(Some("off"))); + assert!(!transparent_misses_estimated(None) && !transparent_misses_estimated(Some("title")) && !transparent_misses_estimated(Some("0"))); + assert!(!transparent_misses_estimated(Some("bound")), "another word: left as the title has them"); + assert!(transparent_misses_estimated(Some("estimate")) && transparent_misses_estimated(Some("1")) && transparent_misses_estimated(Some("on"))); + } + + /// The opaque layer's missed reflections are given the estimate; the transparent layer's only + /// with `XCL_AMBIENT_SPECULAR_ALPHA=estimate`; water's and any other never. + #[test] + fn the_transparent_layers_missed_reflections_are_left_unless_asked_for() { + assert!(miss_gets_estimate(0, false) && miss_gets_estimate(0, true), "opaque"); + assert!(!miss_gets_estimate(1, false), "transparent, by default: as the title has them"); + assert!(miss_gets_estimate(1, true), "transparent, with the switch"); + for layer in [2, 3, 7, u32::MAX] { + assert!(!miss_gets_estimate(layer, true) && !miss_gets_estimate(layer, false), "layer {layer}"); + } + } + + /// The fill's and the keep's constants hold the switches where their programs test them, and + /// the notes follow the level buffer's other parts in both programs. + #[test] + fn the_switches_reach_the_programs_in_their_constants() { + assert_eq!(fill_bits(false, false, false, 0), 0, "nothing on: as before"); + assert_eq!(fill_bits(true, true, false, 0), 3, "the sky and the title's light, as before"); + assert_eq!(fill_bits(true, false, true, 0), 0b101); + assert_eq!(fill_bits(false, false, false, 63), 63 << 8); + assert_eq!(fill_bits(true, true, true, 64 + 5), 7 | 5 << 8, "the round's place, 0 to 63"); + assert_eq!([keep_bits(false, false), keep_bits(true, false), keep_bits(false, true), keep_bits(true, true)], [0, 1, 2, 3]); + assert_eq!(ONCE_AT, 2 + 2 * 2304 + 3 * 14400); + assert_eq!(LEVEL_BUFFER_ELEMENTS, ONCE_AT + 25 * FRAME_CELLS.0 * FRAME_CELLS.1); + let define = format!("#define ONCE_AT {ONCE_AT}\n"); + assert!(FRAME_KEEP_HLSL.contains(&define) && LIGHT_COMMON_HLSL.contains(&define)); + for bit in ["(flags & 1u)", "(flags & 2u)"] { + assert!(FRAME_KEEP_HLSL.contains(bit), "{bit}"); + } + for bit in ["(sky_ready & 1u)", "(sky_ready & 2u)", "(sky_ready & 4u)", "(sky_ready >> 8) & 63u"] { + assert!(AMBIENT_FILL_R9G9B9E5_HLSL.contains(bit), "{bit}"); + } + } + + /// The keep's place (x, y) of cell `at` in a `size` picture, as FRAME_KEEP_HLSL finds it. + fn keep_texel(at: [u32; 2], xy: [u32; 2], size: [u32; 2]) -> [u32; 2] { + let one = |i: usize, cells: f32| (((at[i] as f32 + (xy[i] as f32 + 0.5) / 5.0) * size[i] as f32 / cells) as u32).min(size[i] - 1); + [one(0, 64.0), one(1, 36.0)] + } + + /// Where the fill notes texel `p` of a `size` picture (`keep_reads`): its place's index from + /// `ONCE_AT`, if the keep reads it. + fn noted_at(p: [u32; 2], size: [u32; 2]) -> Option { + let g = [(p[0] as f32 + 0.5) / size[0] as f32 * 64.0, (p[1] as f32 + 0.5) / size[1] as f32 * 36.0]; + let at = [(g[0] as u32).min(63), (g[1] as u32).min(35)]; + let xy = [(((g[0] - at[0] as f32) * 5.0) as u32).min(4), (((g[1] - at[1] as f32) * 5.0) as u32).min(4)]; + (keep_texel(at, xy, size) == p).then_some((at[1] * 64 + at[0]) * 25 + xy[1] * 5 + xy[0]) + } + + /// The fill notes every place the keep reads, each by the one texel the keep reads there, at + /// the sizes the title draws (and every texel of a picture too small for 5 x 5 places a cell); + /// both programs find a place in the same words. + #[test] + fn the_fill_notes_each_place_the_keep_reads() { + for size in [[640, 360], [1280, 720], [1920, 1080], [2560, 1440], [3840, 2160]] { + for i in 0..25 * FRAME_CELLS.0 * FRAME_CELLS.1 { + let (cell, place) = (i / 25, i % 25); + let p = keep_texel([cell % 64, cell / 64], [place % 5, place / 5], size); + assert_eq!(noted_at(p, size), Some(i), "{size:?}: place {place} of cell {cell} at {p:?}"); + } + } + let small: Vec = (0..64).filter_map(|i| noted_at([i % 8, i / 8], [8, 8])).collect(); + assert_eq!(small.len(), 64, "8x8: every texel is a place"); + for line in [ + "float2 at_texel = (float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(width, height) / float2(64.0, 36.0);", + "uint2 p = min(uint2(at_texel), uint2(width - 1, height - 1));", + "ONCE_AT + (at.y * 64 + at.x) * 25 + y * 5 + x", + ] { + assert!(FRAME_KEEP_HLSL.contains(line) && AMBIENT_FILL_R9G9B9E5_HLSL.contains(line), "{line}"); + } + } + + /// The interleaved-gradient noise the fill's shade turns its samples by, at texel `p` and the + /// round's place `phase`, as the programs take it. + fn ign(p: [f32; 2], phase: u32) -> f32 { + let shift = 5.588238 * phase as f32; + (52.9829189f32 * ((p[0] + shift) * 0.06711056 + (p[1] + shift) * 0.00583715).fract()).fract() + } + + /// With the dither moving, the noise at a texel takes another value each frame, all of [0, 1) + /// over the round of 64 frames, and comes back after it; still, it is the old pattern every + /// frame. The three programs that use it take it the same way, from the fill's constants. + #[test] + fn the_dither_moves_with_the_frame_and_comes_back_after_64() { + assert!((0..200).all(|f| dither_phase(f, false) == 0), "still"); + assert_eq!([0, 1, 63, 64, 130].map(|f| dither_phase(f, true)), [0, 1, 63, 0, 2]); + for p in [[0.0f32, 0.0], [3.0, 7.0], [100.0, 50.0], [1919.0, 1079.0]] { + let still = (52.9829189f32 * (p[0] * 0.06711056 + p[1] * 0.00583715).fract()).fract(); + assert_eq!(ign(p, 0), still, "place 0: the still pattern"); + let round: Vec = (0..64).map(|k| ign(p, k)).collect(); + let mean = round.iter().sum::() / 64.0; + assert!((mean - 0.5).abs() < 0.05, "{p:?}: mean over the round {mean}"); + assert!(round.iter().all(|v| (0.0..1.0).contains(v))); + assert!(round.iter().cloned().fold(1.0, f32::min) < 0.05 && round.iter().cloned().fold(0.0, f32::max) > 0.95, "{p:?}: all of [0, 1)"); + assert!(round.windows(2).all(|w| (w[0] - w[1]).abs() > 1e-3), "{p:?}: another value each frame"); + } + let moved = "dot(float2(p) + 5.588238 * float((sky_ready >> 8) & 63u), float2(0.06711056, 0.00583715))"; + assert!(AMBIENT_FILL_R9G9B9E5_HLSL.contains(moved)); + for program in [AMBIENT_FILL_HLSL, AMBIENT_FILL_WRITE_HLSL] { + assert!(program.contains(&moved.replace("float2(p)", "float2(tid)"))); + } + for program in [AMBIENT_FILL_HLSL, AMBIENT_FILL_WRITE_HLSL, AMBIENT_FILL_R9G9B9E5_HLSL] { + assert!(!program.contains("dot(float2(tid), float2(0.06711056") && !program.contains("dot(float2(p), float2(0.06711056"), "no still noise left"); + } + } + + /// The probes' garbage as the keep leaves it out with `XCL_AMBIENT_MEAN_CLEAN`. + fn probes_garbage(c: [f32; 3]) -> bool { + (c[1] < 0.5 * c[0].min(c[2]) && c[0].max(c[2]) > 0.02) || (c[2] > 2.5 * c[1] && c[2] > c[0] && c[2] > 0.02) + } + + /// The clean keep leaves out what the fill drops of the resolve's light, in the same words: + /// magenta and the bluer kind, not the sky's blue, a sunset, grey, or what is too dim to tell. + #[test] + fn the_clean_keep_leaves_out_what_the_fill_drops() { + assert!(probes_garbage([1.0, 0.1, 0.9]), "magenta"); + assert!(probes_garbage([0.05, 0.1, 0.6]), "the bluer kind"); + assert!(!probes_garbage([0.3, 0.45, 0.8]), "the sky's blue"); + assert!(!probes_garbage([1.0, 0.45, 0.15]), "a sunset"); + assert!(!probes_garbage([0.5, 0.5, 0.5]) && !probes_garbage([0.0; 3]), "grey, black"); + assert!(!probes_garbage([0.015, 0.0, 0.015]), "too dim to tell"); + assert!(!probes_garbage([0.2, 0.9, 0.1]) && !probes_garbage([1.0, 0.3, 0.1]), "green, orange"); + for test in ["c.g < 0.5 * min(c.r, c.b) && max(c.r, c.b) > 0.02", "c.b > 2.5 * c.g && c.b > c.r && c.b > 0.02"] { + assert!(FRAME_KEEP_HLSL.contains(test), "{test}"); + assert!(AMBIENT_FILL_R9G9B9E5_HLSL.contains(&test.replace("c.", "was.")), "the fill's: {test}"); + } + } + + /// The keep and the fill frame after frame on a room of surfaces that send out `albedo` of the + /// light they get – `direct` from lamps or the sun, which the resolve's light does not hold, and + /// the fill's – with the resolve leaving `title` on each (bounded by `MOST` 2 times the + /// estimate), every surface lit by `level` of the mean the keep counts (`counted`: of a + /// surface's light `sent`, given the fill's note there – the title's light and all of it – if + /// any): the estimate it settles at. + fn settle(level: f32, albedo: &[f32], direct: &[f32], title: &[f32], counted: impl Fn(f32, Option<(f32, f32)>) -> f32) -> f32 { + let mut noted: Vec> = vec![None; albedo.len()]; + let mut estimate = 0.0; + for _ in 0..1000 { + let sent = |i: usize| albedo[i] * (direct[i] + noted[i].map_or(0.0, |(_, all)| all)); + estimate = level * (0..albedo.len()).map(|i| counted(sent(i), noted[i])).sum::() / albedo.len() as f32; + for (i, note) in noted.iter_mut().enumerate() { + let was = title[i].min(2.0 * estimate); + *note = Some((was, was.max(estimate))); + } + } + estimate + } + + /// Without `XCL_AMBIENT_ONCE` the fill's light comes back to it: 1.9 times one bounce in a room + /// whose walls send out 0.6 of what they get, more by far with pale walls. With it, a little + /// under one bounce where a lamp lights a wall (its wall counted as if white: no more than the + /// fill added is taken out) – where the title's share of the light alone would count the lamp's + /// light out with the fill's, and leave nothing. Where the title's own light is above the + /// estimate (outdoors by day) nothing changes. + #[test] + fn once_is_one_bounce_and_keeps_what_the_lamps_give() { + let fed = |sent: f32, _: Option<(f32, f32)>| sent; + let once = |sent: f32, note: Option<(f32, f32)>| { + note.map_or(sent, |(title, all)| sent * (1.0 - (all - title).max(0.0) / all.max(sent).max(1e-6)).clamp(0.0, 1.0)) + }; + let share = |sent: f32, note: Option<(f32, f32)>| note.map_or(sent, |(title, all)| sent * (title / all.max(1e-6)).clamp(0.0, 1.0)); + // a room the rays leave dark: a lamp lights one of its two walls + let (walls, lamp, dark) = ([0.6, 0.6], [1.0, 0.0], [0.0, 0.0]); + let one_bounce = 0.8 * 0.6 * 0.5; + let fed_back = settle(0.8, &walls, &lamp, &dark, fed); + assert!((fed_back - one_bounce / (1.0 - 0.8 * 0.6)).abs() < 1e-4 && fed_back > 1.9 * one_bounce, "fed back: {fed_back}"); + let one = settle(0.8, &walls, &lamp, &dark, once); + assert!((one - one_bounce / (1.0 + 0.8 * 0.4 / 2.0)).abs() < 1e-4 && one > 0.85 * one_bounce, "once: {one}"); + assert!(settle(0.8, &walls, &lamp, &dark, share) < 1e-6, "the title's share alone: nothing left"); + let pale = [0.9, 0.9]; + assert!(settle(0.8, &pale, &lamp, &dark, fed) > 3.0 * settle(0.8, &pale, &lamp, &dark, once), "pale walls"); + let day = [1.0, 1.0]; + assert_eq!(settle(0.8, &walls, &day, &day, once), settle(0.8, &walls, &day, &day, fed), "by day"); + } + /// R11G11B10_FLOAT of non-negative values (round to nearest), and back. fn pack_r11g11b10(c: [f32; 3]) -> u32 { let one = |v: f32, bits: u32| -> u32 { @@ -2995,6 +3366,23 @@ mod tests { level: &[[f32; 4]], ) -> Option<[u32; 64]> { assert_eq!(level.len(), LEVEL_ELEMENTS as usize); + let mut whole = level.to_vec(); + whole.resize(LEVEL_BUFFER_ELEMENTS as usize, [0.0; 4]); + run_with_level(pick, format, raw_t0, depth, consts, texels, &whole).map(|(image, _)| image) + } + + /// `run_on_image` with the whole level buffer (`XCL_AMBIENT_ONCE`'s notes too) given and read + /// back after the dispatch. + unsafe fn run_with_level( + pick: impl Fn(&AmbientDevice) -> &ID3D12PipelineState, + format: DXGI_FORMAT, + raw_t0: bool, + depth: Option<&[f32; 64]>, + consts: [u32; 8], + texels: &[u32; 64], + level: &[[f32; 4]], + ) -> Option<([u32; 64], Vec<[f32; 4]>)> { + assert_eq!(level.len(), LEVEL_BUFFER_ELEMENTS as usize); let mut dev: Option = None; if D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { crate::gpu::recomp::runner::skip_test("no GPU"); @@ -3034,11 +3422,12 @@ mod tests { ..Default::default() }; const PITCH: usize = 256; - let level_bytes = LEVEL_ELEMENTS as usize * 16; + let level_bytes = LEVEL_BUFFER_ELEMENTS as usize * 16; let image_at = level_bytes.next_multiple_of(512); let depth_at = image_at + 8 * PITCH; let upload = make(D3D12_HEAP_TYPE_UPLOAD, &buffer((depth_at + 8 * PITCH) as u64), D3D12_RESOURCE_STATE_GENERIC_READ); let readback = make(D3D12_HEAP_TYPE_READBACK, &buffer((8 * PITCH) as u64), D3D12_RESOURCE_STATE_COPY_DEST); + let level_readback = make(D3D12_HEAP_TYPE_READBACK, &buffer(level_bytes as u64), D3D12_RESOURCE_STATE_COPY_DEST); let image = make( D3D12_HEAP_TYPE_DEFAULT, &D3D12_RESOURCE_DESC { @@ -3166,7 +3555,7 @@ mod tests { Format: DXGI_FORMAT_UNKNOWN, ViewDimension: D3D12_UAV_DIMENSION_BUFFER, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { - Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_ELEMENTS, StructureByteStride: 16, ..Default::default() }, + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: LEVEL_BUFFER_ELEMENTS, StructureByteStride: 16, ..Default::default() }, }, }; create_srv(dev_raw, t0, &t0_view, cpu0 as usize); @@ -3189,6 +3578,8 @@ mod tests { dispatch(list_raw, 1, 1, 1); list_x::transition(list_raw, image.as_raw() as usize, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); list_x::pc_copy_texture_region(list_raw, &in_readback, 0, 0, 0, &in_image, std::ptr::null()); + list_x::transition(list_raw, ad.sky_level.as_raw() as usize, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + copy_buffer(list_raw, level_readback.as_raw(), 0, ad.sky_level.as_raw(), 0, level_bytes as u64); list.Close().unwrap(); let cl: ID3D12CommandList = list.cast().unwrap(); @@ -3208,7 +3599,11 @@ mod tests { std::ptr::copy_nonoverlapping((r as *const u8).add(y * PITCH) as *const u32, out[y * 8..].as_mut_ptr(), 8); } readback.Unmap(0, None); - Some(out) + let mut level_out = vec![[0.0f32; 4]; LEVEL_BUFFER_ELEMENTS as usize]; + level_readback.Map(0, None, Some(&mut r)).unwrap(); + std::ptr::copy_nonoverlapping(r as *const u8, level_out.as_mut_ptr() as *mut u8, level_bytes); + level_readback.Unmap(0, None); + Some((out, level_out)) } /// A reflection far brighter than the room is held to `hold` times the light around (the @@ -3276,6 +3671,104 @@ mod tests { assert!((s[2] / s[1] - sky_blue[2] / sky_blue[1]).abs() < 0.05, "sky light keeps its hue: {s:?}"); } + /// The fill's shade turns its samples by the noise: a crease is shaded, otherwise at another + /// place of the dither's round, the same at the same place. + #[test] + fn the_shade_moves_with_the_dither_on_gpu() { + // a wall 1 m away, its right half 0.5 m away: the far side of the step is shaded + let mut depth = [0.1f32; 64]; + for row in depth.chunks_mut(8) { + row[4..].fill(0.2); + } + let mut level = vec![[0.0f32; 4]; LEVEL_ELEMENTS as usize]; + level[0] = [0.2, 0.2, 0.2, 0.2]; + let consts = |phase: u32| [8, 8, 8, 8, 1, 0.55f32.to_bits(), fill_bits(true, false, false, phase), PRE_SKY_FALLBACK.to_bits()]; + let run = |phase: u32| unsafe { run_on_image(|ad| &ad.fill_r9_pso, DXGI_FORMAT_R32_UINT, false, Some(&depth), consts(phase), &[0; 64], &level) }; + let Some(still) = run(0) else { return }; + // (unshaded: the sky's share, nothing else lights it) + let unshaded = 0.2 * config().sky; + assert!(still.iter().any(|&v| luma(unpack_r9(v)) < 0.95 * unshaded), "the step shades: {:?}", still.map(|v| luma(unpack_r9(v)))); + let Some(again) = run(0) else { return }; + assert_eq!(still, again, "the same place of the round: the same shade"); + let Some(moved) = run(1) else { return }; + assert_ne!(still, moved, "the next place: the samples turned"); + } + + /// With `XCL_AMBIENT_ONCE` the fill notes, at each place the keep reads, the luminance of the + /// title's light it left there (bounded by the estimate) and of all it wrote; without, nothing. + #[test] + fn the_fill_notes_its_light_where_the_keep_reads_on_gpu() { + let cfg = config(); + // the sky's level only (no frame's light kept yet, no depth): the estimate is its share + let mut level = vec![[0.0f32; 4]; LEVEL_BUFFER_ELEMENTS as usize]; + level[0] = [0.2, 0.2, 0.2, 0.2]; + let found = 0.2 * cfg.sky; + // the title left a little on the top half, more than the bound lets through below + let (little, much) = (pack_r9([0.02; 3]), pack_r9([0.5; 3])); + let mut texels = [much; 64]; + texels[..32].fill(little); + let consts = |once: bool| [8, 8, 1, 1, 0, cfg.ao.to_bits(), fill_bits(true, true, once, 0), PRE_SKY_FALLBACK.to_bits()]; + let run = |once: bool| unsafe { run_with_level(|ad| &ad.fill_r9_pso, DXGI_FORMAT_R32_UINT, false, None, consts(once), &texels, &level) }; + let Some((_, noted)) = run(true) else { return }; + for i in 0..64u32 { + let p = [i % 8, i / 8]; + let at = noted_at(p, [8, 8]).expect("every texel of an 8x8 picture is a place the keep reads"); + let n = noted[(ONCE_AT + at) as usize]; + let (title, all) = if i < 32 { (luma(unpack_r9(little)), found) } else { (found * cfg.most, found * cfg.most) }; + assert!((n[0] - title).abs() < 0.01 * title && (n[1] - all).abs() < 0.01 * all, "texel {p:?}: {n:?} for ({title}, {all})"); + } + assert_eq!(noted[ONCE_AT as usize..].iter().filter(|n| n[1] > 0.0).count(), 64, "one note a texel"); + let Some((_, none)) = run(false) else { return }; + assert!(none[ONCE_AT as usize..].iter().all(|n| *n == [0.0; 4]), "off: nothing noted"); + } + + /// The keep with `XCL_AMBIENT_ONCE` takes the fill's light out of what each place sent back: + /// all of it where the place sent no more than the fill gave it, what the fill added where it + /// sent more (a lamp lit it too), nothing where nothing was noted. With + /// `XCL_AMBIENT_MEAN_CLEAN` the probes' garbage is no light; with neither the cells are kept + /// as before. + #[test] + fn the_keep_leaves_out_the_fills_light_and_the_garbage_on_gpu() { + // (it reads the light, R11G11B10_FLOAT, from a UAV) + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + if !unsafe { typed_uav_load_supported(dev.as_ref().unwrap(), DXGI_FORMAT_R11G11B10_FLOAT) } { + crate::gpu::recomp::runner::skip_test("no typed UAV loads of R11G11B10_FLOAT"); + return; + } + // an 8x8 picture: the cells (0..8, 0..4) read its first texel, the cells (0..8, 5..8) the + // first of its second row + let magenta = [1.0, 0.0625, 1.0]; + let mut texels = [pack_r11g11b10([0.25; 3]); 64]; + texels[0] = pack_r11g11b10([0.5; 3]); + texels[8] = pack_r11g11b10(magenta); + let mut level = vec![[0.0f32; 4]; LEVEL_BUFFER_ELEMENTS as usize]; + for (cell, title, all) in [(0u32, 0.0f32, 1.0f32), (1, 0.5, 1.0), (2, 0.0, 0.1)] { + let at = (ONCE_AT + cell * 25) as usize; + level[at..at + 25].fill([title, all, 0.0, 0.0]); + } + let run = |once: bool, clean: bool| unsafe { + run_with_level(|ad| &ad.keep_pso, DXGI_FORMAT_R11G11B10_FLOAT, false, None, [8, 8, keep_bits(once, clean), 0, 0, 1.0f32.to_bits(), 0, 0], &texels, &level) + }; + let cell = |level: &[[f32; 4]], x: u32, y: u32| level[2 + (y * 64 + x) as usize]; + let grey = |c: [f32; 4], v: f32| (0..3).all(|k| (c[k] - v).abs() < 1e-4) && c[3] == 1.0; + let is = |c: [f32; 4], v: [f32; 3]| (0..3).all(|k| (c[k] - v[k]).abs() < 1e-4); + let Some((_, once)) = run(true, false) else { return }; + // none of it the title's; half of it; the fill's 0.1 of the lamp-lit 0.5; no note + for (x, v) in [(0, 0.0), (1, 0.25), (2, 0.4), (3, 0.5)] { + assert!(grey(cell(&once, x, 0), v), "cell {x}: {:?} for {v}", cell(&once, x, 0)); + } + assert!(is(cell(&once, 0, 5), magenta), "garbage kept without the clean keep: {:?}", cell(&once, 0, 5)); + let Some((_, clean)) = run(false, true) else { return }; + assert!((0..4).all(|x| grey(cell(&clean, x, 0), 0.5)), "notes not read without one bounce"); + assert!(grey(cell(&clean, 0, 5), 0.0), "garbage: no light, {:?}", cell(&clean, 0, 5)); + let Some((_, neither)) = run(false, false) else { return }; + assert!((0..4).all(|x| grey(cell(&neither, x, 0), 0.5)) && is(cell(&neither, 0, 5), magenta), "as before"); + } + #[test] fn scan_cbv_indices_resolves_each_64k_mirror_page_independently() { const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8771550554..14e2cde9a5 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -69,6 +69,9 @@ struct State { batch_buf: Option, batch_used: u64, batch_open: bool, + /// the textures this recording's bake draws pick by index, for its submit + /// (`bake_sources`, `title_textures::bake_at_submit`) + bake_sources: Vec, } /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its @@ -407,24 +410,43 @@ fn hold_res_until_reset(allocator: usize, mut bufs: Vec) { ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); } -fn put_free_bufs(bufs: Vec) { +/// `bufs` the GPU is done with, kept in `FREE_RES` for the recordings that need one next: at once +/// when the submit fences of their recording passed (`exact`), else after `free_hold`. +fn put_free_bufs(bufs: Vec, exact: bool) { if bufs.is_empty() { return; } let free_cap = two_pass_cap().min(FREE_RES_CAP); + let hold = free_hold(exact, console_list::retire_age()); let gone = { let mut free = FREE_RES.lock().unwrap(); free.cap = free_cap; let now = std::time::Instant::now(); let mut gone = free.take_idle(now, FREE_RES_IDLE); for b in bufs { - gone.extend(free.put(now, b.bytes, b.dev, b)); + gone.extend(free.put_held(now, hold, b.bytes, b.dev, b)); } gone }; drop(gone); } +/// How long a two-pass buffer handed back to `FREE_RES` waits before a recording takes it again. +/// None when the submit fences of the recording that used it passed (`exact`, `FENCED_RES`): the +/// GPU is done with it. `retire` (`console_list::retire_age`) when an allocator reset or the time +/// in `UNKNOWN_RES` says so: that bookkeeping misses a submit now and then. +/// +/// (A hold for every buffer, with the idle ones let go `FREE_RES_IDLE` after they were handed back, +/// let them go just as they could be taken: with both at 2 s next to nothing was taken again, and +/// the two-pass buffers alive stood at the cap with half of them kept for reuse.) +fn free_hold(exact: bool, retire: std::time::Duration) -> std::time::Duration { + if exact { + std::time::Duration::ZERO + } else { + retire + } +} + const FENCE_WAIT_LIMIT: std::time::Duration = std::time::Duration::from_millis(10); const FENCE_WAIT_RESCAN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(1); const FENCE_WAIT_YIELD_POLLS: u32 = 64; @@ -609,7 +631,7 @@ fn retire_recording_res(allocator: usize, bufs: Vec, marks: Vec<(usi if !untracked && !marks.is_empty() { let marks: Vec<(ID3D12Fence, u64)> = marks.into_iter().map(|(_, f, v)| (f, v)).collect(); if marks.iter().all(|(f, v)| unsafe { fence_state(f, *v) == FenceState::Completed }) { - put_free_bufs(bufs); + put_free_bufs(bufs, true); return; } let bytes: u64 = bufs.iter().map(|b| b.bytes).sum(); @@ -647,7 +669,7 @@ fn reclaim_fenced() -> u64 { WAIT_BACKOFF_UNTIL_MS.store(0, Ordering::Release); } } - put_free_bufs(reclaimed_bufs); + put_free_bufs(reclaimed_bufs, true); reclaimed } @@ -660,7 +682,8 @@ pub(super) fn release_allocator_res(allocator: usize) { let gone = FREE_RES.lock().unwrap().take_idle(std::time::Instant::now(), FREE_RES_IDLE); drop(gone); } else { - put_free_bufs(bufs); + // (an allocator reset, or time, says the GPU is done with them: `free_hold`) + put_free_bufs(bufs, false); } } @@ -669,7 +692,7 @@ fn take_free(dev: usize, min: u64, max: u64) -> Option { reclaim_fenced(); let (gone, picked) = { let mut free = FREE_RES.lock().unwrap(); - (free.take_idle(std::time::Instant::now(), FREE_RES_IDLE + console_list::retire_age()), free.take(dev, min, max)) + (free.take_idle(std::time::Instant::now(), FREE_RES_IDLE), free.take(dev, min, max)) }; // (let go outside the lock) drop(gone); @@ -729,11 +752,12 @@ impl Aging { static UNKNOWN_RES: Mutex> = Mutex::new(Aging::new(UNKNOWN_RES_CAP)); /// Buffers the GPU is done with, kept for the recordings that need one next (`FREE_RES`): each -/// with when it was handed back, its bytes and its device, oldest first. What it keeps is what -/// recordings took again in the last `FREE_RES_IDLE`, and at most `cap` bytes, so a steady frame -/// takes back what the one before it handed back and makes none. +/// with when it was handed back, its bytes, its device and how long it is held before it is +/// taken again (`free_hold`), oldest first. What it keeps is what recordings took again in the +/// last `FREE_RES_IDLE` they could, and at most `cap` bytes, so a steady frame takes back what the +/// one before it handed back and makes none. struct FreePool { - free: Vec<(std::time::Instant, u64, usize, T)>, + free: Vec<(std::time::Instant, u64, usize, T, std::time::Duration)>, bytes: u64, cap: u64, } @@ -746,11 +770,16 @@ impl FreePool { /// Keep `item` of `bytes` on the device `dev` from `now`. Past the cap the oldest go (what /// is returned). fn put(&mut self, now: std::time::Instant, bytes: u64, dev: usize, item: T) -> Vec { + self.put_held(now, std::time::Duration::ZERO, bytes, dev, item) + } + + /// `put`, the item taken again only `hold` after `now` (`free_hold`). + fn put_held(&mut self, now: std::time::Instant, hold: std::time::Duration, bytes: u64, dev: usize, item: T) -> Vec { self.bytes += bytes; - self.free.push((now, bytes, dev, item)); + self.free.push((now, bytes, dev, item, hold)); let mut over = Vec::new(); while self.bytes > self.cap && !self.free.is_empty() { - let (_, b, _, t) = self.free.remove(0); + let (_, b, _, t, _) = self.free.remove(0); self.bytes -= b; over.push(t); } @@ -759,17 +788,21 @@ impl FreePool { /// The smallest kept on `dev` of `min..=max` bytes, of those the last handed back (so the /// ones no recording needs grow old and go). - /// One handed back less than `console_list::retire_age` ago is not taken yet. + /// One held (`put_held`) is not taken before its hold is over. fn take(&mut self, dev: usize, min: u64, max: u64) -> Option { - let (now, retire) = (std::time::Instant::now(), console_list::retire_age()); + self.take_at(std::time::Instant::now(), dev, min, max) + } + + /// `take` at `now`. + fn take_at(&mut self, now: std::time::Instant, dev: usize, min: u64, max: u64) -> Option { let i = self .free .iter() .enumerate() - .filter(|(_, &(at, b, d, _))| d == dev && b >= min && b <= max && now.saturating_duration_since(at) >= retire) - .min_by_key(|&(i, &(_, b, _, _))| (b, std::cmp::Reverse(i)))? + .filter(|(_, &(at, b, d, _, hold))| d == dev && b >= min && b <= max && now.saturating_duration_since(at) >= hold) + .min_by_key(|&(i, &(_, b, ..))| (b, std::cmp::Reverse(i)))? .0; - let (_, b, _, t) = self.free.remove(i); + let (_, b, _, t, _) = self.free.remove(i); self.bytes -= b; Some(t) } @@ -793,7 +826,7 @@ impl FreePool { Some( self.free .drain(..n) - .map(|(_, b, _, t)| { + .map(|(_, b, _, t, _)| { self.bytes -= b; t }) @@ -801,12 +834,14 @@ impl FreePool { ) } - /// What was kept `age` or longer at `now`, no recording having taken it. + /// What could be taken for `age` or longer at `now` (from the end of its hold), no recording + /// having taken it. (Holds differ, so these are not only the oldest ones.) fn take_idle(&mut self, now: std::time::Instant, age: std::time::Duration) -> Vec { - let n = self.free.iter().take_while(|&&(at, ..)| now.saturating_duration_since(at) >= age).count(); - self.free - .drain(..n) - .map(|(_, b, _, t)| { + let (idle, kept): (Vec<_>, Vec<_>) = + std::mem::take(&mut self.free).into_iter().partition(|&(at, _, _, _, hold)| now.saturating_duration_since(at) >= hold.saturating_add(age)); + self.free = kept; + idle.into_iter() + .map(|(_, b, _, t, _)| { self.bytes -= b; t }) @@ -1096,6 +1131,7 @@ fn install_reset( let res_untracked = std::mem::take(&mut s.res_untracked); let had_fb = !s.fb_uses.is_empty(); s.fb_uses.clear(); + s.bake_sources.clear(); (old, std::mem::take(&mut s.uma), res_bufs, res_marks, res_untracked, had_fb, old_resolution) }); if !res_bufs.is_empty() || !res_marks.is_empty() || res_untracked || had_fb { @@ -1476,6 +1512,41 @@ unsafe fn uncover_indexed(indices: &[u32], view_heap: u32, bake: bool) { } } +/// `res`, textures a bake's draw on `list` picks by index, are made ready for it again at the +/// list's submit (`bake_sources`, `title_textures::bake_at_submit`): a placement between the +/// draw and the submit shadows them again. +fn keep_bake_sources(list: *mut c_void, res: Vec) { + if res.is_empty() { + return; + } + with(list, |s| { + for r in res { + if !s.bake_sources.contains(&r) { + s.bake_sources.push(r); + } + } + }); +} + +/// The textures the bake draws recorded on `lists` (the PC lists of a submit, as the draws +/// had them) pick by index, each once, taken: a list submitted again has them made ready once. +pub(super) fn bake_sources(lists: &[*mut c_void]) -> Vec { + let mut out = Vec::new(); + for &l in lists { + let Some(entry) = STATES.get(l as usize) else { continue }; + let mut s = entry.state.lock().unwrap(); + if !entry.live.load(Ordering::Acquire) || s.bake_sources.is_empty() { + continue; + } + for r in std::mem::take(&mut s.bake_sources) { + if !out.contains(&r) { + out.push(r); + } + } + } + out +} + /// `XCL_CAPTURE_FRAME`: a draw or dispatch of the title's on `this` (`gfx`: with the graphics /// root arguments), with the root arguments, heaps and pipeline it has, until the call returns. pub(super) unsafe fn capture_work(this: *mut c_void, kind: impl FnOnce() -> super::capture::WorkKind, gfx: bool) -> super::capture::Guard { @@ -2679,7 +2750,7 @@ unsafe fn defer_execute_indirect(this: *mut c_void, tp: &Arc (Some(va), slot, h), None => (None, 0, None), }; - let region = batch_region_bytes(indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint)); + let region = batch_region_bytes(cold_record_need(indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint), hint, fb_slot != 0, cold_records_bytes())); let ty = super::list_x::tracked_list_type(this); if defer_check(true, ty, super::capture::on(), max, region, batch_records_bytes()).is_err() { return false; @@ -2742,7 +2813,7 @@ fn indirect_record_need(record_bytes: u64, split: u32) -> u64 { } /// Record bytes sized from async GPU `SCALE_ARGS_HLSL` feedback (`hint_groups`): `None` (cold) -/// keeps the full `indirect_record_need` (no cold-start clamping); `Some(0)` takes +/// keeps the full `indirect_record_need` (no cold-start clamping here: `cold_record_need`); `Some(0)` takes /// `RECORD_MIN.min(max_need)`; `Some(g)` reserves `2 × g` records up to `max_need`. fn indirect_record_need_hint(record_bytes: u64, split: u32, hint_groups: Option) -> u64 { let max_need = indirect_record_need(record_bytes, split); @@ -2753,6 +2824,34 @@ fn indirect_record_need_hint(record_bytes: u64, split: u32, hint_groups: Option< } } +/// `XCL_TWO_PASS_COLD_MB` (4 by default; `0`: as the draw alone; read once): the most record bytes +/// a two-pass ExecuteIndirect asks for while its pipeline's feedback slot has given no readback yet +/// (`cold_record_need`). As the draw alone, each such draw asked for up to 32 MiB (`INDIRECT_RECORDS`) +/// and a recording held that: a retail world's first second has its pipelines cold on every list, +/// and at world entry the two-pass buffers alive went to the cap of 1 GiB and some 1,900 draws +/// were skipped in 6 s. Most of these draws have no groups or a few; 4 MiB holds 628 groups of the +/// title's largest records (6,672 B). +fn cold_records_bytes() -> u64 { + static MB: std::sync::OnceLock = std::sync::OnceLock::new(); + *MB.get_or_init(|| std::env::var("XCL_TWO_PASS_COLD_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(4).min(128)) << 20 +} + +/// The record bytes of a two-pass ExecuteIndirect that needs `need` (`indirect_record_need_hint` +/// with `hint`): at most `cold` (`cold_records_bytes`; 0: no limit) while its pipeline has a +/// feedback slot (`has_slot`) that has given no readback yet. A command with more groups keeps +/// what fits – `SCALE_ARGS_HLSL` drops the groups past the records and puts what it asked for in +/// the slot (counted as clamped) – and the slot's next readback sizes the pipeline's draws from +/// then on (`IndirectFeedbackSlot::apply_window`): one or two frames after its first draw. A +/// pipeline with no slot (feedback off, or all slots taken) never learns of it: its draws ask +/// for what they would alone. +fn cold_record_need(need: u64, hint: Option, has_slot: bool, cold: u64) -> u64 { + if hint.is_none() && has_slot && cold != 0 { + need.min(cold) + } else { + need + } +} + const FEEDBACK_HEADER_U32S: usize = 2; const FEEDBACK_SLOTS: usize = 4096; const FEEDBACK_BYTES: u64 = ((FEEDBACK_HEADER_U32S + FEEDBACK_SLOTS) as u64) * 4; @@ -3319,7 +3418,8 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); } let cap = two_pass_cap(); - let block = acquire_two_pass_buf_with_cap(dev, size, remaining, remaining, "two-pass argument scratch", cap, FENCE_WAIT_LIMIT)? + let (min, preferred, most) = scratch_window(size, remaining); + let block = acquire_two_pass_buf_with_cap(dev, min, preferred, most, "two-pass argument scratch", cap, FENCE_WAIT_LIMIT)? .ok_or_else(|| refuse_two_pass("two-pass argument scratch", size, cap))?; let b = block.res.clone(); with(this, |s| { @@ -3334,6 +3434,14 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res Ok((b, 0)) } +/// The bytes of a kept buffer a scratch block of `size` takes (`acquire_two_pass_buf_with_cap`): +/// first one of up to twice its size, as a record buffer takes, then – when no new one can be made – +/// any the recording's `remaining` scratch bytes hold. (Any up to `remaining` first took the record +/// buffers of 16 MiB and less from the recordings that needed them next, for 256 KiB of arguments.) +fn scratch_window(size: u64, remaining: u64) -> (u64, u64, u64) { + (size, size.saturating_mul(2).min(remaining).max(size), remaining) +} + /// The root UAVs of the pass that rewrites a two-pass ExecuteIndirect's arguments /// (`SCALE_ARGS_HLSL`), as (root slot, GPU address): every view its program declares gets one. /// @@ -4301,7 +4409,8 @@ unsafe fn execute_indirect_snapshot( Some((va, slot, h)) => (Some(va), slot, h), None => (None, 0, None), }; - let (res_buf, res_va, region, records) = records_for(this, indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint), record_bytes, batch)?; + let need = cold_record_need(indirect_record_need_hint(record_bytes, tp.mesh_groups_per_record, hint), hint, fb_slot != 0, cold_records_bytes()); + let (res_buf, res_va, region, records) = records_for(this, need, record_bytes, batch)?; let cap = record_groups(region, record_bytes, tp.mesh_groups_per_record); if cap == 0 { return Err(format!("a record of {record_bytes} B does not fit the record buffer")); @@ -4439,14 +4548,34 @@ unsafe fn execute_indirect_snapshot( trace_ui_draw(this, raw_pso, pso, true); } super::ambient::diag_path("ExecuteIndirect", pso, raw_pso, count_buf, max); - // a split compute program's one Dispatch-only command runs its chain (`dispatch_chain`) + // (binds a compute root signature and a pipeline: before the dispatch's or draw's own) + let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf); + // a split compute program's one Dispatch-only command runs its chain (`dispatch_chain`), from + // the counts as the guard let them through: its slicer clamps each to 65 535 but runs a + // partial split's whole count in one dispatch, up to 65 535^3 groups of garbage (#3536) if compute && max == 1 && count_buf == 0 && signature.dispatch_only().is_some() { - let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { - super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, with(this, |s| s.allocator), address, - |root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3], None, 0).map(|_| ())) + let address = match &checked { + Some(c) => Some(c.gpu_address()), + None => indirect_address(args, args_off_title, args_off), + }; + let chained = address.map_or(Ok(false), |address| { + let (out, _) = checked.as_ref().map_or((0, 0), |c| c.arguments()); + // (the slicer reads the checked counts as a root SRV) + if out != 0 { + super::list_x::transition(this, out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + } + let r = super::real::dispatch_chain::execute_indirect(list, raw_pso, pso, with(this, |s| s.allocator), address, + |root| bind_abi_with_root_resolved(this, list, raw_pso, pso, false, root, [0; 3], None, 0).map(|_| ())); + if out != 0 { + super::list_x::transition(this, out, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + } + r }); match chained { Ok(true) => { + if let Some(c) = &checked { + c.read(this); + } ei_work(this, dispatches, super::targets::RAN); count(DISPATCHES); // a split program's chain is the title's pass too: the stand-in lighting follows it @@ -4460,6 +4589,9 @@ unsafe fn execute_indirect_snapshot( } Ok(false) => {} Err(e) => { + if let Some(c) = &checked { + c.read(this); + } ei_work(this, dispatches, super::targets::SKIPPED); count(DISPATCHES_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -4473,8 +4605,6 @@ unsafe fn execute_indirect_snapshot( if gfx && super::present::trace_planes_from().is_some() { trace_plane_draw(this, raw_pso, true); } - // (binds a compute root signature and a pipeline: before the dispatch's or draw's own) - let checked = super::indirect_guard::check(this, pso, sig, max, args, args_off, count_buf); match bind_abi_resolved(this, list, raw_pso, pso, gfx) { Ok(b) => { let mut whole = None; @@ -6183,7 +6313,9 @@ unsafe fn bind_abi_with_root_resolved( let bake = super::pso_async::is_kept(original); let trace = super::indexed::trace_on(); let uncover = (bake || super::indexed::uncover_all()) && super::title_textures::has_shadowed(); - if let Some(l) = layout.as_deref().filter(|_| trace || uncover) { + // (a bake's sources are seen to again at its list's submit, shadowed now or not) + let keep = bake && super::title_textures::bake_at_submit(); + if let Some(l) = layout.as_deref().filter(|_| trace || uncover || keep) { let indices = super::indexed::indices(l, &args, u); // (what the draw finds, before it is seen to) if trace { @@ -6192,6 +6324,9 @@ unsafe fn bind_abi_with_root_resolved( if uncover { uncover_indexed(&indices, heaps[0], bake); } + if keep { + keep_bake_sources(this, super::indexed::resources(&indices, heaps[0])); + } } } let b = Bound { rs, views, original, pso: pc, io: views[0], allocator }; @@ -7454,6 +7589,25 @@ void main(uint t : SV_GroupIndex) { remove_state_for_test(to); } + /// The textures a recording's bake draws pick (`keep_bake_sources`) are taken once, each + /// once, at the submit of its lists, and a reset drops those of a recording not submitted. + #[test] + fn a_recordings_bake_sources_are_taken_at_its_submit_and_dropped_at_its_reset() { + let (a, b) = (0x7103_0001usize as *mut c_void, 0x7103_0002usize as *mut c_void); + let unknown = 0x7103_0003usize as *mut c_void; + keep_bake_sources(a, vec![0xA1, 0xA2]); + keep_bake_sources(a, vec![0xA2, 0xA3]); + keep_bake_sources(b, vec![0xA3, 0xB1]); + assert_eq!(bake_sources(&[a, b, unknown]), vec![0xA1, 0xA2, 0xA3, 0xB1]); + assert!(STATES.get(unknown as usize).is_none(), "a list with no state gets none"); + assert!(bake_sources(&[a, b]).is_empty(), "a list submitted again has them made ready once"); + keep_bake_sources(a, vec![0xA4]); + install_reset(a, 0, 0, None); + assert!(bake_sources(&[a]).is_empty()); + remove_state_for_test(a); + remove_state_for_test(b); + } + #[test] fn reset_keys_uma_to_the_lists_native_allocator_backing() { let list = 0x7101_7001usize as *mut c_void; @@ -9009,10 +9163,257 @@ void main(uint t : SV_GroupIndex) { assert_eq!(p.bytes, 0); } + /// A kept buffer whose recording's submit fences passed is taken again at once, one an + /// allocator reset handed back only after its hold (`retire_age`); and one goes idle + /// `FREE_RES_IDLE` after it could first be taken. (Measured from when it was handed back, a + /// hold as long as `FREE_RES_IDLE` let it go the moment it could be taken.) + #[test] + fn kept_two_pass_buffers_are_taken_after_their_hold_and_go_idle_after_that() { + use std::time::{Duration, Instant}; + let (t, ms) = (Instant::now(), Duration::from_millis(1)); + let retire = Duration::from_secs(2); + let mib = 1u64 << 20; + let mut p: FreePool<&str> = FreePool::new(1 << 30); + p.put_held(t, free_hold(false, retire), mib, 1, "after an allocator reset"); + p.put_held(t, free_hold(true, retire), mib, 1, "after its fences"); + assert_eq!(p.take_at(t, 1, 0, u64::MAX), Some("after its fences"), "the GPU is done with it: at once"); + assert_eq!(p.take_at(t + retire - ms, 1, 0, u64::MAX), None, "held"); + assert!(p.take_idle(t + retire, FREE_RES_IDLE).is_empty(), "not idle the moment it can be taken"); + assert!(p.take_idle(t + retire + FREE_RES_IDLE - ms, FREE_RES_IDLE).is_empty()); + assert_eq!(p.take_at(t + retire + FREE_RES_IDLE - ms, 1, 0, u64::MAX), Some("after an allocator reset")); + // idle only once it could be taken for `FREE_RES_IDLE`, of every hold + p.put_held(t, retire, mib, 1, "held"); + p.put(t + retire, mib, 1, "not held"); + assert!(p.take_idle(t + retire + FREE_RES_IDLE - ms, FREE_RES_IDLE).is_empty()); + assert_eq!(p.take_idle(t + retire + FREE_RES_IDLE, FREE_RES_IDLE), vec!["held", "not held"]); + assert_eq!((p.bytes, p.free.len()), (0, 0)); + } + + /// A scratch block takes a kept buffer of up to twice its size, else a new one is made; a larger + /// one (a record buffer the next recording needs) only when no new one can be made. + #[test] + fn scratch_blocks_take_kept_buffers_of_their_size() { + use std::time::Instant; + let (t, kib) = (Instant::now(), 1u64 << 10); + assert_eq!(scratch_window(SCRATCH_BLOCK, SCRATCH_CAP), (SCRATCH_BLOCK, 2 * SCRATCH_BLOCK, SCRATCH_CAP)); + assert_eq!(scratch_window(SCRATCH_BLOCK, SCRATCH_BLOCK), (SCRATCH_BLOCK, SCRATCH_BLOCK, SCRATCH_BLOCK), "within what the recording has left"); + let (min, preferred, most) = scratch_window(SCRATCH_BLOCK, SCRATCH_CAP); + let mut p: FreePool<&str> = FreePool::new(1 << 30); + p.put(t, 12 << 20, 1, "12 MiB of records"); + assert_eq!(p.take_at(t, 1, min, preferred), None, "the record buffer stays for records"); + p.put(t, 384 * kib, 1, "384 KiB"); + assert_eq!(p.take_at(t, 1, min, preferred), Some("384 KiB")); + assert_eq!(p.take_at(t, 1, min, most), Some("12 MiB of records"), "when no new one can be made"); + } + + /// A two-pass ExecuteIndirect of a pipeline whose feedback slot has given no readback yet asks + /// for at most `XCL_TWO_PASS_COLD_MB` (4 MiB: 628 groups of 6,672 B records, not the 32 MiB of + /// its draw alone); a command with more keeps 628 and its slot's next readback sizes the + /// pipeline's draws as they would be alone. Without a slot, or with the limit off, as alone. + #[test] + fn cold_indirect_draws_ask_for_the_cold_records_until_their_feedback() { + let mib = 1u64 << 20; + let alone = indirect_record_need_hint(6672, 1, None); + assert_eq!(alone, 32 * mib); + let cold = cold_record_need(alone, None, true, 4 * mib); + assert_eq!(cold, 4 * mib); + assert_eq!(record_groups(record_buffer_bytes(cold), 6672, 1), 628); + assert_eq!(cold_record_need(alone, None, false, 4 * mib), alone, "no slot: nothing would ever say it needs more"); + assert_eq!(cold_record_need(alone, None, true, 0), alone, "XCL_TWO_PASS_COLD_MB=0"); + assert_eq!(cold_record_need(mib, None, true, 4 * mib), mib, "never more than the draw alone"); + // a command of 5,000 groups at its first draw: 628 kept, and the readback after it (the + // slot's cap was 628) gives the draws after it all of them + let mut slot = IndirectFeedbackSlot::new(); + slot.in_flight_cap = record_groups(record_buffer_bytes(cold), 6672, 1); + slot.apply_window(5_000 + 1); + let hint = slot.hint(); + assert_eq!(hint, Some(5_000)); + assert_eq!(cold_record_need(indirect_record_need_hint(6672, 1, hint), hint, true, 4 * mib), alone); + // one with no groups: the least record buffer + let mut empty = IndirectFeedbackSlot::new(); + empty.in_flight_cap = 628; + empty.apply_window(1); + assert_eq!(cold_record_need(indirect_record_need_hint(6672, 1, empty.hint()), empty.hint(), true, 4 * mib), RECORD_MIN); + } + + /// What `replay_two_pass_buffers` saw, by kind (0: argument scratch blocks, 1: record buffers). + #[derive(Debug, Default)] + struct Replay { + /// asked for, taken again from the pool, made, refused at the cap + asked: [u64; 2], + taken: [u64; 2], + made: [u64; 2], + refused: [u64; 2], + /// bytes of two-pass buffers alive at most, and of the ones recordings held at most + peak_alive: u64, + peak_held: u64, + /// the same at the end + end_alive: u64, + end_held: u64, + } + + /// The rules of `FREE_RES` a replay follows. + #[derive(Clone, Copy, Debug, PartialEq)] + enum PoolRules { + /// as merged into amd/next: every buffer handed back held for `retire_age` (amd-dev's + /// `take`), while the idle ones went `FREE_RES_IDLE` after they were handed back whenever + /// more were (main's `put_free_bufs`) – both 2 s; a scratch block took any kept buffer up to + /// its recording's 16 MiB; a cold ExecuteIndirect asked for what its draw would alone + Merged, + /// `free_hold`, `scratch_window`, `cold_record_need` + Now, + } + + /// `acquire_two_pass_buf_with_cap` in a replay: a kept buffer within `preferred`, else a new one + /// within the cap (the oldest kept go to make room), else a kept one up to `most` (no fence + /// waits, no shrinking). + #[allow(clippy::too_many_arguments)] + fn replay_acquire(pool: &mut FreePool, alive: &mut u64, cap: u64, r: &mut Replay, now: std::time::Instant, kind: usize, (min, preferred, most): (u64, u64, u64)) -> Option { + r.asked[kind] += 1; + // (`take_free`: the idle ones go first) + for b in pool.take_idle(now, FREE_RES_IDLE) { + *alive -= b; + } + if let Some(b) = pool.take_at(now, 1, min, preferred) { + r.taken[kind] += 1; + return Some(b); + } + if *alive + min > cap { + for b in pool.take_room(*alive + min - cap).unwrap_or_default() { + *alive -= b; + } + } + if *alive + min <= cap { + *alive += min; + r.made[kind] += 1; + return Some(min); + } + if let Some(b) = pool.take_at(now, 1, min, most) { + r.taken[kind] += 1; + return Some(b); + } + r.refused[kind] += 1; + None + } + + /// The two-pass buffers of 30 s of a retail world (next-r6: RX 9070 XT, `XCL_TWO_PASS_MB=1024`, + /// no batching, 6.7 frames a second): a dozen recordings a frame with two-pass ExecuteIndirects + /// of 6,672 B records, each with an argument scratch block and a record buffer as large as its + /// largest draw so far (`ensure_res_buffer_with_cap`), handed back when its submit fences pass + /// three frames on (`reclaim_fenced`; the run had 77 buffers in flight at world entry). Every + /// recording's first draw is of a pipeline with no feedback yet for the first 8 frames. + fn replay_two_pass_buffers(rules: PoolRules) -> Replay { + use std::time::{Duration, Instant}; + const FRAMES: u32 = 200; + const LISTS: u32 = 12; + const DRAWS: u32 = 6; + const LAG: u32 = 3; + const COLD_FRAMES: u32 = 8; + const RECORD: u64 = 6672; + // the groups a pipeline's feedback holds at most: most none or a few (of 12,032 draws of + // one program 10,246 read back empty, amd-dev's XCL_TRACE_ARGS) + const GROUPS: [u32; 9] = [0, 0, 0, 3, 8, 20, 60, 150, 600]; + let frame = Duration::from_millis(150); + // (`console_list::retire_age`'s default) + let retire = Duration::from_secs(2); + let cap = 1u64 << 30; + let t0 = Instant::now(); + let mut pool: FreePool = FreePool::new(cap.min(FREE_RES_CAP)); + let mut alive = 0u64; + let mut r = Replay::default(); + let mut held: VecDeque<(u32, Vec)> = VecDeque::new(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + for f in 0..FRAMES { + let now = t0 + frame * f; + while held.front().is_some_and(|&(done, _)| done <= f) { + let (_, bufs) = held.pop_front().unwrap(); + let (hold, idle) = match rules { + PoolRules::Merged => (retire, Duration::ZERO), + PoolRules::Now => (free_hold(true, retire), FREE_RES_IDLE), + }; + for b in pool.take_idle(now, idle) { + alive -= b; + } + for b in bufs { + for gone in pool.put_held(now, hold, b, 1, b) { + alive -= gone; + } + } + } + for _ in 0..LISTS { + let mut bufs = Vec::new(); + let scratch = match rules { + PoolRules::Merged => (SCRATCH_BLOCK, SCRATCH_CAP, SCRATCH_CAP), + PoolRules::Now => scratch_window(SCRATCH_BLOCK, SCRATCH_CAP), + }; + if let Some(b) = replay_acquire(&mut pool, &mut alive, cap, &mut r, now, 0, scratch) { + bufs.push(b); + let mut have = 0; + for d in 0..DRAWS { + let hint = (f >= COLD_FRAMES || d > 0).then(|| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + GROUPS[(seed % GROUPS.len() as u64) as usize] + }); + let need = indirect_record_need_hint(RECORD, 1, hint); + let need = record_buffer_bytes(if rules == PoolRules::Now { cold_record_need(need, hint, true, cold_records_bytes()) } else { need }); + if have >= need { + continue; + } + if let Some(b) = replay_acquire(&mut pool, &mut alive, cap, &mut r, now, 1, (need, need.saturating_mul(2), u64::MAX)) { + have = b; + bufs.push(b); + } + } + } + held.push_back((f + LAG, bufs)); + } + let held_now: u64 = held.iter().flat_map(|(_, b)| b.iter()).sum(); + (r.peak_held, r.peak_alive) = (r.peak_held.max(held_now), r.peak_alive.max(alive)); + (r.end_held, r.end_alive) = (held_now, alive); + } + r + } + + /// Replayed (`replay_two_pass_buffers`), the buffers kept for reuse are taken again and the + /// two-pass buffers alive stay near what the recordings hold, with no draw refused at world + /// entry. As merged, next to nothing was taken again: buffers were held as long as they were + /// kept, so they went just as they could be taken (next-r6: 179 of 18,369 taken again, 1 GiB + /// alive with 550 MiB kept), and cold draws of 32 MiB each took the buffers to the cap. + #[test] + fn two_pass_buffers_are_taken_again_and_stay_near_what_recordings_hold() { + let mib = |b: u64| b >> 20; + for rules in [PoolRules::Merged, PoolRules::Now] { + let r = replay_two_pass_buffers(rules); + for (k, kind) in ["argument scratch", "record buffers"].iter().enumerate() { + println!( + "{rules:?} {kind}: {} asked, {} taken again ({:.1} %), {} made, {} refused", + r.asked[k], + r.taken[k], + 100.0 * r.taken[k] as f64 / r.asked[k].max(1) as f64, + r.made[k], + r.refused[k] + ); + } + println!("{rules:?}: alive at most {} MiB (recordings held at most {} MiB); at the end {} MiB alive, {} MiB held", mib(r.peak_alive), mib(r.peak_held), mib(r.end_alive), mib(r.end_held)); + } + let merged = replay_two_pass_buffers(PoolRules::Merged); + assert!(merged.taken[0] * 10 < merged.asked[0] && merged.taken[1] * 10 < merged.asked[1], "as merged, next to nothing is taken again: {merged:?}"); + assert!(merged.refused.iter().sum::() > 0, "as merged, cold draws reach the cap: {merged:?}"); + let now = replay_two_pass_buffers(PoolRules::Now); + assert_eq!(now.refused, [0, 0], "{now:?}"); + for k in 0..2 { + assert!(now.taken[k] * 10 >= now.asked[k] * 9, "nine in ten taken again: {now:?}"); + } + assert!(now.peak_alive <= 2 * now.peak_held, "alive at most twice what the recordings hold: {now:?}"); + assert!(now.end_alive <= 2 * now.end_held, "{now:?}"); + } + /// Record buffers come in half-step sizes from 256 KiB, and a draw has at least as many /// groups as before: none drops groups it drew under power-of-two MiB buckets. Cold - /// ExecuteIndirect starts at full `indirect_record_need` (no cold clamping) before shrinking - /// on feedback. + /// ExecuteIndirect starts at full `indirect_record_need` (no cold clamping; the draws' limit is + /// `cold_record_need`'s) before shrinking on feedback. #[test] fn two_pass_record_buffers_fit_what_their_draws_need() { let kib = 1u64 << 10; @@ -9786,6 +10187,227 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) } } + /// Deferred runs (`batch_commands`) on the GPU with stand-ins for the two passes and XCL's + /// argument rewrite: the "compute pass" writes each group's record (from the start of its + /// region) with its draw's number, the "mesh pass" (a mesh shader) copies the records it reads + /// out by draw. One recording's draws (DispatchMesh and one-command ExecuteIndirect, some + /// with no groups) in two runs whose regions start again at the start of its batch record + /// buffer (`batch_open` before the second), then another recording's run in a batch record + /// buffer of its own, both lists in one submit: every mesh pass reads its own draw's records. + #[test] + fn gpu_deferred_runs_read_their_own_records() { + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + #[repr(C, align(8))] + struct Sub { + ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, + v: T, + } + #[repr(C)] + struct Stream { + rs: Sub<*mut c_void>, + ms: Sub, + mask: Sub, + rast: Sub, + depth: Sub, + rtv: Sub, + samples: Sub, + } + let src = r#" +#define RS "UAV(u0), UAV(u1), UAV(u2), UAV(u3), UAV(u4), UAV(u5)" +RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer rec : register(u1); +RWByteAddressBuffer o : register(u2); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void cs(uint3 g : SV_GroupID) { rec.Store(g.x * 4u, io.Load(0)); } +struct V { float4 p : SV_Position; }; +[RootSignature(RS)] +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void ms(uint3 g : SV_GroupID, out vertices V v[3], out indices uint3 t[1]) { + SetMeshOutputCounts(0, 0); + // (never: io dword 1 is 0; the validator wants the outputs written) + if (io.Load(4) != 0u) { v[0].p = float4(0.0f, 0.0f, 0.0f, 1.0f); t[0] = uint3(0u, 0u, 0u); } + o.Store((io.Load(0) * 16u + g.x) * 4u, rec.Load(g.x * 4u)); +} +"#; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + skip_test("no GPU"); + return; + } + if !crate::gpu::recomp::runner::mesh_shaders_supported().unwrap_or(false) { + skip_test("no mesh shaders"); + return; + } + let dev = dev.unwrap(); + // (recording, run, draw number, groups, ExecuteIndirect) + let draws: [(usize, usize, u32, u32, bool); 10] = + [(0, 0, 1, 3, false), (0, 0, 2, 0, true), (0, 0, 3, 4, true), (0, 1, 4, 1, false), (0, 1, 5, 2, true), (0, 1, 6, 4, true), (1, 0, 7, 2, true), (1, 0, 8, 4, false), (1, 0, 9, 0, true), (1, 0, 10, 3, true)]; + unsafe { + let cs = crate::gpu::recomp::dxc::compile(src, "cs", "cs_6_6", &[]).unwrap(); + let msb = crate::gpu::recomp::dxc::compile(src, "ms", "ms_6_6", &[]).unwrap(); + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &cs).unwrap(); + let cpso: ID3D12PipelineState = dev + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as _, BytecodeLength: cs.len() }, + ..Default::default() + }) + .unwrap(); + let mut stream = Stream { + rs: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, v: rs.as_raw() }, + ms: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, v: D3D12_SHADER_BYTECODE { pShaderBytecode: msb.as_ptr() as _, BytecodeLength: msb.len() } }, + mask: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, v: u32::MAX }, + rast: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, v: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() } }, + depth: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, v: D3D12_DEPTH_STENCIL_DESC::default() }, + rtv: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, v: D3D12_RT_FORMAT_ARRAY::default() }, + samples: Sub { ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, v: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 } }, + }; + let dev2: ID3D12Device2 = dev.cast().unwrap(); + let mpso: ID3D12PipelineState = dev2 + .CreatePipelineState(&D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: std::mem::size_of::(), pPipelineStateSubobjectStream: &mut stream as *mut Stream as *mut c_void }) + .unwrap(); + let sig_of = |ty: D3D12_INDIRECT_ARGUMENT_TYPE| -> ID3D12CommandSignature { + let a = [D3D12_INDIRECT_ARGUMENT_DESC { Type: ty, ..Default::default() }]; + let mut s: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: a.as_ptr(), NodeMask: 0 }, None, &mut s).unwrap(); + s.unwrap() + }; + let (dsig, msig) = (sig_of(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH), sig_of(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH)); + let (rw_rs, rw_pso) = scale_indirect_pipeline(&dev).unwrap(); + let buffer = |bytes: u64, cpu: bool| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = if cpu { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() } + } else { + D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() } + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + // one block of 256 B a draw: [the commands at 32-byte steps (the title's), io, rewrite constants] + let (mem, out) = (buffer(3 * 256 * 16, true), buffer(256 * 16 * 4, true)); + // (each recording's batch record buffer, and its argument scratch block) + let records = [buffer(256 * 4, false), buffer(256 * 4, false)]; + let scratch = [buffer(256 * 16, false), buffer(256 * 16, false)]; + let map = |b: &ID3D12Resource| -> *mut u32 { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + p as *mut u32 + }; + let (m, o) = (map(&mem), map(&out)); + std::ptr::write_bytes(o, 0, 256 * 16); + let mem_va = mem.GetGPUVirtualAddress(); + let (args_at, io_at, consts_at) = (0u64, 256 * 16, 2 * 256 * 16); + let mut steps: [Vec>; 2] = [vec![Vec::new(), Vec::new()], vec![Vec::new()]]; + let mut slot = [0u64; 2]; + for &(list, run, d, groups, indirect) in &draws { + let k = d as u64; + std::ptr::copy_nonoverlapping([groups, 1, 1].as_ptr(), m.add((args_at / 4 + 8 * k) as usize), 3); + *m.add(((io_at + 256 * k) / 4) as usize) = d; + // its region: from the start of the buffer in each run (`batch_region` after a flush) + let at = steps[list][run].len() as u64; + let region = records[list].GetGPUVirtualAddress() + 256 * at; + let io = mem_va + io_at + 256 * k; + let views = [io, region, out.GetGPUVirtualAddress(), io, io, io]; + let work = if indirect { + // (count 1, stride 12, the DispatchMesh argument at 0, split 1, cap 4; no count + // buffer, no feedback slot) + let c = [1u32, 12, 0, 1, 4, 0, 0, 0, 0, 0]; + std::ptr::copy_nonoverlapping(c.as_ptr(), m.add(((consts_at + 256 * k) / 4) as usize), c.len()); + let dst = slot[list] * 256; + slot[list] += 1; + let rewrite = Rewrite { rs: rw_rs.as_raw() as usize, pso: rw_pso.as_raw() as usize, views: scale_views(mem_va + consts_at + 256 * k, None, mem_va + args_at + 32 * k, scratch[list].GetGPUVirtualAddress() + dst, None), groups: 1 }; + // (a later run of the recording finds its block in INDIRECT_ARGUMENT) + let before = if run == 0 { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }; + DeferredWork::Indirect { rewrite, block: scratch[list].as_raw() as usize, before, companion: dsig.as_raw() as usize, sig: msig.as_raw() as usize, compute_at: dst, mesh_at: dst + 12 } + } else { + DeferredWork::Mesh { groups, mesh_groups: groups } + }; + let stage = |pso: &ID3D12PipelineState| StageBind { rs: rs.as_raw() as usize, pso: pso.as_raw() as usize, views }; + steps[list][run].push(Step::Draw(DrawSnap { compute: stage(&cpso), mesh: stage(&mpso), work })); + } + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut lists = Vec::new(); + for (list, runs) in steps.iter().enumerate() { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let l6: ID3D12GraphicsCommandList6 = l.cast().unwrap(); + for (run, run_steps) in runs.iter().enumerate() { + // a later run of a recording: the last one's mesh passes may still read its + // buffer (`flush_two_pass` leaves `batch_open`); a buffer just taken: none + let open = run > 0; + for c in batch_commands(run_steps, records[list].as_raw() as usize, open) { + let res = |raw: usize| { + let p = raw as *mut c_void; + ID3D12Resource::from_raw_borrowed(&p).cloned() + }; + match c { + Cmd::Barriers { all, uav, transitions } => { + let uav = uav.and_then(res); + let held: Vec<(ID3D12Resource, D3D12_RESOURCE_STATES, D3D12_RESOURCE_STATES)> = transitions.iter().filter_map(|&(r, a, b)| Some((res(r)?, a, b))).collect(); + let t: Vec<_> = held.iter().map(|(r, a, b)| (r, *a, *b)).collect(); + emit_barrier_set(&l, all, uav.as_ref(), &t); + } + Cmd::ComputeRs(r) => { + let p = r as *mut c_void; + l.SetComputeRootSignature(ID3D12RootSignature::from_raw_borrowed(&p)); + } + Cmd::GraphicsRs(r) => { + let p = r as *mut c_void; + l.SetGraphicsRootSignature(ID3D12RootSignature::from_raw_borrowed(&p)); + } + Cmd::Pso(p) => { + let p = p as *mut c_void; + l.SetPipelineState(ID3D12PipelineState::from_raw_borrowed(&p)); + } + Cmd::ComputeView(s, va) => l.SetComputeRootUnorderedAccessView(s, va), + Cmd::GraphicsView(s, va) => l.SetGraphicsRootUnorderedAccessView(s, va), + Cmd::Dispatch(n) => l.Dispatch(n, 1, 1), + Cmd::DispatchMesh(n) => l6.DispatchMesh(n, 1, 1), + Cmd::Indirect(sig, b, at) => { + let (sp, bp) = (sig as *mut c_void, b as *mut c_void); + l.ExecuteIndirect(ID3D12CommandSignature::from_raw_borrowed(&sp).unwrap(), 1, ID3D12Resource::from_raw_borrowed(&bp).unwrap(), at, None::<&ID3D12Resource>, 0); + } + Cmd::Bind(_) | Cmd::StencilRef(_) | Cmd::Topology(_) | Cmd::Scissors(_) | Cmd::TimesBegin(_) | Cmd::TimesEnd => {} + } + } + } + emit_transition(&l, &scratch[list], D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + l.Close().unwrap(); + lists.push((alloc, l)); + } + let submit: Vec> = lists.iter().map(|(_, l)| Some(l.cast().unwrap())).collect(); + queue.ExecuteCommandLists(&submit); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + for &(_, _, d, groups, indirect) in &draws { + let got: Vec = (0..4).map(|g| *o.add((d * 16 + g) as usize)).collect(); + let want: Vec = (0..4).map(|g| if g < groups { d } else { 0 }).collect(); + assert_eq!(got, want, "the records the mesh pass of draw {d} read (ExecuteIndirect {indirect})"); + } + mem.Unmap(0, None); + out.Unmap(0, None); + } + } + /// With heap windows the two-pass programs read the memory windows from the shared heap /// (`pso::mem_windows`): both passes' binds set it on a list that has none, as `bind_abi` does. /// (Heap windows are opt-in: run with `XCL_HEAP_WINDOWS=1`, else skipped.) @@ -10987,7 +11609,7 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} let buf = unsafe { TwoPassBuf::make(&dev, RECORD_MIN, "pool cap test") }.unwrap(); let expected_cap = two_pass_cap().min(FREE_RES_CAP); - put_free_bufs(vec![buf]); + put_free_bufs(vec![buf], true); let pool_cap = FREE_RES.lock().unwrap().cap; while FREE_RES.lock().unwrap().take(key, 0, u64::MAX).is_some() {} assert_eq!(pool_cap, expected_cap); diff --git a/crates/xcl/src/hle/d3d12x/indirect_guard.rs b/crates/xcl/src/hle/d3d12x/indirect_guard.rs index 435776e5b6..47c4e74e07 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_guard.rs +++ b/crates/xcl/src/hle/d3d12x/indirect_guard.rs @@ -382,6 +382,12 @@ impl Checked { (self.guard.out.as_raw() as usize, self.slot as u64 * SLOT as u64) } + /// The GPU address of the checked counts (`arguments`), for a pass that reads them through a + /// root view; `read` after it. + pub(super) fn gpu_address(&self) -> u64 { + self.guard.out_va + self.slot as u64 * SLOT as u64 + } + /// After a pass read the counts at `arguments`: the buffer back to COMMON (its write and that /// read left it in UNORDERED_ACCESS). pub(super) unsafe fn read(&self, list: *mut c_void) { diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 22683eb4e0..98c19666d2 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -40,6 +40,37 @@ struct Batch { dead: Vec, /// (fence, value) a queue: all reached = nothing submitted before the batch closed is left marks: Vec<(ID3D12Fence, u64)>, + /// the title's submits when it closed (`note_submit`), for `XCL_LATE_RELEASE_LAG` + submits: u64, +} + +/// The title's submits so far (`note_submit`). +static SUBMITS: AtomicU64 = AtomicU64::new(0); + +/// A title's `ExecuteCommandLists` (not XCL's own submits): counted for `XCL_LATE_RELEASE_LAG`. +pub(super) fn note_submit() { + SUBMITS.fetch_add(1, Ordering::Relaxed); +} + +/// `XCL_LATE_RELEASE_LAG=n` (a diagnostic, 0 = off by default): a closed batch also waits for `n` +/// more submits of the title after it closed, as Whiplash's bury lag (64) does. With the fences +/// alone a batch goes once the queues are past the work submitted before the release; a GPU fault +/// that goes away with a lag points at a resource that later work still reaches (a stale view or +/// descriptor), not at the program that faulted. +fn lag() -> u64 { + static LAG: std::sync::OnceLock = std::sync::OnceLock::new(); + *LAG.get_or_init(|| { + let n = std::env::var("XCL_LATE_RELEASE_LAG").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + if n != 0 { + crate::xlog_info!("D3D12.X: XCL_LATE_RELEASE_LAG={n}: last releases wait for {n} more title submits too"); + } + n + }) +} + +/// Whether a batch closed at `closed` submits has waited out `lag` title submits by `now`. +fn lag_passed(closed: u64, now: u64, lag: u64) -> bool { + now.saturating_sub(closed) >= lag } #[derive(Default)] @@ -62,6 +93,11 @@ impl Held { /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`, /// and take out the batches every queue is past: what to release now. unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { + self.drain_at(queues, seal_now, SUBMITS.load(Ordering::Relaxed), lag()) + } + + /// `drain` with the title's submits so far (`submits`) and `XCL_LATE_RELEASE_LAG` (`lag`) given. + unsafe fn drain_at(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool, submits: u64, lag: u64) -> Vec { if !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) { let mut marks = Vec::with_capacity(queues.len()); let mut ok = true; @@ -98,11 +134,13 @@ impl Held { if ok { self.last_seal = Some(Instant::now()); let dead = std::mem::take(&mut self.open); - self.sealed.push_back(Batch { dead, marks }); + self.sealed.push_back(Batch { dead, marks, submits }); } } let mut gone = Vec::new(); - while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| super::real::fence_completed(&f) >= *v)) { + while self.sealed.front().is_some_and(|b| { + lag_passed(b.submits, submits, lag) && b.marks.iter().all(|(f, v)| super::real::fence_completed(&f) >= *v) + }) { gone.extend(self.sealed.pop_front().unwrap().dead); } gone @@ -158,7 +196,8 @@ static BUSY: Busy = Busy(Mutex::new(None)); pub unsafe fn hold(res: usize, pinned: bool) { HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(Dead::Resource(res)); let start = Instant::now(); - let busy = !pinned || BUSY.is(start); + // (with `XCL_LATE_RELEASE_LAG` nothing goes before more submits: no use waiting here) + let busy = !pinned || lag() != 0 || BUSY.is(start); if !busy { drain_known(true); while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { @@ -362,6 +401,25 @@ mod tests { assert!(held.is_empty()); } + /// `XCL_LATE_RELEASE_LAG`: a batch the queues are past still waits for that many title + /// submits after it closed, then goes; batches go in order. + #[test] + fn a_lag_holds_a_batch_for_more_title_submits() { + let mut held = Held::default(); + held.open.push(Dead::Resource(0x1000)); + // (no queues: the fences are passed at once; closed at 10 submits, lag 3) + assert!(unsafe { held.drain_at(&[], true, 10, 3) }.is_empty(), "closed at 10: not 3 submits later yet"); + held.open.push(Dead::Resource(0x2000)); + assert!(unsafe { held.drain_at(&[], true, 12, 3) }.is_empty(), "12 submits: the first batch is 2 past"); + assert_eq!(unsafe { held.drain_at(&[], false, 13, 3) }, vec![Dead::Resource(0x1000)], "13: the first batch goes alone"); + assert_eq!(unsafe { held.drain_at(&[], false, 15, 3) }, vec![Dead::Resource(0x2000)]); + assert!(held.is_empty()); + // lag 0: as without the switch + held.open.push(Dead::Resource(0x3000)); + assert_eq!(unsafe { held.drain_at(&[], true, 15, 0) }, vec![Dead::Resource(0x3000)]); + assert!(lag_passed(5, 5, 0) && !lag_passed(5, 4, 1) && lag_passed(5, 9, 4)); + } + /// A pipeline state XCL lets go goes into a batch (a list in flight may bind it), and the /// thread here releases it once the queues are past – through its COM Release. (That a batch /// waits for a busy queue is `a_held_resource_goes_when_the_queue_is_past_its_batch`.) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index d86f2ebb75..17e5154757 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5579,6 +5579,8 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { super::capture::kickoff(this, queue); let q_raw = queue_pin.as_raw(); + // (the sources of its bake draws: `title_textures::bake_at_submit`) + super::title_textures::ready_bake_sources(&super::bind::bake_sources(&[this])); real::prepare_title_submission(q_raw, &[this]); super::gpu_profile::note_queue(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 68d9c7cc9d..92957368ab 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1246,6 +1246,17 @@ fn module_of(addr: usize) -> usize { h as usize } +/// Whether the hook that calls this was called from the module that holds `orig` (the hooked +/// method's original): the D3D12 runtime calling one of its objects' methods itself rather than +/// the title or XCL. Frame 0 is this function, 1 the hook, 2 the hook's caller. +#[inline(never)] +fn called_from_module_of(orig: usize) -> bool { + let mut frame = [std::ptr::null_mut::(); 1]; + let n = unsafe { windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace(2, 1, frame.as_mut_ptr(), std::ptr::null_mut()) }; + let module = module_of(orig); + n == 1 && module != 0 && module_of(frame[0] as usize) == module +} + /// Whether `obj` is an object XCL adopted (its vtable is one of XCL's). pub(super) unsafe fn is_adopted(obj: *mut c_void) -> bool { !obj.is_null() && crate::gpu::shader::readable(obj as usize, 8) && is_ext(*(obj as *const usize)) @@ -2747,6 +2758,12 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } drop(tracked_srv_lifetime.take()); if held { + // A last release the D3D12 runtime makes itself is left to the late-release thread, not + // drained here (that drain takes XCL's locks, `placements`' registry among them): with + // DRED on, the runtime lets a resource go inside its breadcrumb lock (a list's Reset), + // while a thread of XCL's that holds the registry waited for that lock in an allocator's + // Reset (`vram`'s zero-fill under `placements::note_use`) – the title stood still. + let pinned = pinned && !called_from_module_of(f as usize); super::late_release::hold(this as usize, pinned); } else if last { // (`XCL_LATE_RELEASE=0`: it goes now) @@ -13039,6 +13056,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis return; } super::gpu_awake::note_activity(); + super::late_release::note_submit(); super::capture::submit(this, std::slice::from_raw_parts(lists, n as usize)); crate::stall::note_submitter(); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's @@ -13072,6 +13090,9 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis crate::xlog_warn!("D3D12.X: ExecuteCommandLists rejected a poisoned physical recording"); return; } + // the sources of the lists' bake draws as the refresh below must find them + // (`title_textures::bake_at_submit`; the draws ran on the PC lists) + super::title_textures::ready_bake_sources(&super::bind::bake_sources(&mapped)); // textures in title memory the CPU wrote since: uploaded again first prepare_title_submission(this, title_lists); super::list_x::note_queue_for_lists(this as usize, &mapped); @@ -16443,3 +16464,49 @@ mod heap_release_order_tests { } } + +#[cfg(test)] +mod runtime_caller_tests { + use super::*; + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + + /// (0 not called, 1 false, 2 true) + static SEEN: AtomicU32 = AtomicU32::new(0); + + /// A hook as `res_release` is one: `lparam` is its "original". + unsafe extern "system" fn hook(_name: windows_sys::core::PCWSTR, _flags: u32, lparam: isize) -> i32 { + SEEN.store(1 + called_from_module_of(lparam as usize) as u32, Ordering::SeqCst); + 0 + } + + /// `res_release` leaves a last release the D3D12 runtime makes itself to the late-release + /// thread; it knows one by the caller's module, that of the original Release. Here the hook + /// is called by XCL's code and by kernelbase (as the runtime calls a hooked Release), with an + /// "original" in either module. + #[test] + fn a_hook_knows_whether_the_originals_module_called_it() { + unsafe { + let kernelbase = GetModuleHandleA(b"kernelbase.dll\0".as_ptr()); + assert!(!kernelbase.is_null()); + let theirs = GetProcAddress(kernelbase, b"EnumSystemLocalesEx\0".as_ptr()).expect("EnumSystemLocalesEx") as usize; + let ours = hook as usize; + let called_by = |via_kernelbase: bool, orig: usize| { + SEEN.store(0, Ordering::SeqCst); + if via_kernelbase { + let f: unsafe extern "system" fn(windows_sys::Win32::Globalization::LOCALE_ENUMPROCEX, u32, isize, *const c_void) -> i32 = std::mem::transmute(theirs); + f(Some(hook), 0, orig as isize, std::ptr::null()); + } else { + hook(std::ptr::null(), 0, orig as isize); + } + match SEEN.load(Ordering::SeqCst) { + 0 => panic!("the hook was not called"), + n => n == 2, + } + }; + assert!(called_by(true, theirs), "kernelbase called it, the original is kernelbase's"); + assert!(!called_by(true, ours), "kernelbase called it, the original is XCL's"); + assert!(called_by(false, ours), "XCL called it, the original is XCL's"); + assert!(!called_by(false, theirs), "XCL called it, the original is kernelbase's"); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index ce17ba81e2..646f46eafc 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -2630,6 +2630,41 @@ struct State { poison: Option, /// Dirty CPU pages whose write-watch bits were reset before an upload failed. retry_pages: Vec, + /// a CPU read whose copy back is waited for with the lock released (`readback_now`) + reading: Option, +} + +/// A CPU read's copy back on the GPU (`State::reading`; one at a time, `CPU_READ`): the range it +/// copied, its place among the copies back of the submissions (`ReadbackQueue::job_seq` when it +/// was recorded), and the parts of the range that changed since in a way the chunks' hashes do not +/// show (`spoil`): what copies back and immediates of later submissions landed there (they may +/// hold what the CPU had before, so the hashes stay), and pages decommitted (committed again they +/// hold zeros, and so may the hashes). Its copy does not land there. +struct Reading { + at: usize, + end: usize, + seq: u64, + spoiled: Vec<(usize, usize)>, +} + +impl State { + /// `[a, a + n)` changed while a CPU read's copy back is on the GPU (`Reading`). + fn spoil(&mut self, a: usize, n: usize) { + if let Some(r) = self.reading.as_mut() { + let (lo, hi) = (a.max(r.at), a.saturating_add(n).min(r.end)); + if lo < hi { + r.spoiled.push((lo, hi)); + } + } + } + + /// A copy back or an immediate of the submissions' (`seq`, `RbJob::seq`) landed in `[a, a + n)`: + /// one recorded after the CPU read's copy holds the newer bytes. + fn spoil_if_newer(&mut self, seq: u64, a: usize, n: usize) { + if self.reading.as_ref().is_some_and(|r| seq > r.seq) { + self.spoil(a, n); + } + } } /// The one 64 KiB of video memory the tiles of the windows without video memory of their own are @@ -3404,6 +3439,7 @@ unsafe fn new_state(dev: &ID3D12Device, windows: Vec<(usize, ID3D12Resource)>) - diag: ViewDiag { keep: view_switches().keep, stats: view_switches().stats, ..Default::default() }, poison: None, retry_pages: Vec::new(), + reading: None, }) } @@ -4444,6 +4480,7 @@ impl State { ReadyJob::Imm(job) => { for &(va, value, bytes, gen) in &job.writes { self.store_imm(va, value, bytes, gen); + self.spoil_if_newer(job.seq, va, (bytes & 0x7f) as usize); } RB_PENDING.fetch_sub(1, Ordering::Release); } @@ -4452,6 +4489,7 @@ impl State { for &(dst, off, len, gen) in &copies { // (the lists' own GPU writes, `readback_after_execute`) self.copy_back(job.ptr, dst, off, len, gen, true); + self.spoil_if_newer(job.seq, dst, len); } TILE_WORK[3].fetch_add(copies.iter().map(|c| c.2 as u64).sum(), Ordering::Relaxed); RB_PENDING.fetch_sub(1, Ordering::Release); @@ -5522,9 +5560,8 @@ impl State { } /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with -/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending -/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then -/// copies the range back from VRAM into CPU memory. +/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): what the GPU wrote +/// there is copied back into CPU memory, where the CPU did not write since (`readback_now_with`). pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; @@ -5535,12 +5572,28 @@ pub unsafe fn readback_now(va: usize, len: usize) { wait_and_check_ready(&rb, Drain::TitleDone, 2000, None); } } - let measure = super::memory_report::enabled(); + readback_now_with(&STATE, va, len); +} + +/// `readback_now` on the state in `state_lock` (the global one, or a test's). +unsafe fn readback_now_with(state_lock: &Mutex>, va: usize, len: usize) { + let is_global = std::ptr::eq(state_lock, &STATE); + let measure = is_global && super::memory_report::enabled(); let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); + let unlocked = cpu_read_unlocked(); + let _one = unlocked.then(|| CPU_READ.lock().unwrap_or_else(|e| e.into_inner())); let (mut uploads, mut timing) = UploadGateTiming::acquire(measure); - let excess = readback_now_locked(va, len, &mut uploads, &mut timing); + let rest = if unlocked { readback_unlocked(state_lock, va, len, &mut uploads, &mut timing) } else { Err(va) }; + let excess = match rest { + Ok(excess) => excess, + // (`XCL_CPU_READ_UNLOCKED=0`, or no readback queue: the lock is held all the way, as + // before; on the global state only, as `wait_upload_released` is) + Err(at) if is_global => readback_now_locked(at, va.saturating_add(len) - at, &mut uploads, &mut timing), + Err(_) => Vec::new(), + }; let times = timing.finish(); drop(uploads.take()); + drop(_one); drop(_upload_lifetime); // (recycled copy-back jobs past the pool's cap drop outside all locks) drop(excess); @@ -5549,6 +5602,388 @@ pub unsafe fn readback_now(va: usize, len: usize) { } } +/// `XCL_CPU_READ_UNLOCKED=0`: a CPU read (`readback_now`) holds the state's lock while the GPU +/// makes its copy back, as before (`readback_now_locked`). Otherwise (with a readback queue) the +/// copy is waited for with the lock and the upload gate released (`cpu_read_begin`, +/// `cpu_read_land`). A retail title's world on an RX 9070 XT: its threads held the lock 3.6–6.3 ms +/// a submit for CPU reads, and each submit waited 0.4–1.6 ms behind them for its own use of it, +/// its after stage 0.3–0.9 ms more. +fn cpu_read_unlocked() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_CPU_READ_UNLOCKED").map_or(true, |v| v.trim() != "0")) +} + +/// One CPU read's copy back at a time (`cpu_read_unlocked`): the state's readback list and +/// buffer are the read's from the copy's recording until it landed, and the copy is waited for +/// with `STATE` and `UPLOAD_GATE` released. Lock order: `UPLOAD_STATE_LIFETIME` (shared) → +/// `CPU_READ` → `UPLOAD_GATE` → `STATE`; never taken under the gate or `STATE`. +static CPU_READ: Mutex<()> = Mutex::new(()); + +/// `XCL_LOOK_STATS=2`: the CPU reads (`readback_now`) since the last sparse lock split line: +/// [reads, bytes asked for, µs with the state's lock held, µs waiting for the copy with it +/// released, copies made, 64-byte chunks landed] +static CPU_READS: super::look_stats::Sums<6> = super::look_stats::Sums::new(); + +/// The CPU reads part of the sparse lock split line (`CPU_READS`' sums over `submits`). +fn cpu_reads_line(x: &[u64; 6], submits: u64) -> String { + let n = submits.max(1) as f64; + let reads = x[0].max(1) as f64; + format!( + "CPU reads: {:.2} a submit, {:.0} KB each, {:.3} ms each with the lock held and {:.3} ms waiting for the copy without it, {:.1} chunks landed each, {:.1} copies each", + x[0] as f64 / n, + x[1] as f64 / reads / 1024.0, + x[2] as f64 / reads / 1e3, + x[3] as f64 / reads / 1e3, + x[5] as f64 / reads, + x[4] as f64 / reads + ) +} + +/// Wait until `fence` reaches `value`, 5 s at most (true: it did). Not for a holder of `STATE` +/// or `UPLOAD_GATE`. +unsafe fn wait_fence(fence: &ID3D12Fence, value: u64, dev: &ID3D12Device) -> bool { + thread_local! { + /// this thread's event for its waits (`fence::wait` takes a wake for an earlier + /// registration that gave up as no completion) + static EVENT: HANDLE = unsafe { windows::Win32::System::Threading::CreateEventW(None, false, false, None).unwrap_or_default() }; + } + match EVENT.with(|&ev| crate::gpu::fence::wait(fence, value, dev, (!ev.is_invalid()).then_some(ev), 5000)) { + Ok(()) => true, + Err(e) => { + crate::xlog_warn!("sparse: the queue has not reached fence value {value} (at {}: {e}): a CPU read's copy back is left out", super::real::fence_completed(fence)); + false + } + } +} + +/// What `cpu_read_begin` did. +enum CpuReadStep { + /// the read stops here: its tile clears did not go out (back in `to_zero` for the next) + Stop, + /// an upload slot the GPU still holds for the tile clears (back in `to_zero`): waited for + /// with the locks let go, then again + Wait(WaitTicket), + /// the copy before this one is still on the GPU (given up on): wait for the fence, then again + Busy(ID3D12Fence, u64, ID3D12Device), + /// nothing to copy before this address; the copy-back jobs to drop + Skip(usize, Vec), + Copy(CpuReadCopy), +} + +/// A piece of a CPU read's copy (`cpu_read_begin`): `[va, va + len)` of one tile, at `off` in the +/// readback buffer, the tile's video memory and CPU memory when it was recorded +/// (`TileEntry::pool`, `gen`), the hash each 64-byte chunk there was last sent with, and (made +/// with the lock released once the copy is done, `hash_copied`) the hash of each whole chunk the +/// copy holds (0 for a chunk only partly read). +struct CpuReadPart { + va: usize, + off: usize, + len: usize, + pool: (u32, u32), + gen: u32, + sent: Vec, + copied: Vec, +} + +/// A CPU read's copy submitted on the state's queue (`cpu_read_begin`), to land once the fence +/// reaches `value` (`cpu_read_land`). +struct CpuReadCopy { + fence: ID3D12Fence, + value: u64, + dev: ID3D12Device, + /// where the rest of the read begins + next: usize, + /// the readback buffer (`ptr` is its mapping), kept while the copy is read + _buf: ID3D12Resource, + ptr: *const u8, + parts: Vec, + /// copy-back jobs to drop outside the locks + excess: Vec, +} + +impl CpuReadCopy { + /// `CpuReadPart::copied`, made with the lock released: the hashes `cpu_read_land` gives the + /// chunks it lands. + unsafe fn hash_copied(&mut self) { + for part in &mut self.parts { + part.copied.clear(); + let end = part.va + part.len; + let mut c = part.va & !(CHUNK - 1); + while c < end { + let whole = c >= part.va && c + CHUNK <= end; + part.copied.push(if whole { chunk_hash(std::slice::from_raw_parts(self.ptr.add(part.off + (c - part.va)), CHUNK)) } else { 0 }); + c += CHUNK; + } + } + } +} + +/// The hashes the 64-byte chunks of `[a, a + n)` (in the tile at `t`, `e`) were last sent with: +/// `ZERO_HASH` for a page with none (all zero, or a hole). +fn sent_hashes(e: &TileEntry, t: usize, a: usize, n: usize) -> Vec { + let mut out = Vec::with_capacity(n / CHUNK + 2); + let mut c = a & !(CHUNK - 1); + while c < a + n { + let idx = (c - t) / PAGE; + out.push(e.sent[idx].as_deref().map_or(ZERO_HASH, |s| s[(c - t) % PAGE / CHUNK])); + c += CHUNK; + } + out +} + +/// Whether `[lo, hi)` meets one of `runs` (sorted by start). +fn meets(runs: &[(usize, usize)], lo: usize, hi: usize) -> bool { + runs.iter().take_while(|r| r.0 < hi).any(|r| r.1 > lo) +} + +/// `readback_now_with` when `cpu_read_unlocked`, with `CPU_READ` and the upload gate held: the +/// range in copies of the readback buffer one after the other, each waited for and landed with +/// `STATE` and the gate released. The copy-back jobs to drop outside all locks; `Err(at)`: the +/// state has no readback queue, and the read from `at` on holds the lock all the way. +unsafe fn readback_unlocked( + state_lock: &Mutex>, va: usize, len: usize, uploads: &mut Option, timing: &mut UploadGateTiming, +) -> Result, usize> { + let is_global = std::ptr::eq(state_lock, &STATE); + let lock = || if is_global { lock_state() } else { state_lock.lock().unwrap() }; + let deep = is_global && super::look_stats::deep(); + let stamp = || deep.then(std::time::Instant::now); + let since = |t: Option| t.map_or(0, |t| t.elapsed().as_micros() as u64); + let end = va.saturating_add(len); + let mut at = va; + let mut excess: Vec = Vec::new(); + // [µs with the lock, µs waiting without it, copies, chunks landed] + let mut x = [0u64; 4]; + while at < end { + let t = stamp(); + let step = { + let mut g = lock(); + let _held = is_global.then(|| holding(Holder::CpuRead)); + let Some(s) = g.as_mut() else { break }; + if s.window_index(at).is_none() { + break; + } + if s.rbq.is_none() { + return Err(at); + } + s.cpu_read_begin(at, end) + }; + x[0] += since(t); + match step { + CpuReadStep::Stop => break, + CpuReadStep::Wait(ticket) => { + if !timing.with_released(uploads, || wait_upload_released(ticket)) { + break; + } + } + CpuReadStep::Busy(fence, value, dev) => { + let t = stamp(); + let there = timing.with_released(uploads, || wait_fence(&fence, value, &dev)); + x[1] += since(t); + if !there { + break; + } + } + CpuReadStep::Skip(next, done) => { + excess.extend(done); + at = next; + } + CpuReadStep::Copy(mut copy) => { + excess.append(&mut copy.excess); + // (the copy is waited for and lands with the upload gate let go too: a submit's + // preparation goes on meanwhile) + let (there, landed) = timing.with_released(uploads, || { + let t = stamp(); + let there = wait_fence(©.fence, copy.value, ©.dev); + if there { + copy.hash_copied(); + } + x[1] += since(t); + let t = stamp(); + let (done, landed) = { + let mut g = lock(); + let _held = is_global.then(|| holding(Holder::CpuRead)); + match g.as_mut() { + Some(s) => s.cpu_read_land(©, there), + None => (Vec::new(), 0), + } + }; + x[0] += since(t); + excess.extend(done); + (there, landed) + }); + x[2] += 1; + x[3] += landed; + if !there { + break; + } + at = copy.next; + } + } + } + if deep { + CPU_READS.add(0, 1); + CPU_READS.add(1, len as u64); + for (k, v) in x.into_iter().enumerate() { + CPU_READS.add(2 + k, v); + } + } + Ok(excess) +} + +impl State { + /// The first half of a CPU read of `[at, end)` whose copy back is waited for with the lock + /// released (`readback_unlocked`): pending tile clears and mappings go first and the copies + /// back done land (they are older than this one), then a copy of as much of the range as the + /// readback buffer holds is submitted on the state's queue, with the hashes its chunks were + /// last sent with. `reading` follows what lands in the range until `cpu_read_land`. + /// + /// Unlike `readback_now_locked`, the CPU's writes there that are not sent yet are not scanned + /// and sent first: a chunk the CPU wrote since it was sent does not take the copy back + /// (`cpu_read_land`, as `land_page`) and goes up with the next look anyway, so sending it here + /// only had the GPU copy back what the CPU has. + unsafe fn cpu_read_begin(&mut self, at: usize, end: usize) -> CpuReadStep { + // (a copy given up on is still in the readback list and buffer) + if self.rb_last_fence != 0 && super::real::fence_completed(&self.fence) < self.rb_last_fence { + return CpuReadStep::Busy(self.fence.clone(), self.rb_last_fence, self.dev.clone()); + } + let zeroed = zero_runs(std::mem::take(&mut self.to_zero)); + if !zeroed.is_empty() { + for &(a, n) in &zeroed { + self.clear_sent_range(a, n); + } + // (as in `readback_now_locked`: clears that did not go out are journaled again before + // the upload gate is let go) + match self.upload_zeros(&zeroed) { + UploadStep::Done(PreparationOutcome::Ready) => {} + UploadStep::Wait(ticket) => { + rejournal_zeros(&mut self.to_zero, zeroed); + return CpuReadStep::Wait(ticket); + } + UploadStep::Done(_) => { + rejournal_zeros(&mut self.to_zero, zeroed); + return CpuReadStep::Stop; + } + } + } + self.flush_pending(); + let excess = self.land_finished_readbacks(); + let Some((buf, p)) = self.readback_buf() else { return CpuReadStep::Skip(end, excess) }; + let piece_end = end.min(at.saturating_add(READBACK_STAGING)); + let mut parts: Vec = Vec::new(); + let mut used = 0usize; + let mut cur = at; + while cur < piece_end { + let tile = cur & !(TILE - 1); + let Some(wi) = self.window_index(cur) else { + cur = end; + break; + }; + let b = self.windows[wi].0; + let n = (piece_end - cur).min(tile + TILE - cur).min(b + crate::gpu::uma::WINDOW - cur); + // (a tile with no video memory has nothing to copy back, as in `readback_ranges`) + let Some(e) = self.mapped.get(&tile).filter(|e| e.pool != LAZY) else { + cur += n; + continue; + }; + let (pool, gen, sent) = (e.pool, e.gen, sent_hashes(e, tile, cur, n)); + if parts.is_empty() && (self.rb_alloc.Reset().is_err() || self.rb_list.Reset(&self.rb_alloc, None).is_err()) { + return CpuReadStep::Skip(end, excess); + } + self.rb_list.CopyBufferRegion(&buf, used as u64, &self.windows[wi].1, (cur - b) as u64, n as u64); + parts.push(CpuReadPart { va: cur, off: used, len: n, pool, gen, sent, copied: Vec::new() }); + used += n; + cur += n; + } + if parts.is_empty() { + return CpuReadStep::Skip(cur, excess); + } + let list = self.rb_list.Close().ok().and_then(|_| self.rb_list.cast::().ok()); + let Some(list) = list else { return CpuReadStep::Skip(end, excess) }; + super::title_textures::own_work(|| super::real::native_queue_execute(&self.queue, &list)); + self.signal(); + self.rb_last_fence = self.value; + let seq = self.readbacks.lock().unwrap().job_seq; + self.reading = Some(Reading { at, end: cur, seq, spoiled: Vec::new() }); + CpuReadStep::Copy(CpuReadCopy { fence: self.fence.clone(), value: self.value, dev: self.dev.clone(), next: cur, _buf: buf, ptr: p, parts, excess }) + } + + /// The second half of a CPU read (`cpu_read_begin`), its copy done (`there`; else it lands + /// nowhere): the copies back done meanwhile land first, then the copy lands in each chunk of + /// its range that is as the copy found it: the tile has the same video and CPU memory, the + /// chunk the hash it had then and the CPU did not write it since (`land_page`), and nothing + /// landed there that the hashes do not show (`Reading::spoiled`). (A copy back of a submission + /// before the read that lands meanwhile keeps what it changed, as one that landed after the + /// read did when the read held the lock.) The excess copy-back jobs to drop outside the lock, + /// and the chunks landed. + unsafe fn cpu_read_land(&mut self, copy: &CpuReadCopy, there: bool) -> (Vec, u64) { + let excess = self.land_finished_readbacks(); + let reading = self.reading.take(); + // (a state made again while the copy was waited for: not its memory) + let Some(reading) = reading.filter(|_| there && self.fence.as_raw() == copy.fence.as_raw()) else { return (excess, 0) }; + let mut spoiled = reading.spoiled; + spoiled.sort_unstable(); + spoiled.dedup_by(|b, a| { + if b.0 > a.1 { + return false; + } + a.1 = a.1.max(b.1); + true + }); + let deep = super::look_stats::deep(); + let mut landed = 0u64; + for part in ©.parts { + let t = part.va & !(TILE - 1); + let Some(entry) = self.mapped.get_mut(&t).filter(|e| e.pool == part.pool && e.gen == part.gen) else { continue }; + let here = entry.cpu(t); + let end = part.va + part.len; + let mut c = part.va & !(CHUNK - 1); + let mut i = 0; + // (the page of the chunks landed last, and their bytes: noted once a page) + let mut page: Option<(usize, usize)> = None; + while c < end { + let (lo, hi) = (c.max(part.va), (c + CHUNK).min(end)); + let idx = (c - t) / PAGE; + let k = (c - t) % PAGE / CHUNK; + let sent = entry.sent[idx].as_deref().map_or(ZERO_HASH, |s| s[k]); + let whole = lo == c && hi == c + CHUNK; + let copied = part.copied.get(i).copied(); + // (a whole chunk the copy holds as it was sent: the CPU has it, or wrote it since) + let same = whole && copied == Some(sent); + if entry.holes & (1u16 << idx) == 0 && part.sent.get(i) == Some(&sent) && !same && !meets(&spoiled, lo, hi) { + let cpu = (here + (c - t)) as *mut u8; + if chunk_hash(std::slice::from_raw_parts(cpu, CHUNK)) == sent { + std::ptr::copy_nonoverlapping(copy.ptr.add(part.off + (lo - part.va)), cpu.add(lo - c), hi - lo); + let h = match copied { + Some(h) if whole => h, + _ => chunk_hash(std::slice::from_raw_parts(cpu, CHUNK)), + }; + entry.sent[idx].get_or_insert_with(|| Box::new(ZERO_HASHES))[k] = h; + landed += 1; + let pg = here + (c - t) - (c - t) % PAGE; + match page.as_mut() { + Some((p, n)) if *p == pg => *n += hi - lo, + _ => { + if let Some((p, n)) = page.replace((pg, hi - lo)) { + crate::hle::kernelx::pagelog::note("GPU copy back landed", p, 0, n); + } + if deep && self.own_pages.len() < OWN_PAGES_MAX { + self.own_pages.push(pg); + } + } + } + } + } + c += CHUNK; + i += 1; + } + if let Some((p, n)) = page { + crate::hle::kernelx::pagelog::note("GPU copy back landed", p, 0, n); + } + } + (excess, landed) + } +} + /// `readback_now` with the upload gate held. Returns any excess recycled `RbJob`s for the caller /// to drop outside `STATE`. unsafe fn readback_now_locked( @@ -5925,6 +6360,8 @@ impl State { /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps /// them and frees their pool tiles) unsafe fn decommit_range(&mut self, a: usize, n: usize) { + // (committed again, these pages hold zeros: a CPU read's copy back of them is old) + self.spoil(a, n); let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); let end = a.saturating_add(n); // tiles over a CPU view go as a whole (their holes are the CPU view's pages, not these) @@ -7959,10 +8396,11 @@ impl State { let x = LOCK_SPLIT.take(); let [made, kept] = RANGES_TAKEN.take(); crate::xlog_info!( - "D3D12.X: {}; {}; {}; mapped ranges asked for {made} times under the lock, {kept} times not", + "D3D12.X: {}; {}; {}; {}; mapped ranges asked for {made} times under the lock, {kept} times not", lock_split_line(&x), view_split_line(&VIEW_SPLIT.take(), x[LS_SUBMITS]), - holders_line(&HELD.take(), x[LS_SUBMITS]) + holders_line(&HELD.take(), x[LS_SUBMITS]), + cpu_reads_line(&CPU_READS.take(), x[LS_SUBMITS]) ); } } @@ -9143,6 +9581,7 @@ mod tests { diag: ViewDiag::default(), poison: None, retry_pages: Vec::new(), + reading: None, }; s.commit_range(base, TILE); assert!(s.mapped.contains_key(&base)); @@ -10646,6 +11085,7 @@ mod tests { diag: ViewDiag::default(), poison: None, retry_pages: Vec::new(), + reading: None, }; let (first, reused) = s.take_tile().expect("a tile from a new pool"); @@ -11067,6 +11507,7 @@ mod tests { diag: ViewDiag::default(), poison: None, retry_pages: Vec::new(), + reading: None, }; // Mirrors `place_buffer`: map both tiles probing real OS page commitment. @@ -11203,6 +11644,7 @@ mod tests { diag: ViewDiag::default(), poison: None, retry_pages: Vec::new(), + reading: None, }; s.commit_range(base, TILE); @@ -14068,4 +14510,160 @@ mod tests { asker.join().unwrap(); assert_ne!(again, fake); } + + /// `len` bytes of `byte` put into the window's video memory at `va`, not into its CPU memory: + /// what the GPU wrote there. + unsafe fn gpu_fill(s: &mut State, va: usize, len: usize, byte: u8) { + // (the tiles' clears first, as a submit sends them before the title's work) + let zeroed = zero_runs(std::mem::take(&mut s.to_zero)); + for &(a, n) in &zeroed { + s.clear_sent_range(a, n); + } + assert!(matches!(s.upload_zeros(&zeroed), UploadStep::Done(PreparationOutcome::Ready)), "the tiles' clears went out"); + let mut d = buffer_desc(len as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut up: Option = None; + s.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up).expect("upload buffer"); + let up = up.expect("upload buffer"); + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).expect("Map"); + std::ptr::write_bytes(p as *mut u8, byte, len); + up.Unmap(0, None); + let (base, window) = (s.windows[0].0, s.windows[0].1.clone()); + let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.CopyBufferRegion(&window, (va - base) as u64, &up, 0, len as u64); + list.Close().expect("Close"); + s.flush_pending(); + s.queue.ExecuteCommandLists(&[Some(list.cast().expect("list"))]); + s.signal(); + s.wait_for(s.value); + } + + /// A CPU read longer than the readback buffer goes in copies of it one after the other, each + /// waited for with the lock released, and one that begins and ends inside a 64-byte chunk lands + /// those bytes only. + #[test] + fn a_long_cpu_read_lands_in_pieces_and_its_ends_only_in_range() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + if !cpu_read_unlocked() { + return crate::gpu::recomp::runner::skip_test("XCL_CPU_READ_UNLOCKED=0"); + } + unsafe { + let tiles = READBACK_STAGING / TILE + 2; + let (base, mut s) = test_state_with_reserved(tiles); + if s.rbq.is_none() { + let _ = VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + return crate::gpu::recomp::runner::skip_test("no readback queue"); + } + assert!(!VirtualAlloc(base as *const c_void, tiles * TILE, MEM_COMMIT, PAGE_READWRITE).is_null()); + s.commit_range(base, tiles * TILE); + s.flush_pending(); + gpu_fill(&mut s, base, tiles * TILE, 0x3C); + let state = Mutex::new(Some(s)); + // (from 0x1234 into the first tile to 7 bytes into a chunk of the last) + let (va, end) = (base + 0x1234, base + (tiles - 1) * TILE + 0x5007); + readback_now_with(&state, va, end - va); + // (the first byte that is not as it should be, by its distance from `base`) + let other = |a: usize, n: usize, b: u8| std::slice::from_raw_parts(a as *const u8, n).iter().position(|&x| x != b).map(|k| a + k - base); + assert_eq!(other(va, end - va, 0x3C), None, "the whole read has the GPU's bytes, past the readback buffer's size too"); + assert_eq!((other(base, va - base, 0), other(end, base + tiles * TILE - end, 0)), (None, None), "nothing lands outside the read"); + let mut g = state.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.reading.is_none()); + assert_eq!(s.rb_last_fence, s.value, "the last copy was the read's"); + s.wait_for(s.value); + drop(g); + let _ = VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + #[test] + fn meets_finds_overlaps_with_sorted_runs() { + let runs = [(0x100, 0x140), (0x800, 0x900)]; + assert!(!meets(&runs, 0x140, 0x180), "ends are exclusive"); + assert!(meets(&runs, 0x13F, 0x141)); + assert!(meets(&runs, 0x8C0, 0x900)); + assert!(!meets(&runs, 0x900, 0x940)); + assert!(!meets(&[], 0, usize::MAX)); + } + + /// A CPU read (`readback_now_with`) waits for its copy back with the state's lock released, and + /// what changed in its range meanwhile keeps its bytes: a chunk the CPU wrote, a page + /// decommitted and committed again (zeros), and what a later submission's copy back landed + /// (here the zeros the CPU had: the hashes cannot tell it from an untouched chunk). The rest + /// gets what the GPU wrote, with its hashes. Before, the read held the lock until its copy was + /// done (a retail title: 3.6–6.3 ms a submit, the submits waiting behind it). + #[test] + fn cpu_read_waits_unlocked_and_keeps_what_changed_meanwhile() { + if !cpu_read_unlocked() { + return crate::gpu::recomp::runner::skip_test("XCL_CPU_READ_UNLOCKED=0"); + } + unsafe { + let iso = IsolatedAsyncState::new(); + let base = iso.base; + let blocker: ID3D12Fence = iso.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let _unblock = SignalOnDrop(blocker.clone(), 1); + { + let mut g = iso.state.lock().unwrap(); + let s = g.as_mut().unwrap(); + gpu_fill(s, base, 4 * PAGE, 0x5A); + // (the state's queue held until the test lets it go: the read's copy waits behind it) + s.queue.Wait(&blocker, 1).expect("Wait"); + } + let state = Arc::clone(&iso.state); + let reader = std::thread::spawn(move || readback_now_with(&state, base, 4 * PAGE)); + let t0 = std::time::Instant::now(); + while iso.state.lock().unwrap().as_ref().is_some_and(|s| s.reading.is_none()) { + assert!(t0.elapsed() < std::time::Duration::from_secs(10), "the read's copy was never submitted"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + for _ in 0..5 { + assert!(iso.state.try_lock().is_ok(), "the state's lock is free while the read waits for its copy"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + // the CPU writes a chunk + std::ptr::write_bytes((base + 0x100) as *mut u8, 0x77, CHUNK); + // a page is decommitted and committed again + let p2 = base + 2 * PAGE; + assert!(VirtualFree(p2 as *mut c_void, PAGE, MEM_DECOMMIT) != 0); + iso.state.lock().unwrap().as_mut().unwrap().decommit_range(p2, PAGE); + assert!(!VirtualAlloc(p2 as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + iso.state.lock().unwrap().as_mut().unwrap().commit_range(p2, PAGE); + // a later submission's copy back lands + let at = base + 3 * PAGE + 0x800; + let done: ID3D12Fence = iso.dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).expect("fence"); + let mut job = take_or_alloc_rb_job(&iso.dev, &iso.rb, 256, D3D12_COMMAND_LIST_TYPE_DIRECT).expect("readback job"); + std::ptr::write_bytes(job.ptr, 0, 256); + job.copies.clear(); + job.copies.push((at, 0, 256, iso.gen)); + (job.rb_v, job.done_v, job.fences) = (1, 1, Some((done.clone(), done))); + { + let mut rq = iso.rb.lock().unwrap(); + rq.job_seq += 1; + job.seq = rq.job_seq; + rq.rb_jobs.push_back(job); + } + RB_PENDING.fetch_add(1, Ordering::Release); + drop(iso.state.lock().unwrap().as_mut().unwrap().land_finished_readbacks()); + assert!(iso.rb.lock().unwrap().rb_jobs.is_empty(), "the later copy back landed"); + blocker.Signal(1).expect("Signal"); + reader.join().unwrap(); + + let bytes = |a: usize, n: usize| std::slice::from_raw_parts(a as *const u8, n).to_vec(); + let all = |a: usize, n: usize, b: u8| bytes(a, n).iter().all(|&x| x == b); + assert!(all(base, 0x100, 0x5A) && all(base + 0x140, PAGE - 0x140, 0x5A), "the GPU's bytes landed around the CPU's chunk"); + assert!(all(base + 0x100, CHUNK, 0x77), "the chunk the CPU wrote while the copy was made keeps its bytes"); + assert!(all(base + PAGE, PAGE, 0x5A)); + assert!(all(p2, PAGE, 0), "the page committed again keeps its zeros"); + assert!(all(base + 3 * PAGE, 0x800, 0x5A) && all(at + 256, PAGE - 0x900, 0x5A)); + assert!(all(at, 256, 0), "what the later copy back landed stays"); + assert!(all(base + 4 * PAGE, PAGE, 0), "nothing lands past the read"); + let g = iso.state.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(s.reading.is_none()); + let sent = s.mapped[&base].sent[1].as_deref().expect("hashes of a landed page"); + assert_eq!(sent[0], chunk_hash(&[0x5A; CHUNK]), "a landed chunk has the hash of its bytes: the next look sends nothing"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ed4bb11a70..9664fe84b6 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -507,6 +507,34 @@ impl Table { Some((pending_delta, remap)) } + /// The sources `res` of a bake whose list is about to be submitted (`ready_bake_sources`): one + /// shadowed now – a texture placed over it since the draw, or one a later draw made active + /// again – is made active again (`uncover`; the last of overlapping ones wins, as at the + /// draw); an active one whose bytes are the CPU's goes up whole at this submit, as the title's + /// memory has it now rather than at an earlier upload. Not one the GPU wrote. + fn ready_for_bake(&mut self, res: &[usize], until: u64) -> BakeReady { + let mut out = BakeReady::default(); + for &r in res { + if self.shadowed.contains_key(&r) { + if let Some((d, unmapped)) = self.uncover(r, until) { + out.uncovered += 1; + out.pending_delta += d; + if unmapped { + out.remap.push(r); + } + } + continue; + } + let Table { by_res, pending_res, .. } = self; + let Some(e) = by_res.get_mut(&r).filter(|e| e.cpu_backed && !e.gpu_written && !e.pending) else { continue }; + e.pending = true; + pending_res.insert(r); + out.pending_delta += 1; + out.whole += 1; + } + out + } + /// Remove `res` on COM release, reactivating any shadowed older textures it uncovered (newest /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap, uniform_state)`. fn remove(&mut self, res: usize) -> (bool, isize, Vec, Option) { @@ -1374,15 +1402,7 @@ pub(super) fn uncover_drawn(res: &[usize]) { } (restored, unsafe { clone_resources(&remap) }) }; - for r in &remap { - unsafe { - super::vram::remap_if_unmapped(r); - // Lazy levels of a GPU-written texture cannot wait for a CPU upload to map them. - if super::vram::level_pages() && TEXTURES.lock().unwrap().get_mut(r.as_raw() as usize).is_some_and(|e| e.gpu_written) { - super::vram::map_levels(r, None); - } - } - } + unsafe { remap_uncovered(&remap) }; TEXTURES_GEN.fetch_add(1, Ordering::Release); static N: AtomicU64 = AtomicU64::new(0); let before = N.fetch_add(restored, Ordering::Relaxed); @@ -1392,6 +1412,103 @@ pub(super) fn uncover_drawn(res: &[usize]) { } } +/// Textures `uncover` made active again whose tiles were unmapped get them back. +unsafe fn remap_uncovered(remap: &[ID3D12Resource]) { + for r in remap { + super::vram::remap_if_unmapped(r); + // Lazy levels of a GPU-written texture cannot wait for a CPU upload to map them. + if super::vram::level_pages() && TEXTURES.lock().unwrap().get_mut(r.as_raw() as usize).is_some_and(|e| e.gpu_written) { + super::vram::map_levels(r, None); + } + } +} + +/// `XCL_BAKE_AT_SUBMIT` (on by default; `0`: off): the sources of a bake's draws are seen to +/// again at the submit of the list that holds them (`ready_bake_sources`), not only when the +/// draw is recorded (`bind::uncover_indexed`). +/// +/// The title places the textures a bake reads in the frame it bakes, packed 8 KiB apart over +/// each other's larger levels (only their small levels are there; GFX10 keeps them first), and +/// it goes on placing there while the frame is recorded. A placement over a source between the +/// bake's draw and its list's submit shadows the source again: the submit's refresh does not +/// upload it, and its tiles are unmapped once the work submitted before that placement is done +/// – before the bake, which then samples zeros. What it bakes is kept for the run: a head and +/// skin black at mid range (next-r9). A draw recorded on another list in between that makes an +/// overlapping texture active again takes the shared pages the same way. The active sources go +/// up whole at that submit too, as title memory has them then – the idea of Whiplash +/// (`Kalmarv/whiplash` 699f191, GPL-3.0-or-later: `early_budgets` and `bake_exact` in its +/// `Whiplash-AMD/crates/victory-gpu/src/draw.rs`), which uploads every texture a bake picks just +/// before its draw; see THIRD_PARTY.md. +pub(super) fn bake_at_submit() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_BAKE_AT_SUBMIT").map_or(true, |v| v.trim() != "0"); + if !on { + crate::xlog_info!("D3D12.X: XCL_BAKE_AT_SUBMIT=0 - a bake's sources are made active only when its draw is recorded"); + } + on + }) +} + +/// What `Table::ready_for_bake` did. +#[derive(Debug, Default, PartialEq, Eq)] +struct BakeReady { + /// shadowed ones made active again (`Table::uncover`) + uncovered: usize, + /// active ones that go up whole at this submit + whole: usize, + /// the change of the count of pending textures (`PENDING`) + pending_delta: isize, + /// of the uncovered, those whose tiles were unmapped + remap: Vec, +} + +/// Before a submit of lists that hold a bake's draws (`XCL_BAKE_AT_SUBMIT`): `res`, the textures +/// those draws pick by index (`bind::bake_sources`), are made ready for it as the submit's +/// refresh, which comes next, finds them (`Table::ready_for_bake`): its uploads go ahead of the +/// lists on the queue. +pub(super) fn ready_bake_sources(res: &[usize]) { + if res.is_empty() || !bake_at_submit() { + return; + } + let until = { + let (p, b) = super::present::counters(); + p.max(b) + DISPLACED_FRAMES + }; + let (r, remap, nothing) = { + let mut t = TEXTURES.lock().unwrap(); + let r = t.ready_for_bake(res, until); + adjust_pending(r.pending_delta); + if r.uncovered > 0 { + update_lengths(&t); + if t.displaced.values().any(|d| d.whole) { + HAS_DISPLACED.store(true, Ordering::Release); + } + } + // (those read through the title's page mappings whose first page shows nothing now: the + // title had not mapped what the bake reads when its list was submitted) + use crate::hle::kernelx::mirrors; + let nothing = res.iter().filter_map(|r| t.by_res.get(r)).filter(|e| e.paged && mirrors::shows(e.va) == mirrors::Shows::Nothing).count(); + let remap = unsafe { clone_resources(&r.remap) }; + (r, remap, nothing) + }; + unsafe { remap_uncovered(&remap) }; + if r.uncovered + r.whole > 0 { + TEXTURES_GEN.fetch_add(1, Ordering::Release); + } + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed) + 1; + if r.uncovered > 0 || nothing > 0 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a submit of a bake's list (#{n}): its draws pick {} textures by index; {} of them shadowed since the draw was recorded, made active again ({} remapped); {} active ones go up whole again; {nothing} where the title's page mappings show nothing now (XCL_BAKE_AT_SUBMIT=0: as at the draw)", + res.len(), + r.uncovered, + remap.len(), + r.whole + ); + } +} + /// The title-memory address of a texture kept in step with it. pub fn address(res: usize) -> Option { let t = TEXTURES.lock().unwrap(); @@ -6574,6 +6691,65 @@ pub(super) mod tests { assert!(!table.by_res[&3].pending, "GPU-written content must not be overwritten by a retry"); } + /// A bake's source made active again at its draw (`uncover`) that the title places another + /// texture over before the list's submit is shadowed at that submit, its tiles to be + /// unmapped: the submit's refresh uploads only active and displaced textures, and the bake + /// read nothing (next-r9: a head black for the run). At the submit it is made active again + /// and goes up whole; an active source goes up whole again; one the GPU wrote does not. + #[test] + fn a_bake_source_placed_over_after_its_draw_is_made_ready_at_its_submit() { + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + assert!(tex.size() > 0x2000); + let entry = |va: usize, pending: bool, gpu_written: bool| Entry { + device: 0, + committed_bytes: 0, + va, + src: va, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending, + gpu_written, + gpu_writers: Vec::new(), + cpu_backed: true, + placed: true, + unmapped: false, + generation: 0, + paged: false, + written_call: 0, + known: Default::default(), + target: false, + }; + const A: usize = 1; + const B: usize = 2; + const C: usize = 3; + const D: usize = 4; + const G: usize = 5; + let mut t = Table::new(); + // the title places A, then B 8 KiB on, over A's larger levels + t.insert(A, entry(0x10_0000, true, false)); + t.insert(B, entry(0x10_2000, true, false)); + assert!(t.shadowed[&A].unmapped); + // the bake's draw makes A active again (`bind::uncover_indexed`) + assert!(t.uncover(A, 10).is_some_and(|(_, remap)| remap)); + assert!(t.by_res.contains_key(&A) && !t.by_res[&A].unmapped); + // before the list's submit the title places C over A: the submit found A shadowed, not + // to be uploaded, its tiles to be unmapped + t.insert(C, entry(0x10_1000, true, false)); + assert!(!t.by_res.contains_key(&A) && t.shadowed[&A].unmapped && !t.displaced.contains_key(&A)); + // the bake's other sources: D active and uploaded, G written by the GPU (99: none) + t.insert(D, entry(0x20_0000, false, false)); + t.insert(G, entry(0x30_0000, false, true)); + let r = t.ready_for_bake(&[A, D, G, 99], 10); + assert_eq!(r, BakeReady { uncovered: 1, whole: 1, pending_delta: 1, remap: vec![A] }); + assert!(t.by_res[&A].pending && !t.by_res[&A].unmapped && t.pending_res.contains(&A)); + assert!(t.displaced.get(&C).is_some_and(|d| d.whole), "the texture placed over it goes up first, as at a draw"); + assert!(t.by_res[&D].pending && t.pending_res.contains(&D)); + assert!(!t.by_res[&G].pending && !t.pending_res.contains(&G)); + // a second time: nothing left to do + assert_eq!(t.ready_for_bake(&[A, D, G], 10), BakeReady::default()); + } + #[test] fn small_cpu_filled_target_accepts_wide_glyph_atlas_and_rejects_large_or_depth() { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 23639741cb..b5ba9e5883 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -3232,11 +3232,31 @@ pub unsafe extern "system" fn RegCloseKey(key: usize) -> u32 { const LOAD_AS_DATA: u32 = 0x2 | 0x20 | 0x40; // DATAFILE | IMAGE_RESOURCE | DATAFILE_EXCLUSIVE +/// The console's FidelityFX upscaler, which the title's FidelityFX loader loads by name. +const FFX_UPSCALER_DLL: &str = "amd_fidelityfx_upscaler_xbox.dll"; + +/// `XCL_FFX_UPSCALER=0`: the title's FidelityFX loader finds no upscaler (LoadLibrary of +/// `amd_fidelityfx_upscaler_xbox.dll` fails as for a missing DLL), and the title upscales its own +/// way. With the console's FSR the people left copies along their path and the last shot showed +/// through a camera cut, though the title asked for a reset at the cuts (`ffx.rs`). Whiplash (a +/// VIctory descendant, GPL-3.0-or-later) never loads that DLL either: its loader refuses host DLLs +/// outside its policy, and the title runs without it. On (loaded) unless set to `0`. +fn ffx_upscaler_refused(name: &str, switch: Option<&str>) -> bool { + switch.is_some_and(|v| v.trim() == "0") + && name.rsplit(['\\', '/']).next().is_some_and(|file| file.eq_ignore_ascii_case(FFX_UPSCALER_DLL)) +} + fn load_library_impl(name: Option) -> usize { let Some(name) = name else { unsafe { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER) }; return 0; }; + static UPSCALER: std::sync::OnceLock> = std::sync::OnceLock::new(); + if ffx_upscaler_refused(&name, UPSCALER.get_or_init(|| std::env::var("XCL_FFX_UPSCALER").ok()).as_deref()) { + crate::xlog_info!("LoadLibrary({name}) → NULL: the console's FidelityFX upscaler is left out (XCL_FFX_UPSCALER=0)"); + unsafe { fnd::SetLastError(fnd::ERROR_MOD_NOT_FOUND) }; + return 0; + } match resolver::load_library(&name) { Some(h) => { crate::xlog_debug!("LoadLibrary({name}) → {h:#x}"); @@ -3480,6 +3500,20 @@ pub unsafe extern "system" fn DisableThreadLibraryCalls(h: usize) -> BOOL { mod tests { use super::*; + /// `XCL_FFX_UPSCALER=0` refuses the console's FidelityFX upscaler by its file name (any case, + /// any folder) and nothing else; unset or any other value loads it as before. + #[test] + fn the_ffx_upscaler_is_refused_only_with_the_switch_off() { + for name in ["amd_fidelityfx_upscaler_xbox.dll", "AMD_FidelityFX_Upscaler_Xbox.DLL", "G:\\amd_fidelityfx_upscaler_xbox.dll", "d:/x/amd_fidelityfx_upscaler_xbox.dll"] { + assert!(ffx_upscaler_refused(name, Some("0")), "{name}"); + assert!(!ffx_upscaler_refused(name, None), "{name} unset"); + assert!(!ffx_upscaler_refused(name, Some("1")), "{name} on"); + } + for name in ["amd_fidelityfx_loader_xbox.dll", "amd_fidelityfx_upscaler_xbox.dll.bak", "xamd_fidelityfx_upscaler_xbox.dll", "Bink2Scarlett.dll"] { + assert!(!ffx_upscaler_refused(name, Some("0")), "{name}"); + } + } + #[test] fn exposed_physical_home_is_never_made_private_again() { let mut away = Away::default(); diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index 4a5003b962..adf7af9b8a 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -36,6 +36,7 @@ mod source_hash; pub mod stall; pub mod state; pub mod stubs; +pub mod title_patch; pub mod tls; pub mod util; pub mod vfs; diff --git a/crates/xcl/src/loader.rs b/crates/xcl/src/loader.rs index bb38bb8bb8..2392dbff8d 100644 --- a/crates/xcl/src/loader.rs +++ b/crates/xcl/src/loader.rs @@ -235,6 +235,10 @@ fn map_image_ex(path: &Path, is_main: bool) -> Result, String> unsafe { crate::eh::patch_clzero_loops(base + s.va as usize, len, &name) }; } } + // 10. places of a retail title's code the switches change (`title_patch`: XCL_UPSCALER) + if !module.is_dll { + unsafe { crate::title_patch::apply(base, size, &name) }; + } Ok(module) } diff --git a/crates/xcl/src/title_patch.rs b/crates/xcl/src/title_patch.rs new file mode 100644 index 0000000000..e36c3dcc67 --- /dev/null +++ b/crates/xcl/src/title_patch.rs @@ -0,0 +1,216 @@ +//! Places in a retail title's code changed when its executable is mapped, each only where the +//! title's bytes are the ones expected (another build of the title is left alone, said so). +//! +//! - `XCL_UPSCALER=6` (or `7`; unset: as the title picks): the title's upscaler picker +//! (game_scarlett_master.exe 1.0.2.1, image offset +0x7e93f0) returns that kind: 6 the title's +//! own upscaler, 7 AMD FidelityFX. The title picks FidelityFX on a Series S whose feature flags +//! have bit 0x40 set (XCL's do), its own otherwise. With the console's FidelityFX (FSR4) the +//! people left copies along their path and the last shot showed through a camera cut, though +//! the title asked for a reset at the cuts (`hle::ffx`); its jitter phase count is what the +//! title divides by at +0x28f03e8, so leaving the upscaler's DLL out instead ends the title there. +//! With 6, Series S's heap 2 grows too (`SERIES_S_HEAPS`): the title sized it for FidelityFX. +//! +//! The picker's bytes and offsets are from Whiplash (a VIctory descendant, GPL-3.0-or-later, +//! `Kalmarv/whiplash` 699f191, `Whiplash-AMD/crates/victory-loader/src/resolution.rs`, +//! `VICTORY_UPSCALER`, after VIctory pull request #53); see `THIRD_PARTY.md`. The heap sizes are +//! XCL's own finding (Whiplash runs the title as a Series X, whose picker returns 6 anyway). + +/// A place to change: its offset in the image and the bytes expected there (the replacement is +/// at most as long). +pub struct Site { + pub at: usize, + pub what: &'static str, + pub bytes: &'static [u8], +} + +/// The upscaler picker, +0x7e93f0, to its first `ret`: 6 unless a check passes and a feature +/// flag has bit 0x40, then 7. +pub const PICKER: Site = Site { + at: 0x7e93f0, + what: "upscaler picker", + bytes: &[ + 0x48, 0x83, 0xec, 0x28, 0x80, 0x3d, 0x6d, 0xf0, 0x3a, 0x07, 0x00, 0x75, 0x09, 0x83, 0x3d, 0x68, 0xf0, 0x3a, 0x07, 0x00, + 0x74, 0x28, 0xe8, 0x35, 0xbd, 0x88, 0xff, 0x8a, 0x0d, 0x5b, 0xf0, 0x3a, 0x07, 0x80, 0xe1, 0x40, 0x80, 0xf9, 0x01, 0xb9, + 0x07, 0x00, 0x00, 0x00, 0x83, 0xd9, 0x00, 0x84, 0xc0, 0xb8, 0x06, 0x00, 0x00, 0x00, 0x0f, 0x45, 0xc1, 0x48, 0x83, 0xc4, + 0x28, 0xc3, + ], +}; + +/// The title's heap sizes per console, +0x6186250 (read at start by +0x1e1ced0, the heaps made +/// by +0x1e1cf60): Series S's row, ten 8-byte sizes – the total, then heaps 0 to 8 (8572 MB in +/// all); Series X's row (13312 MB) follows it. Heap 2 is 1277 MB on Series S, 2199 MB on Series +/// X: with the title's own upscaler on a Series S it runs out at start (a 576 KiB allocation of +/// it fails, the title stops at its `int3` at +0x2219650: runs next-r12/r13), so it is sized for +/// FidelityFX there. +pub const SERIES_S_HEAPS: Site = Site { + at: 0x6186250, + what: "Series S heap sizes", + bytes: &[ + 0x00, 0x00, 0xc0, 0x17, 0x02, 0x00, 0x00, 0x00, // total 8572 MB + 0x00, 0x00, 0xa0, 0x48, 0x00, 0x00, 0x00, 0x00, // 0: 1162 MB + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 1 + 0x00, 0x00, 0xd0, 0x4f, 0x00, 0x00, 0x00, 0x00, // 2: 1277 MB + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 3 + 0x00, 0x00, 0x20, 0x0c, 0x00, 0x00, 0x00, 0x00, // 4: 194 MB + 0x00, 0x00, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, // 5: 258 MB + 0x00, 0x00, 0x80, 0x23, 0x00, 0x00, 0x00, 0x00, // 6: 568 MB + 0x00, 0x00, 0x20, 0x27, 0x01, 0x00, 0x00, 0x00, // 7: 4722 MB + 0x00, 0x00, 0x70, 0x18, 0x00, 0x00, 0x00, 0x00, // 8: 391 MB + ], +}; + +/// What Series S's heap 2 (and so the total) gains with the title's own upscaler. +pub const OWN_UPSCALER_HEAP_GROWTH: u64 = 512 << 20; + +/// Series S's row of heap sizes with heap 2 and the total grown by `growth` bytes. +pub fn series_s_heaps_grown(growth: u64) -> Vec { + let mut row = SERIES_S_HEAPS.bytes.to_vec(); + for at in [0, 3 * 8] { + let size = u64::from_le_bytes(row[at..at + 8].try_into().unwrap()) + growth; + row[at..at + 8].copy_from_slice(&size.to_le_bytes()); + } + row +} + +/// `mov eax, kind ; ret`. +pub fn picker_code(kind: u32) -> Vec { + let mut c = vec![0xb8]; + c.extend(kind.to_le_bytes()); + c.push(0xc3); + c +} + +/// `XCL_UPSCALER`: 6 or 7 (None: unset or anything else, said so). +fn parse_upscaler(v: Option<&str>) -> Option { + let v = v?; + let kind = v.trim().parse::().ok().filter(|k| matches!(k, 6 | 7)); + if kind.is_none() { + crate::xlog_warn!("XCL_UPSCALER={v}: expected 6 (the title's own upscaler) or 7 (FidelityFX): left as the title picks"); + } + kind +} + +#[derive(Debug, PartialEq, Eq)] +pub enum Patched { + Done, + /// the title's bytes there are not the ones expected (another build) + Differs, + Failed(&'static str), +} + +/// `code` written over `site` in `image` (its bytes in memory) when the bytes there are +/// `site.bytes`; nothing written otherwise. +pub fn patch_bytes(image: &mut [u8], site: &Site, code: &[u8]) -> Patched { + debug_assert!(code.len() <= site.bytes.len()); + match image.get_mut(site.at..site.at + site.bytes.len()) { + None => Patched::Failed("outside the image"), + Some(at) if at != site.bytes => Patched::Differs, + Some(at) => { + at[..code.len()].copy_from_slice(code); + Patched::Done + } + } +} + +/// What the switches ask for, applied to the mapped image of `size` bytes at `base` (its code +/// writable or made so for the write); a line each in the log. +/// +/// # Safety +/// The image is mapped and no thread runs its code yet. +pub unsafe fn apply(base: usize, size: usize, image: &str) { + let Some(kind) = parse_upscaler(std::env::var("XCL_UPSCALER").ok().as_deref()) else { return }; + let picked = write_site(base, size, &PICKER, &picker_code(kind)); + match picked { + Patched::Done => crate::xlog_info!("{image}: {} at +{:#x} returns {kind} (XCL_UPSCALER: 6 the title's own upscaler, 7 FidelityFX)", PICKER.what, PICKER.at), + ref other => crate::xlog_warn!("{image}: {} at +{:#x} not patched: {other:?} (another build of the title?)", PICKER.what, PICKER.at), + } + // the title's own upscaler on a Series S: room for it in heap 2 (`SERIES_S_HEAPS`) + if kind == 6 && picked == Patched::Done { + match write_site(base, size, &SERIES_S_HEAPS, &series_s_heaps_grown(OWN_UPSCALER_HEAP_GROWTH)) { + Patched::Done => crate::xlog_info!( + "{image}: {} at +{:#x}: heap 2 is {} MB (+{} MB) for the title's own upscaler", + SERIES_S_HEAPS.what, + SERIES_S_HEAPS.at, + (0x4fd0_0000 + OWN_UPSCALER_HEAP_GROWTH) >> 20, + OWN_UPSCALER_HEAP_GROWTH >> 20 + ), + other => crate::xlog_warn!("{image}: {} at +{:#x} not changed: {other:?} (another build of the title?)", SERIES_S_HEAPS.what, SERIES_S_HEAPS.at), + } + } +} + +/// `code` over `site` of the mapped image at `base` (`patch_bytes`), its pages made writable for +/// the write and given back their protection after it. +unsafe fn write_site(base: usize, size: usize, site: &Site, code: &[u8]) -> Patched { + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + if site.at + site.bytes.len() > size { + return Patched::Failed("outside the image"); + } + let at = base + site.at; + let mut old = 0u32; + if VirtualProtect(at as *const std::ffi::c_void, site.bytes.len(), PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return Patched::Failed("its page could not be made writable"); + } + let bytes = std::slice::from_raw_parts_mut(at as *mut u8, site.bytes.len()); + // (`patch_bytes` sees the site's bytes as an image starting at the site) + let local = Site { at: 0, what: site.what, bytes: site.bytes }; + let done = patch_bytes(bytes, &local, code); + VirtualProtect(at as *const std::ffi::c_void, site.bytes.len(), old, &mut old); + windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache(windows_sys::Win32::System::Threading::GetCurrentProcess(), at as *const std::ffi::c_void, site.bytes.len()); + done +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_picker_returns_the_kind_asked_for() { + assert_eq!(picker_code(6), [0xb8, 6, 0, 0, 0, 0xc3]); + assert_eq!(picker_code(7), [0xb8, 7, 0, 0, 0, 0xc3]); + } + + #[test] + fn the_upscaler_switch_takes_6_or_7_only() { + assert_eq!(parse_upscaler(Some("6")), Some(6)); + assert_eq!(parse_upscaler(Some(" 7 ")), Some(7)); + assert_eq!(parse_upscaler(Some("8")), None); + assert_eq!(parse_upscaler(Some("own")), None); + assert_eq!(parse_upscaler(None), None); + } + + /// The bytes are written only where the title has the expected ones, and only the first + /// `code.len()` of them. + #[test] + fn a_site_is_patched_only_over_the_expected_bytes() { + let mut image = vec![0xccu8; PICKER.at + PICKER.bytes.len() + 16]; + image[PICKER.at..PICKER.at + PICKER.bytes.len()].copy_from_slice(PICKER.bytes); + assert_eq!(patch_bytes(&mut image, &PICKER, &picker_code(6)), Patched::Done); + assert_eq!(&image[PICKER.at..PICKER.at + 6], &[0xb8, 6, 0, 0, 0, 0xc3]); + assert_eq!(&image[PICKER.at + 6..PICKER.at + PICKER.bytes.len()], &PICKER.bytes[6..]); + // patched once, the bytes there differ: a second patch leaves them + let before = image.clone(); + assert_eq!(patch_bytes(&mut image, &PICKER, &picker_code(7)), Patched::Differs); + assert_eq!(image, before); + // an image too short for the site + assert_eq!(patch_bytes(&mut [0u8; 16], &PICKER, &picker_code(6)), Patched::Failed("outside the image")); + } + + /// Series S's row: the heaps add up to its total; grown, heap 2 and the total gain the same + /// and nothing else changes. + #[test] + fn series_s_heap_2_grows_with_the_total() { + let sizes = |row: &[u8]| row.chunks(8).map(|c| u64::from_le_bytes(c.try_into().unwrap())).collect::>(); + let before = sizes(SERIES_S_HEAPS.bytes); + assert_eq!(before.len(), 10); + assert_eq!(before[0], before[1..].iter().sum::()); + assert_eq!((before[0] >> 20, before[3] >> 20), (8572, 1277)); + let after = sizes(&series_s_heaps_grown(512 << 20)); + assert_eq!(after[0], before[0] + (512 << 20)); + assert_eq!(after[3], before[3] + (512 << 20)); + assert_eq!(after[0], after[1..].iter().sum::()); + for i in [1, 2, 4, 5, 6, 7, 8, 9] { + assert_eq!(after[i], before[i]); + } + } +} From 3a3a8e9c71bd54cd274ff4b8091bbf98232a1cdb Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:01:58 +0100 Subject: [PATCH 158/175] Sparse, shader, kernelx: cache committed source regions across VirtualQuery Add a range-invalidated SourceRegions cache (opt-out via XCL_SOURCE_HOLES_CACHE=0) populated from source_holes_cached and shader::readable (strictly for UMA windows and kernelx graphics reservations whose lifecycle is fully intercepted) and invalidated on decommit, VirtualFree/VirtualProtect, FreeTitlePhysicalPages, and mirror reserve/release. Measured on RX 9070 XT over 5+ minutes of world gameplay (next-r20 vs next-r14): - asking Windows which pages are committed: 1.513 ms avg / 10.233 ms max -> 0.002 ms avg / 0.009 ms max (~756x avg, ~1,137x peak) - sparse lock per submit: 1.637 ms avg / 10.414 ms max -> 0.149 ms avg / 0.767 ms max (~11x avg, ~13.6x peak) --- crates/xcl/src/gpu/shader.rs | 13 +- crates/xcl/src/hle/d3d12x/sparse.rs | 291 +++++++++++++++++++++++++++- crates/xcl/src/hle/kernelx.rs | 34 +++- 3 files changed, 332 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/shader.rs b/crates/xcl/src/gpu/shader.rs index 0d510f18d3..4da0ad33eb 100644 --- a/crates/xcl/src/gpu/shader.rs +++ b/crates/xcl/src/gpu/shader.rs @@ -215,6 +215,10 @@ pub fn readable(p: usize, len: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, len)) { return true; } + if crate::hle::d3d12x::sparse::known_readable(p, end) { + return true; + } + let rev0 = crate::hle::d3d12x::sparse::source_regions_rev(); if let Some(answer) = pages_readable(p, end) { return answer; } @@ -225,7 +229,14 @@ pub fn readable(p: usize, len: usize) -> bool { if n == 0 || mbi.State != MEM_COMMIT || mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD) != 0 || mbi.Protect == 0 { return false; } - cur = mbi.BaseAddress as usize + mbi.RegionSize; + let lo = mbi.BaseAddress as usize; + let hi = lo.saturating_add(mbi.RegionSize); + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(lo) || u.is_view(lo) || u.contains(lo)) + || crate::hle::kernelx::in_graphics_reservation(lo) + { + crate::hle::d3d12x::sparse::cache_readable_region(lo, hi, rev0); + } + cur = hi; } true } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 646f46eafc..5dfed92432 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -271,6 +271,240 @@ unsafe fn source_holes(tiles: &[usize]) -> Vec { out } +/// `XCL_SOURCE_HOLES_CACHE=0`: query Windows (`source_holes`) on every `holes_now` without +/// caching known-accessible source regions across submits. On by default. +fn source_holes_cache_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_SOURCE_HOLES_CACHE").ok().is_none_or(|v| v.trim() != "0")) +} + +/// Sorted, disjoint, coalesced `[lo, hi)` page-aligned spans known to be `MEM_COMMIT` and +/// accessible (`Protect != 0`, not `PAGE_NOACCESS | PAGE_GUARD`). Only accessible spans are +/// cached, so committing new pages needs no invalidation; decommits, frees, and non-writable +/// protection changes punch their exact span out (`invalidate_source_range`). +#[derive(Default)] +struct SourceRegions { + rev: u64, + ranges: Vec<(usize, usize)>, + /// Recent invalidations `(rev, lo, hi)` so an in-flight `VirtualQuery` can still safely + /// populate unaffected regions (`(rev, 0, usize::MAX)` marks a full clear). + recent: VecDeque<(u64, usize, usize)>, +} + +impl SourceRegions { + const RECENT_CAP: usize = 64; + + fn contains_tile(&self, tile: usize) -> bool { + let Some(end) = tile.checked_add(TILE) else { return false }; + let i = self.ranges.partition_point(|&(lo, _)| lo <= tile); + i > 0 && self.ranges[i - 1].1 >= end + } + + fn insert(&mut self, lo: usize, hi: usize) { + if lo >= hi { + return; + } + let mut start = lo; + let mut end = hi; + // First range whose end >= start (touches or overlaps `[start, end)`). + let first = self.ranges.partition_point(|&(_, r_end)| r_end < start); + let mut last = first; + while last < self.ranges.len() && self.ranges[last].0 <= end { + start = start.min(self.ranges[last].0); + end = end.max(self.ranges[last].1); + last += 1; + } + self.ranges.splice(first..last, std::iter::once((start, end))); + } + + fn subtract(&mut self, lo: usize, hi: usize) { + if lo >= hi || self.ranges.is_empty() { + return; + } + let first = self.ranges.partition_point(|&(_, r_end)| r_end <= lo); + let mut last = first; + let mut repl: Vec<(usize, usize)> = Vec::new(); + while last < self.ranges.len() && self.ranges[last].0 < hi { + let (a, b) = self.ranges[last]; + if a < lo { + repl.push((a, lo)); + } + if b > hi { + repl.push((hi, b)); + } + last += 1; + } + if first < last { + self.ranges.splice(first..last, repl); + } + } + + fn note_invalidation(&mut self, lo: usize, hi: usize) { + self.rev = self.rev.wrapping_add(1); + if self.recent.len() >= Self::RECENT_CAP { + self.recent.pop_front(); + } + self.recent.push_back((self.rev, lo, hi)); + } + + fn invalidate(&mut self, a: usize, n: usize) { + if n == 0 { + if a == 0 { + self.ranges.clear(); + self.note_invalidation(0, usize::MAX); + } else { + // Unknown length (`MEM_RELEASE` with size 0): drop any range containing `a`, and + // record a full-clear sentinel in `recent` so an in-flight query won't re-add it. + let i = self.ranges.partition_point(|&(lo, _)| lo <= a); + if i > 0 && self.ranges[i - 1].1 > a { + self.ranges.remove(i - 1); + } + self.note_invalidation(0, usize::MAX); + } + return; + } + let (lo, hi) = page_span(a, n); + self.subtract(lo, hi); + self.note_invalidation(lo, hi); + } +} + +/// Leaf lock (never held across OS syscalls or `STATE`): cached known-accessible source regions for +/// `holes_now`. +static SOURCE_REGIONS: Mutex = Mutex::new(SourceRegions { rev: 0, ranges: Vec::new(), recent: VecDeque::new() }); + +/// Drop `[a, a + n)` (or the region at `a` when `n == 0`) from the `source_holes` region cache. +/// Call around any decommit, release, or non-writable `VirtualProtect` of process memory. +pub fn invalidate_source_range(a: usize, n: usize) { + SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()).invalidate(a, n); +} + +/// Fast-path check for `gpu::shader::readable`: returns `true` if `[p, end)` lies completely +/// inside a cached committed, readable region (`SOURCE_REGIONS`). Never returns a false positive: +/// every free, decommit, and non-writable protection change in `kernelx` / `sparse` punches out +/// the affected span. +pub(crate) fn known_readable(p: usize, end: usize) -> bool { + if !source_holes_cache_on() || p >= end { + return false; + } + let s = SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let i = s.ranges.partition_point(|&(lo, _)| lo <= p); + i > 0 && s.ranges[i - 1].1 >= end +} + +/// Snapshot the current invalidation revision of `SOURCE_REGIONS` before querying Windows. +pub(crate) fn source_regions_rev() -> u64 { + SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()).rev +} + +/// Record `[lo, hi)` (already verified `MEM_COMMIT` + readable via `VirtualQuery`) into +/// `SOURCE_REGIONS`, only for regions whose lifecycle is 100% intercepted by XCL (`uma` windows +/// or `kernelx` graphics reservations) and subtracting any invalidations since `rev0`. +pub(crate) fn cache_readable_region(lo: usize, hi: usize, rev0: u64) { + if !source_holes_cache_on() || lo >= hi { + return; + } + let mut s = SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let delta = s.rev.wrapping_sub(rev0); + let can_commit = delta == 0 + || (delta <= s.recent.len() as u64 + && s.recent.iter().rev().take(delta as usize).all(|&(_, rlo, rhi)| !(rlo == 0 && rhi == usize::MAX))); + if can_commit { + s.insert(lo, hi); + if delta > 0 { + let subtracts: Vec<(usize, usize)> = s.recent.iter().rev().take(delta as usize).map(|&(_, rlo, rhi)| (rlo, rhi)).collect(); + for (rlo, rhi) in subtracts { + s.subtract(rlo, rhi); + } + } + } +} + +/// Cached `source_holes`: checks `SOURCE_REGIONS` first, then runs sorted `VirtualQuery` over +/// cache misses without `K32QueryWorkingSetEx` working-set-lock contention, caching newly +/// discovered accessible spans (minus any concurrent invalidations or `freeing` ranges). +unsafe fn source_holes_cached(tiles: &[usize], freeing: &[(usize, usize)]) -> Vec { + if tiles.is_empty() { + return Vec::new(); + } + if !source_holes_cache_on() { + return source_holes(tiles); + } + let t0 = super::look_stats::deep().then(std::time::Instant::now); + let mut out = vec![0u16; tiles.len()]; + let mut misses: Vec<(usize, usize)> = Vec::new(); + let rev0 = { + let s = SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + for (idx, &t) in tiles.iter().enumerate() { + if !s.contains_tile(t) { + misses.push((t, idx)); + } + } + s.rev + }; + if !misses.is_empty() { + misses.sort_unstable_by_key(|&(t, _)| t); + let mut region = (0usize, 0usize, false); + let mut newly_accessible: Vec<(usize, usize)> = Vec::new(); + for (t, idx) in misses { + if region.0 <= t && t.saturating_add(TILE) <= region.1 { + out[idx] = if region.2 { 0 } else { 0xFFFF }; + continue; + } + let mut holes = 0xFFFFu16; + for i in 0..PAGES_PER_TILE { + let pg = t + i * PAGE; + if !(region.0..region.1).contains(&pg) { + #[cfg(test)] + tests::VIRTUAL_QUERIES.with(|n| n.set(n.get() + 1)); + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + region = if VirtualQuery(pg as *const c_void, &mut mbi, std::mem::size_of::()) == 0 || mbi.RegionSize == 0 { + (pg, pg + PAGE, false) + } else { + let ok = mbi.State == MEM_COMMIT && mbi.Protect != 0 && (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) == 0; + let lo = (mbi.BaseAddress as usize).min(pg); + let hi = (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize).max(pg + PAGE); + if ok { + newly_accessible.push((lo, hi)); + } + (lo, hi, ok) + }; + } + if region.2 { + holes &= !(1u16 << i); + } + } + out[idx] = holes; + } + if !newly_accessible.is_empty() { + let mut s = SOURCE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let delta = s.rev.wrapping_sub(rev0); + let can_commit = delta == 0 + || (delta <= s.recent.len() as u64 + && s.recent.iter().rev().take(delta as usize).all(|&(_, lo, hi)| !(lo == 0 && hi == usize::MAX))); + if can_commit { + for (lo, hi) in newly_accessible { + s.insert(lo, hi); + } + if delta > 0 { + let subtracts: Vec<(usize, usize)> = s.recent.iter().rev().take(delta as usize).map(|&(_, lo, hi)| (lo, hi)).collect(); + for (lo, hi) in subtracts { + s.subtract(lo, hi); + } + } + for &(a, end) in freeing { + s.subtract(a, end); + } + } + } + } + if let Some(t0) = t0 { + VIEW_SPLIT.add(VS_ASKED_US, t0.elapsed().as_micros() as u64); + VIEW_SPLIT.add(VS_ASKED_TILES, tiles.len() as u64); + } + out +} + /// `XCL_LOOK_STATS=2`: where the GPU-view tiles part of a submit's time with the sparse lock goes /// (`LS_VIEWS`, the sparse lock split line): [µs linking tiles whose page changed /// (`remap_mirrors`), µs giving asked tiles video memory (`map_mirrors`), µs for the CPU writes @@ -6186,6 +6420,7 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + invalidate_source_range(a, n); let mut g = lock_in_turn(&STATE, &SUBMITS_WAITING); let _held = holding(Holder::Commits); forget_released(&mut g); @@ -6360,6 +6595,7 @@ impl State { /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps /// them and frees their pool tiles) unsafe fn decommit_range(&mut self, a: usize, n: usize) { + invalidate_source_range(a, n); // (committed again, these pages hold zeros: a CPU read's copy back of them is old) self.spoil(a, n); let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); @@ -6943,10 +7179,12 @@ pub unsafe fn source_decommit(a: usize, n: usize, os: impl FnOnce() -> R) -> return os(); } let (span, shown) = freeing_begins(&SOURCES, a, n); + invalidate_source_range(a, n); if shown { source_decommitted(a, n); } let r = os(); + invalidate_source_range(a, n); freeing_ends(&SOURCES, span); r } @@ -6960,10 +7198,12 @@ pub unsafe fn source_release(a: usize, n: usize, os: impl FnOnce() -> R) -> R return os(); } let (span, shown) = freeing_begins(&SOURCES, a, n); + invalidate_source_range(a, n); if shown { source_decommitted(a, n); } let r = os(); + invalidate_source_range(a, n); forget_mirrors(a, n); freeing_ends(&SOURCES, span); r @@ -6999,6 +7239,7 @@ pub fn forget_mirrors(a: usize, n: usize) { if n == 0 { return; } + invalidate_source_range(a, n); let end = a.saturating_add(n); // (out of the queue before out of the set: an ask in between finds the tile still asked // for, or stays queued, and the count after it has the thread ask again. The other way @@ -7443,7 +7684,7 @@ impl State { /// is in the list read here. unsafe fn holes_now(&self, tiles: &[usize]) -> Vec { let freeing = lock_sources(self.sources).freeing.clone(); - let mut holes = source_holes(tiles); + let mut holes = source_holes_cached(tiles, &freeing); for &(a, end) in &freeing { for (h, &t) in holes.iter_mut().zip(tiles) { let (lo, hi) = (a.max(t), end.min(t + TILE)); @@ -7545,6 +7786,7 @@ impl State { /// holes (`decommit_tiles`); a tile all holes is parked, and stays in `mirrors` (a commit and /// write there gives it video memory again). unsafe fn source_decommitted_in(&mut self, a: usize, n: usize) { + invalidate_source_range(a, n); let end = a.saturating_add(n); for t in self.src_tiles_in(a, end) { let (lo, hi) = (a.max(t), end.min(t + TILE)); @@ -13001,6 +13243,53 @@ mod tests { } } + /// `source_holes_cached` caches known-accessible regions across calls (zero VirtualQuery on + /// repeat queries even for unsorted tiles), keeps unrelated regions cached when another range + /// is freed, immediately exposes a decommitted hole after `invalidate_source_range`, and sees + /// a newly re-committed page without needing commit invalidation. + #[test] + fn source_holes_cached_reuses_regions_and_invalidates_only_freed_ranges() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + const TILES: usize = 32; + unsafe { + let a = VirtualAlloc(std::ptr::null(), TILES * TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let b = VirtualAlloc(std::ptr::null(), 4 * TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(a != 0 && b != 0); + // Unsorted tiles inside `a` populate the region cache in one VirtualQuery. + let tiles_a: Vec = [20, 3, 31, 0, 10].into_iter().map(|k| a + k * TILE).collect(); + let q0 = VIRTUAL_QUERIES.with(|n| n.get()); + assert_eq!(source_holes_cached(&tiles_a, &[]), vec![0; tiles_a.len()]); + let q1 = VIRTUAL_QUERIES.with(|n| n.get()); + assert!(q1 - q0 >= 1 && q1 - q0 <= 2, "initial miss should populate `a` in <= 2 queries, got {}", q1 - q0); + + // Second query over different tiles in `a` makes zero VirtualQuery calls. + let more_a: Vec = [1, 15, 29, 7].into_iter().map(|k| a + k * TILE).collect(); + assert_eq!(source_holes_cached(&more_a, &[]), vec![0; more_a.len()]); + assert_eq!(VIRTUAL_QUERIES.with(|n| n.get()), q1, "cache hit must do 0 VirtualQuery calls"); + + // Invalidating unrelated region `b` must not evict `a`. + invalidate_source_range(b, 4 * TILE); + assert_eq!(source_holes_cached(&tiles_a, &[]), vec![0; tiles_a.len()]); + assert_eq!(VIRTUAL_QUERIES.with(|n| n.get()), q1, "unrelated free must not evict `a`"); + + // Decommitting one page in tile 10 and invalidating it exposes the hole immediately. + let hole_pg = a + 10 * TILE + 5 * PAGE; + assert_ne!(VirtualFree(hole_pg as *mut c_void, PAGE, MEM_DECOMMIT), 0); + invalidate_source_range(hole_pg, PAGE); + let holes = source_holes_cached(&[a + 10 * TILE, a + 20 * TILE], &[]); + assert_eq!(holes, vec![1 << 5, 0]); + + // Re-committing the hole is seen immediately (holes are never cached). + assert!(!VirtualAlloc(hole_pg as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert_eq!(source_holes_cached(&[a + 10 * TILE], &[]), vec![0]); + + invalidate_source_range(a, TILES * TILE); + invalidate_source_range(b, 4 * TILE); + assert_ne!(VirtualFree(a as *mut c_void, 0, MEM_RELEASE), 0); + assert_ne!(VirtualFree(b as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// A tile of a GPU view holds what its CPU view holds once it is asked for (the CPU wrote it /// before), and follows the CPU's writes, the many small ones too (dispatches) – far into the /// window and across the 1 GiB a dispatch reaches on a GPU. Before, the GPU read zeros there. diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index b5ba9e5883..27f1489099 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -219,6 +219,7 @@ pub mod mirrors { if t & PAGES_64K != PAGES_64K || t & 0x1000 != 0 { return false; } + crate::hle::d3d12x::sparse::invalidate_source_range(base, size); let mut s = STATE.lock().unwrap(); if p & GRAPHICS_NOACCESS != 0 && p & 0xFF == super::mem::PAGE_NOACCESS { if let Some(cpu) = unpaired_cpu(&s, size) { @@ -1240,10 +1241,16 @@ unsafe fn source_part_going(part: Option<(usize, usize)>, release: bool, os: pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32) -> BOOL { let _cost = super::api_cost::time(super::api_cost::Call::Memory); if let Some(ok) = placeholders::free(addr, size, t) { + if ok != 0 { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } return ok; } if alias::enabled() { if let Some(ok) = alias::free_space(addr as usize, size, t) { + if ok { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } return ok as BOOL; } } @@ -1328,6 +1335,9 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 mirrors::released(addr as usize); } let ok = source_part_going(part, release, || mem::VirtualFree(addr, size, t)); + if ok != 0 { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, whole); + } if ok != 0 && t & 0x8000 != 0 { let released = GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)); if let Some(len) = released { @@ -1367,6 +1377,11 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a) || u.is_view(a)) || in_graphics_reservation(a) || alias::in_space(a) { return VirtualFree(addr, size, t); } + let ok = mem::VirtualFreeEx(proc_, addr, size, t); + if ok != 0 { + crate::hle::d3d12x::sparse::invalidate_source_range(a, size); + } + return ok; } mem::VirtualFreeEx(proc_, addr, size, t) } @@ -1383,10 +1398,15 @@ pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p let writable = read_write(protection); if !writable { note_protection(addr, size, protection); + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); } let ok = mem::VirtualProtect(addr, size, protection, old); - if ok != 0 && writable { - note_protection(addr, size, protection); + if ok != 0 { + if writable { + note_protection(addr, size, protection); + } else { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } } ok } @@ -1397,10 +1417,15 @@ pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_voi let writable = read_write(protection); if own && !writable { note_protection(addr, size, protection); + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); } let ok = mem::VirtualProtectEx(proc_, addr, size, protection, old); - if ok != 0 && own && writable { - note_protection(addr, size, protection); + if ok != 0 && own { + if writable { + note_protection(addr, size, protection); + } else { + crate::hle::d3d12x::sparse::invalidate_source_range(addr as usize, size); + } } ok } @@ -2598,6 +2623,7 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: crate::hle::d3d12x::sparse::remapped(&mirrors::page_freed(page)); } alias::free(pages); + crate::hle::d3d12x::sparse::invalidate_source_range(0, 0); return 1; } // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes From 4d6d4a7741ade4674d3c0947353ed1cb5f216942 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:01:59 +0100 Subject: [PATCH 159/175] D3D12.X: remove per-draw/barrier mutex contention, cache barrier descs, and fix retained PSO wait budget - Track cpu_backed_count in O(1) in title_textures::Table instead of scanning 55k+ entries under TEXTURES lock on every texture create/release. - Add leaf RwLock mirrors (SHADOWED_IDS, RES_GENERATIONS, SUPERSEDED_IDS, TITLE_TEX_IDS) so uncover_drawn, capture_transitions, capture_gpu_write, placements::note_use(s), and format_alias::note_title_transition use shared read locks instead of contending on global mutexes during draw/dispatch/barrier recording. - Merge duplicate descriptor-table scans in bind.rs into single-pass scan_bound_tables and add known_readable fast path to read_committed_into. - Add sharded DESC_CACHE in barrier_groups.rs (for adopted resources, cleared in forget) so texture barriers and list_x::is_buffer skip per-barrier readable() + COM GetDesc(). - Honor XCL_GFX_PSO_WAIT_MS, XCL_CS_PSO_WAIT_MS, and kept override in pso_async::resolve_retained_for_emission. Measured on RX 9070 XT over 5+ minutes of world gameplay (next-r20 vs next-r14): - draw recording: 168.1 us -> 47.6 us avg (15.8 us warm, 3.53x faster) - dispatch recording: 140.0 us -> 68.4 us avg (2.05x faster) - barriers and flushes: 145.7 us -> 117.2 us avg (48 us warm, 1.24x faster) - placed textures: 584.1 us -> 413.5 us avg (1.41x faster) - physical page calls: 4.87 ms -> 2.65 ms avg (1.84x faster) - sustained world FPS (t>=120s): 2.10 -> 2.54 fps avg (+21%), 5.5 -> 7.0 fps peak (+27%), 591 -> 737 frames (+24.7%), 0 TDRs over 420 s. --- crates/xcl/src/hle/d3d12x/barrier_groups.rs | 64 +++++-- crates/xcl/src/hle/d3d12x/bind.rs | 82 ++++----- crates/xcl/src/hle/d3d12x/format_alias.rs | 20 ++- crates/xcl/src/hle/d3d12x/list_x.rs | 5 +- crates/xcl/src/hle/d3d12x/placements.rs | 57 +++++- crates/xcl/src/hle/d3d12x/pso_async.rs | 75 +++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 185 ++++++++++++++++---- 7 files changed, 383 insertions(+), 105 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/barrier_groups.rs b/crates/xcl/src/hle/d3d12x/barrier_groups.rs index 91a4010c2f..1e9590851e 100644 --- a/crates/xcl/src/hle/d3d12x/barrier_groups.rs +++ b/crates/xcl/src/hle/d3d12x/barrier_groups.rs @@ -272,6 +272,16 @@ struct Tracked { plane_stride: u32, } +/// Cached texture geometry/flags for a live `ID3D12Resource`, cleared in `forget(res)` when the +/// resource's last reference is released (`real::res_release`). Avoids `shader::readable` +/// (`K32QueryWorkingSetEx`) and COM `GetDesc()` on every texture barrier. +#[derive(Clone, Copy)] +struct CachedDesc { + tex: Option<(bool, u32, u32, u32, Asked)>, +} + +static DESC_CACHE: Sharded = Sharded::new(); + /// The per-plane state each texture was last moved to by a barrier group (the title's recording order). static LAST: Sharded = Sharded::new(); /// Texture barriers read, and transitions made of them. @@ -300,11 +310,46 @@ pub(super) fn note_legacy_state(res: usize, sub: u32, after: u32) { /// The last reference of `res` goes (`real::res_release`). pub(super) fn forget(res: usize) { + DESC_CACHE.remove(res); if COUNTS[0].load(Ordering::Relaxed) != 0 { LAST.remove(res); } } +/// Cached texture descriptor lookup (None for buffers or unreadable pointers). +unsafe fn cached_desc(res: usize) -> Option<(bool, u32, u32, u32, Asked)> { + if let Some(c) = DESC_CACHE.get(res) { + return c.tex; + } + if !crate::gpu::shader::readable(res, 8) { + return None; + } + let r = res as *mut c_void; + let d = ID3D12Resource::from_raw_borrowed(&r)?.GetDesc(); + let tex = if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + None + } else { + let depth = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0; + let array = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { d.DepthOrArraySize as u32 }; + // (two planes: the depth-stencil formats R32G8X24 and R24G8 and their views) + let planes = if matches!(d.Format.0, 19..=22 | 44..=47) { 2 } else { 1 }; + let asked = Asked { flags: d.Flags.0 as u32, subresources: d.MipLevels as u32 * array * planes, format: d.Format.0 }; + Some((depth, d.MipLevels as u32, array, planes, asked)) + }; + if super::real::is_adopted(r) { + DESC_CACHE.insert(res, CachedDesc { tex }); + } + tex +} + +/// Fast cached `Dimension == BUFFER` check for `list_x::resource_barrier_x`. +pub(super) unsafe fn is_buffer_cached(res: usize) -> bool { + if res == 0 { + return true; + } + cached_desc(res).is_none() +} + /// `state` as a texture with the PC resource flags `flags` (D3D12_RESOURCE_FLAGS) can be in it on /// a direct list (`direct`) or a compute one: the reading states the texture or the list cannot /// have are left out of it. None: it cannot be there at all (a render target state of a texture @@ -378,22 +423,11 @@ pub(super) unsafe fn transitions(n: u32, groups: *const c_void, direct: bool) -> let mut out = transitions_of( &textures, &mut |res| { - if !crate::gpu::shader::readable(res, 8) { - return None; - } - let r = res as *mut c_void; - let d = ID3D12Resource::from_raw_borrowed(&r)?.GetDesc(); - if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { - return None; - } - let depth = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0; - let array = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { d.DepthOrArraySize as u32 }; - // (two planes: the depth-stencil formats R32G8X24 and R24G8 and their views) - let planes = if matches!(d.Format.0, 19..=22 | 44..=47) { 2 } else { 1 }; - if !asked.iter().any(|a| a.0 == res) { - asked.push((res, Asked { flags: d.Flags.0 as u32, subresources: d.MipLevels as u32 * array * planes, format: d.Format.0 })); + let (depth, mips, array, planes, a) = cached_desc(res)?; + if !asked.iter().any(|x| x.0 == res) { + asked.push((res, a)); } - Some((depth, d.MipLevels as u32, array, planes)) + Some((depth, mips, array, planes)) }, &mut |res| LAST.get(res).map_or([None, None], |t| t.states), &mut |res, plane, state, stride| { diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 14e2cde9a5..8d32ebc00e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1344,10 +1344,19 @@ pub(super) fn bound_pso(this: *mut c_void) -> usize { /// Remap any superseded targets named in the first 256 slots of each descriptor table in `layout` /// / `args`. Only called when `placements::any_superseded()` is true. -unsafe fn note_superseded_in_tables(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8]) { - let Some(layout) = layout else { return }; - const TABLE_SLOTS: usize = 256; - let mut table = [0u8; TABLE_SLOTS * 32]; +/// Single-pass scan of bound descriptor tables for both superseded target reactivation +/// (`placements::note_uses`, up to 256 slots) and shadowed sampled-texture reactivation +/// (`title_textures::uncover_drawn`, first 64 slots). Avoids reading every table twice per draw +/// and checks each set with one shared `RwLock::read()`. +unsafe fn scan_bound_tables(u: &crate::gpu::uma::Uma, layout: Option<&Layout>, args: &[u8], check_superseded: bool, check_shadowed: bool) { + let Some(layout) = layout.filter(|_| check_superseded || check_shadowed) else { return }; + const SUP_SLOTS: usize = 256; + const SHAD_SLOTS: usize = 64; + let slots = if check_superseded { SUP_SLOTS } else { SHAD_SLOTS }; + let mut table = [0u8; SUP_SLOTS * 32]; + let byte_len = slots * 32; + let mut sup_res = Vec::new(); + let mut shad_res = Vec::new(); for p in &layout.params { let Param::Table { at } = *p else { continue }; let at = at as usize; @@ -1357,23 +1366,34 @@ unsafe fn note_superseded_in_tables(u: &crate::gpu::uma::Uma, layout: Option<&La continue; } let addr = u.base() + offset; - if u.in_committed_window(addr, table.len()) { - std::ptr::copy_nonoverlapping(addr as *const u8, table.as_mut_ptr(), table.len()); + let slice = &mut table[..byte_len]; + if u.in_committed_window(addr, byte_len) || super::sparse::known_readable(addr, addr.saturating_add(byte_len)) { + std::ptr::copy_nonoverlapping(addr as *const u8, slice.as_mut_ptr(), byte_len); } else { - table.fill(0); - super::title_textures::read_committed_into(addr, &mut table); + super::title_textures::read_committed_into(addr, slice); } - for slot in table.chunks_exact(32) { + for (slot_idx, slot) in slice.chunks_exact(32).enumerate() { let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); if slot[15] >> 4 < 8 || index == 0 { continue; } let res = super::console_heap::named_by_index(index); if res != 0 && res != super::console_heap::GONE { - super::placements::note_use(res); + if check_superseded && !sup_res.contains(&res) { + sup_res.push(res); + } + if check_shadowed && slot_idx < SHAD_SLOTS && !shad_res.contains(&res) { + shad_res.push(res); + } } } } + if check_superseded && !sup_res.is_empty() { + super::placements::note_uses(&sup_res); + } + if check_shadowed && !shad_res.is_empty() { + super::title_textures::uncover_drawn(&shad_res); + } } /// `XCL_TRACE_SLOT=`: the image views at that place of the descriptor tables of graphics @@ -1446,36 +1466,7 @@ fn table_resources_of(this: *mut c_void, gfx: bool, slots: usize) -> Vec /// Check the first 64 slots of each bound table. A texture descriptor copied as bytes still /// samples the resource named by its heap index in word 0. unsafe fn uncover_bound_tables(layout: Option<&Layout>, args: &[u8], u: &crate::gpu::uma::Uma) { - let Some(layout) = layout.filter(|_| super::title_textures::has_shadowed()) else { return }; - const TABLE_SLOTS: usize = 64; - let mut resources = Vec::new(); - for p in &layout.params { - let Param::Table { at } = *p else { continue }; - let at = at as usize; - let Some(word) = args.get(at..at + 4) else { continue }; - let offset = u32::from_le_bytes(word.try_into().unwrap()) as usize; - if offset == 0 { - continue; - } - let addr = u.base() + offset; - let mut table = [0u8; TABLE_SLOTS * 32]; - if u.in_committed_window(addr, table.len()) { - std::ptr::copy_nonoverlapping(addr as *const u8, table.as_mut_ptr(), table.len()); - } else { - super::title_textures::read_committed_into(addr, &mut table); - } - for slot in table.chunks_exact(32) { - let index = u32::from_le_bytes(slot[..4].try_into().unwrap()); - if slot[15] >> 4 < 8 || index == 0 { - continue; - } - let res = super::console_heap::named_by_index(index); - if res != 0 && res != super::console_heap::GONE && !resources.contains(&res) { - resources.push(res); - } - } - } - super::title_textures::uncover_drawn(&resources); + scan_bound_tables(u, layout, args, false, super::title_textures::has_shadowed()); } /// A draw whose result is drawn once and kept (`pso_async::is_kept`: the title's bake of its @@ -6283,8 +6274,10 @@ unsafe fn bind_abi_with_root_resolved( if gfx { trace_table_slot(u, layout.as_deref(), &args, original); } - if super::placements::any_superseded() { - note_superseded_in_tables(u, layout.as_deref(), &args); + let check_sup = super::placements::any_superseded(); + let check_shad = super::title_textures::has_shadowed(); + if check_sup || check_shad { + scan_bound_tables(u, layout.as_deref(), &args, check_sup, check_shad); } std::ptr::copy_nonoverlapping(args[inline..].as_ptr(), table_at as *mut u8, args.len() - inline); let io = prepared_abi_io(layout.as_deref(), &args, table_at, gfx, user_sgprs, u.base(), heaps, limits, groups, group_limit); @@ -6306,9 +6299,8 @@ unsafe fn bind_abi_with_root_resolved( views[2 + k] = super::real::uma_window_va(k).filter(|&v| v != 0).unwrap_or(first); } let pc = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("pipeline")?.clone(); - // shadowed textures the draw's tables name are made active again; a bake pipeline's draws - // (`pso_async::is_kept`) also the ones they pick by index - uncover_bound_tables(layout.as_deref(), &args, u); + // (bound tables already checked by `scan_bound_tables` above; a bake pipeline's draws + // (`pso_async::is_kept`) also check the ones they pick by index) if gfx { let bake = super::pso_async::is_kept(original); let trace = super::indexed::trace_on(); diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs index c490d8a3e0..761f0c20d6 100644 --- a/crates/xcl/src/hle/d3d12x/format_alias.rs +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -21,7 +21,7 @@ use std::collections::{HashMap, HashSet}; use std::ffi::c_void; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Mutex, OnceLock, RwLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -388,6 +388,11 @@ impl AliasTable { self.by_va.entry(tex.va).or_default().push(res); if tex.owner == Owner::TitlePlaced { TRACKED_TITLE_TEX.fetch_add(1, Ordering::Relaxed); + TITLE_TEX_IDS + .write() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(HashSet::new) + .insert(res); } self.by_res.insert(res, tex); mark_gpu_written @@ -461,6 +466,9 @@ impl AliasTable { if let Some(old) = self.by_res.remove(&res) { if old.owner == Owner::TitlePlaced { TRACKED_TITLE_TEX.fetch_sub(1, Ordering::Relaxed); + if let Some(set) = TITLE_TEX_IDS.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + set.remove(&res); + } } if let Some(list) = self.by_va.get_mut(&old.va) { list.retain(|&r| r != res); @@ -482,6 +490,10 @@ impl AliasTable { } static TABLE: Mutex> = Mutex::new(None); +/// Leaf lock mirror of `Owner::TitlePlaced` resource pointers in `TABLE::by_res` so per-barrier +/// `note_title_transition` rejects untracked resources (buffers, non-aliased RTs) with a shared +/// read lock instead of contending on `TABLE`. +static TITLE_TEX_IDS: RwLock>> = RwLock::new(None); static TRACKED_TITLE_TEX: AtomicUsize = AtomicUsize::new(0); static ACTIVE_PAIRS: AtomicUsize = AtomicUsize::new(0); static ACTIVE_PLACED_UAV_PAIRS: AtomicUsize = AtomicUsize::new(0); @@ -818,6 +830,12 @@ pub(super) fn note_title_transition(res: usize, subresource: u32, before: u32, a if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 || flags == BARRIER_BEGIN_ONLY { return; } + { + let ids = TITLE_TEX_IDS.read().unwrap_or_else(|e| e.into_inner()); + if !ids.as_ref().is_some_and(|s| s.contains(&res)) { + return; + } + } let mut g = TABLE.lock().unwrap(); let Some(t) = g.as_mut() else { return; diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 17e5154757..e4ccbf9bb8 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -6804,7 +6804,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 plan }); // the states uploads into textures kept in step start from once this list has run - if super::title_textures::any() || super::lut3d::on() { + if (super::title_textures::any() || super::lut3d::on()) && out.iter().any(|b| b[0] == 0) { let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = out.iter().filter(|b| b[0] == 0).map(|b| ((b[2] as u64 | (b[3] as u64) << 32) as usize, b[4], D3D12_RESOURCE_STATES(b[6] as i32))).collect(); note_texture_transitions(this as usize, &t); @@ -6934,8 +6934,7 @@ const UNORDERED_ACCESS: u32 = 0x8; /// Whether `res` is a buffer (null / unknown: taken as one – its states are left alone). unsafe fn is_buffer(res: usize) -> bool { - let r = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&r).is_none_or(|x| x.GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) + super::barrier_groups::is_buffer_cached(res) } /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) diff --git a/crates/xcl/src/hle/d3d12x/placements.rs b/crates/xcl/src/hle/d3d12x/placements.rs index 5dda38c2d4..ef3e635c8f 100644 --- a/crates/xcl/src/hle/d3d12x/placements.rs +++ b/crates/xcl/src/hle/d3d12x/placements.rs @@ -12,10 +12,10 @@ //! before (`late_release::hold_unmap`), and come back when the title uses it again (a barrier or a //! copy of it: `note_use`) or releases the newer ones over it while it still holds it. -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; -use std::sync::Mutex; +use std::sync::{Mutex, RwLock}; use std::time::Instant; use windows::core::Interface; @@ -186,6 +186,8 @@ struct Registry { seq: u64, /// the superseded ones the title holds (`SUPERSEDED`) unmapped: usize, + /// Pending `(res, superseded)` updates to `SUPERSEDED_IDS`, flushed in `sync_superseded`. + superseded_delta: Vec<(usize, bool)>, } /// What a placement found (`Registry::place`). @@ -256,6 +258,7 @@ impl Registry { old.under.push(res); p.over.push(o); self.unmapped += 1; + self.superseded_delta.push((o, true)); out.victims.push(o); } } @@ -277,6 +280,7 @@ impl Registry { if !p.mapped { // (its tiles go with it: `vram::forget`) self.unmapped -= 1; + self.superseded_delta.push((res, false)); } let (over, under) = (std::mem::take(&mut p.over), std::mem::take(&mut p.under)); for n in under { @@ -307,6 +311,7 @@ impl Registry { if newer.is_empty() { old.mapped = true; self.unmapped -= 1; + self.superseded_delta.push((o, false)); remap.push(o); } else { old.under = newer; @@ -337,6 +342,7 @@ impl Registry { let Some(p) = self.live.get_mut(&res).filter(|p| !p.mapped && !p.released) else { return Vec::new() }; p.mapped = true; self.unmapped -= 1; + self.superseded_delta.push((res, false)); let under = std::mem::take(&mut p.under); for n in &under { if let Some(q) = self.live.get_mut(n) { @@ -482,6 +488,25 @@ unsafe fn map_again(remap: &[usize]) -> Vec { held } +/// Leaf lock mirroring currently superseded target resource pointers so `note_use` / `note_uses` +/// (called on every draw/dispatch/barrier) skip `REGISTRY.lock()` with a shared read lock. +static SUPERSEDED_IDS: RwLock>> = RwLock::new(None); + +fn sync_superseded(r: &mut Registry) { + SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + if !r.superseded_delta.is_empty() { + let mut g = SUPERSEDED_IDS.write().unwrap_or_else(|e| e.into_inner()); + let set = g.get_or_insert_with(HashSet::new); + for (res, sup) in r.superseded_delta.drain(..) { + if sup { + set.insert(res); + } else { + set.remove(&res); + } + } + } +} + /// Texture `res` placed at title address `va` on `pages` (`[start, end)`: its own title pages), /// its tiles mapped. Returns the older targets it supersedes: their tiles are to leave the shared /// pages once the queues are past the work submitted before (`late_release::hold_unmap`). @@ -492,7 +517,7 @@ pub(super) fn placed(res: usize, va: usize, pages: (usize, usize), backing: Back let mut g = REGISTRY.lock().unwrap(); let r = g.get_or_insert_with(Registry::default); let out = r.place(res, va, pages, backing, kind, desc, Instant::now(), look, retire); - SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + sync_superseded(r); let victims: Vec = out.victims.iter().filter_map(|&o| unsafe { resource(o) }).collect(); let held = unsafe { map_again(&out.remap) }; (out, victims, held) @@ -510,7 +535,7 @@ fn settle(f: impl FnOnce(&mut Registry) -> Vec) { let mut g = REGISTRY.lock().unwrap(); let Some(r) = g.as_mut() else { return }; let remap = f(r); - SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + sync_superseded(r); unsafe { map_again(&remap) } }; drop(held); @@ -538,6 +563,22 @@ pub(super) unsafe fn unmap_if_superseded(res: &ID3D12Resource) { } } +/// Batch `note_use`: checks all candidate resources under one shared `SUPERSEDED_IDS` read lock +/// and only acquires `REGISTRY` for resources that are actually superseded. +pub(super) fn note_uses(res: &[usize]) { + if res.is_empty() || SUPERSEDED.load(Ordering::Relaxed) == 0 { + return; + } + let hits: Vec = { + let g = SUPERSEDED_IDS.read().unwrap_or_else(|e| e.into_inner()); + let Some(set) = g.as_ref() else { return }; + res.iter().copied().filter(|r| *r != 0 && set.contains(r)).collect() + }; + for r in hits { + note_use(r); + } +} + /// Whether any live target is currently superseded (`SUPERSEDED != 0`). pub(super) fn any_superseded() -> bool { SUPERSEDED.load(Ordering::Relaxed) != 0 @@ -551,12 +592,18 @@ pub(super) fn note_use(res: usize) { if res == 0 || SUPERSEDED.load(Ordering::Relaxed) == 0 { return; } + { + let g = SUPERSEDED_IDS.read().unwrap_or_else(|e| e.into_inner()); + if !g.as_ref().is_some_and(|set| set.contains(&res)) { + return; + } + } static LOGGED: Mutex>> = Mutex::new(None); let held = { let mut g = REGISTRY.lock().unwrap(); let Some(r) = g.as_mut() else { return }; let under = r.use_again(res); - SUPERSEDED.store(r.unmapped, Ordering::Relaxed); + sync_superseded(r); if under.is_empty() { return; } diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 901e6c1b13..7d3eb73a72 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -12515,6 +12515,27 @@ fn resolve_wait_bound_and_pin(pso: usize) -> ((usize, bool), Option, + pso: usize, + all: Option, + gfx: Option, + cs: Option, +) -> usize { + if p.kept.load(Ordering::Acquire) { + return resolve_wait_pending(p, pso, None); + } + match gfx.filter(|_| !p.compute) { + Some(budget) => { + let start = std::time::Instant::now(); + let r = resolve_wait_pending(p, pso, Some(gfx_wait_left(budget, start))); + gfx_wait_spent(start.elapsed()); + r + } + None => resolve_wait_pending(p, pso, budget_for(p.compute, all, gfx, cs)), + } +} + /// Resolve one retained Pending to an exactly owned generation without consulting its title /// address. One-shot and recipe-backed builds share the same wait policy at this boundary. fn resolve_retained_for_emission(pso: usize, p: &Arc) -> PipelineChoice { @@ -12524,7 +12545,7 @@ fn resolve_retained_for_emission(pso: usize, p: &Arc) -> PipelineChoice return PipelineChoice::Unavailable; } p.note_use(); - let bound = resolve_wait_pending(p, pso, wait_budget()); + let bound = resolve_wait_pending_budgets(p, pso, wait_budget(), gfx_wait_budget(), cs_wait_budget()); let bound_unbuilt = p.bound_unbuilt(pso, bound); let (raw, generation, _) = pin_resolved(pso, p, bound, bound_unbuilt); match generation { @@ -13025,4 +13046,56 @@ mod backlog_tests { released(standin); } } + + #[test] + fn retained_resolution_honors_gfx_budget_and_kept_override() { + use std::time::{Duration, Instant}; + let (go, finish) = mpsc::channel::<()>(); + let standin = 0x7E57_C090usize; + submit_lazy( + standin, + false, + Box::new(move || { + let _ = finish.recv_timeout(Duration::from_secs(5)); + 0x6F6F + }), + 0x5EED_C090, + ); + let p = entry(standin).expect("pending graphics pipeline registered"); + let t0 = Instant::now(); + let bound = resolve_wait_pending_budgets(&p, standin, None, Some(Duration::from_millis(20)), None); + assert_eq!(bound, standin, "non-kept retained graphics bind must honor XCL_GFX_PSO_WAIT_MS"); + assert!(t0.elapsed() < Duration::from_secs(1)); + + // Reset late/kept state and verify a kept graphics pipeline still waits past the gfx budget. + let (go2, finish2) = mpsc::channel::<()>(); + let kept_standin = 0x7E57_C091usize; + submit_lazy( + kept_standin, + false, + Box::new(move || { + let _ = finish2.recv_timeout(Duration::from_secs(5)); + 0x6F70 + }), + 0x5EED_C091, + ); + kept(kept_standin); + let pk = entry(kept_standin).expect("kept pending graphics pipeline registered"); + let releaser = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(40)); + let _ = go2.send(()); + }); + let bound_kept = resolve_wait_pending_budgets(&pk, kept_standin, None, Some(Duration::from_millis(10)), None); + assert_eq!(bound_kept, 0x6F70, "kept retained graphics bind must wait past gfx budget"); + let _ = releaser.join(); + let _ = go.send(()); + // Wait for the first build to complete before calling `released`, so the worker does not + // try to COM-Release the synthetic sentinel pointer `0x6f6f` on an orphaned build. + let deadline = Instant::now() + Duration::from_secs(5); + while is_pending(standin) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(released(standin), 0x6F6F); + assert_eq!(released(kept_standin), 0x6F70); + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 9664fe84b6..9b1f2ec4c1 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -19,10 +19,10 @@ //! transitions of these textures are captured in each physical command-list segment's immutable //! submission effects and applied in submission order – per subresource once one is named. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -165,6 +165,13 @@ struct Table { /// ones; not GPU-written ones, which no CPU write there sends up): the part of the watched /// ranges that textures make (cheap to rebuild from, unlike all textures) coarse: BTreeMap, + /// O(1) count of `by_res` entries with `cpu_backed == true` (avoids scanning 55k+ entries on + /// every texture placement/release under `TEXTURES` lock). + cpu_backed_count: usize, + /// Pending `(res, inserted)` updates to `SHADOWED_IDS`, flushed in `update_lengths`. + shadowed_delta: Vec<(usize, bool)>, + /// True only for the process-global `TEXTURES` table (local test tables skip global mirrors). + is_global: bool, } /// A texture of `Table::displaced`. @@ -194,7 +201,16 @@ fn in_view_window(src: usize) -> bool { } impl Table { + #[cfg(test)] const fn new() -> Self { + Self::with_global(false) + } + + const fn new_global() -> Self { + Self::with_global(true) + } + + const fn with_global(is_global: bool) -> Self { Table { by_res: BTreeMap::new(), by_va: BTreeMap::new(), @@ -206,9 +222,46 @@ impl Table { pending_res: std::collections::BTreeSet::new(), displaced: BTreeMap::new(), coarse: BTreeMap::new(), + cpu_backed_count: 0, + shadowed_delta: Vec::new(), + is_global, + } + } + + #[inline] + fn insert_active(&mut self, res: usize, e: Entry) { + if e.cpu_backed { + self.cpu_backed_count += 1; + } + if let Some(prev) = self.by_res.insert(res, e) { + if prev.cpu_backed { + self.cpu_backed_count -= 1; + } } } + #[inline] + fn remove_active(&mut self, res: usize) -> Option { + let old = self.by_res.remove(&res)?; + if old.cpu_backed { + self.cpu_backed_count -= 1; + } + Some(old) + } + + #[inline] + fn insert_shadowed(&mut self, res: usize, e: Entry) { + self.shadowed.insert(res, e); + self.shadowed_delta.push((res, true)); + } + + #[inline] + fn remove_shadowed(&mut self, res: usize) -> Option { + let old = self.shadowed.remove(&res)?; + self.shadowed_delta.push((res, false)); + Some(old) + } + /// `watched`: the texture is not GPU-written, so its source's blocks of `coarse` are watched /// for it too (`unlink_src` is told the same). fn link_src(&mut self, res: usize, src: usize, size: usize, watched: bool) { @@ -362,7 +415,10 @@ impl Table { let (mut pending_delta, mut retired, mut to_unmap) = (0isize, 0usize, Vec::new()); for (ova, ores, _) in self.active_overlaps(va, end) { self.by_va.remove(&(ova, ores)); - if let Some(old) = self.by_res.remove(&ores) { + if let Some(old) = self.remove_active(ores) { + if self.is_global { + res_generation_remove(ores); + } self.unlink_src(ores, old.src, old.tex.size() as usize, !old.gpu_written); if old.pending { pending_delta -= 1; @@ -375,7 +431,10 @@ impl Table { } for (sva, sres, _) in self.shadowed_overlaps(va, end) { self.shadowed_by_va.remove(&(sva, sres)); - if let Some(old) = self.shadowed.remove(&sres) { + if let Some(old) = self.remove_shadowed(sres) { + if self.is_global { + res_generation_remove(sres); + } self.undisplace(sres, &old); if old.placed && !old.unmapped { to_unmap.push(sres); @@ -399,14 +458,14 @@ impl Table { let end = va.saturating_add(entry.tex.size() as usize); let mut pending_delta = 0isize; let mut to_unmap = Vec::new(); - if let Some(old) = self.by_res.remove(&res) { + if let Some(old) = self.remove_active(res) { self.unlink_src(res, old.src, old.tex.size() as usize, !old.gpu_written); self.by_va.remove(&(old.va, res)); if old.pending { pending_delta -= 1; } } - if let Some(old) = self.shadowed.remove(&res) { + if let Some(old) = self.remove_shadowed(res) { self.shadowed_by_va.remove(&(old.va, res)); self.undisplace(res, &old); } @@ -415,7 +474,7 @@ impl Table { continue; } self.by_va.remove(&(ova, ores)); - if let Some(mut old) = self.by_res.remove(&ores) { + if let Some(mut old) = self.remove_active(ores) { self.unlink_src(ores, old.src, old.tex.size() as usize, !old.gpu_written); if old.pending { pending_delta -= 1; @@ -429,7 +488,7 @@ impl Table { } self.max_shadowed_size = self.max_shadowed_size.max(oend.saturating_sub(ova)); self.shadowed_by_va.insert((ova, ores), oend); - self.shadowed.insert(ores, old); + self.insert_shadowed(ores, old); } } // Also release tiles of any already-shadowed exact-range sibling now overwritten by a @@ -451,9 +510,12 @@ impl Table { self.pending_res.insert(res); } self.by_va.insert((va, res), end); - let (src, size) = (entry.src, entry.tex.size() as usize); + let (src, size, generation) = (entry.src, entry.tex.size() as usize, entry.generation); self.link_src(res, src, size, !entry.gpu_written); - self.by_res.insert(res, entry); + self.insert_active(res, entry); + if self.is_global { + res_generation_set(res, generation); + } (pending_delta, to_unmap) } @@ -461,7 +523,7 @@ impl Table { /// remapping. Keep displaced textures mapped for work that may still be using them, and /// uploaded until frame `until`. fn uncover(&mut self, res: usize, until: u64) -> Option<(isize, bool)> { - let mut e = self.shadowed.remove(&res)?; + let mut e = self.remove_shadowed(res)?; self.shadowed_by_va.remove(&(e.va, res)); self.undisplace(res, &e); let size = e.tex.size() as usize; @@ -473,7 +535,7 @@ impl Table { continue; } self.by_va.remove(&(ova, ores)); - if let Some(old) = self.by_res.remove(&ores) { + if let Some(old) = self.remove_active(ores) { if old.pending { self.pending_res.remove(&ores); pending_delta -= 1; @@ -486,7 +548,7 @@ impl Table { } self.max_shadowed_size = self.max_shadowed_size.max(oend.saturating_sub(ova)); self.shadowed_by_va.insert((ova, ores), oend); - self.shadowed.insert(ores, old); + self.insert_shadowed(ores, old); } } if self.shadowed.is_empty() { @@ -503,7 +565,7 @@ impl Table { } self.by_va.insert((va, res), end); self.link_src(res, e.src, size, !e.gpu_written); - self.by_res.insert(res, e); + self.insert_active(res, e); Some((pending_delta, remap)) } @@ -538,7 +600,10 @@ impl Table { /// Remove `res` on COM release, reactivating any shadowed older textures it uncovered (newest /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap, uniform_state)`. fn remove(&mut self, res: usize) -> (bool, isize, Vec, Option) { - if let Some(old) = self.shadowed.remove(&res) { + if let Some(old) = self.remove_shadowed(res) { + if self.is_global { + res_generation_remove(res); + } self.shadowed_by_va.remove(&(old.va, res)); self.undisplace(res, &old); if self.shadowed.is_empty() { @@ -547,7 +612,10 @@ impl Table { let st = (old.states.len() == 1).then(|| old.states[0]); return (true, 0, Vec::new(), st); } - let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new(), None) }; + let Some(old) = self.remove_active(res) else { return (false, 0, Vec::new(), None) }; + if self.is_global { + res_generation_remove(res); + } self.unlink_src(res, old.src, old.tex.size() as usize, !old.gpu_written); let st = (old.states.len() == 1).then(|| old.states[0]); self.by_va.remove(&(old.va, res)); @@ -566,7 +634,7 @@ impl Table { continue; } self.shadowed_by_va.remove(&(sva, sres)); - if let Some(mut e) = self.shadowed.remove(&sres) { + if let Some(mut e) = self.remove_shadowed(sres) { self.undisplace(sres, &e); // (the one that lay over it may have been uploaded over the same video memory) texture_upload::forget(&e.known); @@ -586,7 +654,7 @@ impl Table { if e.pending { self.pending_res.insert(sres); } - self.by_res.insert(sres, e); + self.insert_active(sres, e); } } if self.shadowed.is_empty() { @@ -628,7 +696,7 @@ unsafe fn clone_resources(ptrs: &[usize]) -> Vec { } /// PC texture → its place in the title's memory -static TEXTURES: Mutex
= Mutex::new(Table::new()); +static TEXTURES: Mutex
= Mutex::new(Table::new_global()); // The dirty-page scan consumes write-watch state for every submission thread. // Keep the scan, pending-list update and GPU uploads together. static REFRESH: Mutex<()> = Mutex::new(()); @@ -665,10 +733,43 @@ unsafe fn committed_allocation_bytes(device: *mut c_void, resource: *mut c_void, if bytes == u64::MAX { 0 } else { bytes } } -fn update_lengths(t: &Table) { +/// Leaf lock mirroring `Table::shadowed` keys so `uncover_drawn` (called on every draw/dispatch) +/// can reject non-shadowed textures with a shared read lock instead of contending on `TEXTURES`. +static SHADOWED_IDS: RwLock>> = RwLock::new(None); +/// Leaf lock mirroring `res -> generation` for `by_res ∪ shadowed` so per-barrier +/// `capture_transitions` and per-copy/clear `capture_gpu_write` read generations with a shared +/// read lock instead of blocking behind `TEXTURES` during submit texture selection. +static RES_GENERATIONS: RwLock>> = RwLock::new(None); + +#[inline] +fn res_generation_set(res: usize, generation: u64) { + let mut g = RES_GENERATIONS.write().unwrap_or_else(|e| e.into_inner()); + g.get_or_insert_with(HashMap::new).insert(res, generation); +} + +#[inline] +fn res_generation_remove(res: usize) { + let mut g = RES_GENERATIONS.write().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.as_mut() { + m.remove(&res); + } +} + +fn update_lengths(t: &mut Table) { TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); - CPU_TEXTURES_LEN.store(t.by_res.values().filter(|e| e.cpu_backed).count(), Ordering::Relaxed); + CPU_TEXTURES_LEN.store(t.cpu_backed_count, Ordering::Relaxed); HAS_SHADOWED.store(!t.shadowed.is_empty(), Ordering::Relaxed); + if !t.shadowed_delta.is_empty() { + let mut g = SHADOWED_IDS.write().unwrap_or_else(|e| e.into_inner()); + let set = g.get_or_insert_with(HashSet::new); + for (res, inserted) in t.shadowed_delta.drain(..) { + if inserted { + set.insert(res); + } else { + set.remove(&res); + } + } + } } /// Whether a non-depth render target / UAV texture is small enough to be a CPU-filled glyph or UI @@ -764,7 +865,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); - update_lengths(&t); + update_lengths(&mut t); clone_resources(&unmap_ptrs) }; for r in &to_unmap { @@ -865,7 +966,7 @@ pub(super) unsafe fn register_gpu_owned( let mut t = TEXTURES.lock().unwrap(); let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); - update_lengths(&t); + update_lengths(&mut t); clone_resources(&unmap_ptrs) }; for r in &to_unmap { @@ -1201,9 +1302,9 @@ pub(super) fn capture_gpu_write(res: usize, subresource: u32) -> Option Option { let mut t = TEXTURES.lock().unwrap(); let (removed, delta, remap_ptrs, state) = t.remove(res); adjust_pending(delta); - update_lengths(&t); + update_lengths(&mut t); (removed, unsafe { clone_resources(&remap_ptrs) }, state) }; for r in &to_remap { @@ -1373,9 +1474,18 @@ pub(super) fn shadowed_among(res: &[usize]) -> usize { /// Restore sampled shadowed textures while recording so the next submit can upload them. pub(super) fn uncover_drawn(res: &[usize]) { - if res.is_empty() { + if res.is_empty() || !has_shadowed() { return; } + // Fast path: shared read lock on the shadowed ID mirror avoids locking the global `TEXTURES` + // mutex on the 99.9% of draws/dispatches that touch zero shadowed textures. + { + let g = SHADOWED_IDS.read().unwrap_or_else(|e| e.into_inner()); + let Some(set) = g.as_ref() else { return }; + if !res.iter().any(|r| set.contains(r)) { + return; + } + } let until = { let (p, b) = super::present::counters(); p.max(b) + DISPLACED_FRAMES @@ -1396,7 +1506,7 @@ pub(super) fn uncover_drawn(res: &[usize]) { return; } adjust_pending(delta); - update_lengths(&t); + update_lengths(&mut t); if t.displaced.values().any(|d| d.whole) { HAS_DISPLACED.store(true, Ordering::Release); } @@ -1480,7 +1590,7 @@ pub(super) fn ready_bake_sources(res: &[usize]) { let r = t.ready_for_bake(res, until); adjust_pending(r.pending_delta); if r.uncovered > 0 { - update_lengths(&t); + update_lengths(&mut t); if t.displaced.values().any(|d| d.whole) { HAS_DISPLACED.store(true, Ordering::Release); } @@ -1563,12 +1673,15 @@ pub(super) fn capture_transitions(transitions: &[(usize, u32, D3D12_RESOURCE_STA if !any() || transitions.is_empty() { return Vec::new(); } - let t = TEXTURES.lock().unwrap(); + let g = RES_GENERATIONS.read().unwrap_or_else(|e| e.into_inner()); + let Some(map) = g.as_ref() else { + return Vec::new(); + }; transitions .iter() .filter_map(|&(res, subresource, after)| { - let e = t.by_res.get(&res).or_else(|| t.shadowed.get(&res))?; - Some(Transition { res, generation: e.generation, subresource, after }) + let &generation = map.get(&res)?; + Some(Transition { res, generation, subresource, after }) }) .collect() } @@ -3979,7 +4092,9 @@ pub(super) unsafe fn read_committed_into(at: usize, out: &mut [u8]) { let Some(limit) = at.checked_add(len) else { return out.fill(0) }; // (the coherent window is committed as a whole: no `VirtualQuery`, which sizes a region by // walking it) - if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { + if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) + || super::sparse::known_readable(at, limit) + { std::ptr::copy_nonoverlapping(at as *const u8, out.as_mut_ptr(), len); return; } From 41aa60ce842060a597b7e8724896f7bf6a031af5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:01:59 +0100 Subject: [PATCH 160/175] Title patch: add XCL_UPSCALER_HEAP_MB override for Series S heap 2 growth Allow overriding the default +512 MB heap #2 growth when XCL_UPSCALER=6 is active via XCL_UPSCALER_HEAP_MB (0..=2048 MB), e.g. 256 MB saves 256 MB VRAM on 16 GB cards while booting and running 7+ minutes cleanly. --- crates/xcl/src/title_patch.rs | 44 +++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/title_patch.rs b/crates/xcl/src/title_patch.rs index e36c3dcc67..55b5526200 100644 --- a/crates/xcl/src/title_patch.rs +++ b/crates/xcl/src/title_patch.rs @@ -59,9 +59,21 @@ pub const SERIES_S_HEAPS: Site = Site { ], }; -/// What Series S's heap 2 (and so the total) gains with the title's own upscaler. +/// What Series S's heap 2 (and so the total) gains with the title's own upscaler by default. +/// Overridable via `XCL_UPSCALER_HEAP_MB` (e.g. `256` to save 256 MB VRAM on 16 GB cards). pub const OWN_UPSCALER_HEAP_GROWTH: u64 = 512 << 20; +fn upscaler_heap_growth(raw: Option<&str>) -> u64 { + let Some(v) = raw else { return OWN_UPSCALER_HEAP_GROWTH }; + match v.trim().parse::() { + Ok(mb) if mb <= 2048 => mb << 20, + _ => { + crate::xlog_warn!("XCL_UPSCALER_HEAP_MB={v}: expected 0..=2048 MB; using default {} MB", OWN_UPSCALER_HEAP_GROWTH >> 20); + OWN_UPSCALER_HEAP_GROWTH + } + } +} + /// Series S's row of heap sizes with heap 2 and the total grown by `growth` bytes. pub fn series_s_heaps_grown(growth: u64) -> Vec { let mut row = SERIES_S_HEAPS.bytes.to_vec(); @@ -126,15 +138,18 @@ pub unsafe fn apply(base: usize, size: usize, image: &str) { } // the title's own upscaler on a Series S: room for it in heap 2 (`SERIES_S_HEAPS`) if kind == 6 && picked == Patched::Done { - match write_site(base, size, &SERIES_S_HEAPS, &series_s_heaps_grown(OWN_UPSCALER_HEAP_GROWTH)) { - Patched::Done => crate::xlog_info!( - "{image}: {} at +{:#x}: heap 2 is {} MB (+{} MB) for the title's own upscaler", - SERIES_S_HEAPS.what, - SERIES_S_HEAPS.at, - (0x4fd0_0000 + OWN_UPSCALER_HEAP_GROWTH) >> 20, - OWN_UPSCALER_HEAP_GROWTH >> 20 - ), - other => crate::xlog_warn!("{image}: {} at +{:#x} not changed: {other:?} (another build of the title?)", SERIES_S_HEAPS.what, SERIES_S_HEAPS.at), + let growth = upscaler_heap_growth(std::env::var("XCL_UPSCALER_HEAP_MB").ok().as_deref()); + if growth > 0 { + match write_site(base, size, &SERIES_S_HEAPS, &series_s_heaps_grown(growth)) { + Patched::Done => crate::xlog_info!( + "{image}: {} at +{:#x}: heap 2 is {} MB (+{} MB) for the title's own upscaler", + SERIES_S_HEAPS.what, + SERIES_S_HEAPS.at, + (0x4fd0_0000 + growth) >> 20, + growth >> 20 + ), + other => crate::xlog_warn!("{image}: {} at +{:#x} not changed: {other:?} (another build of the title?)", SERIES_S_HEAPS.what, SERIES_S_HEAPS.at), + } } } } @@ -213,4 +228,13 @@ mod tests { assert_eq!(after[i], before[i]); } } + + #[test] + fn upscaler_heap_mb_switch_overrides_growth() { + assert_eq!(upscaler_heap_growth(None), OWN_UPSCALER_HEAP_GROWTH); + assert_eq!(upscaler_heap_growth(Some("256")), 256 << 20); + assert_eq!(upscaler_heap_growth(Some(" 0 ")), 0); + assert_eq!(upscaler_heap_growth(Some("9999")), OWN_UPSCALER_HEAP_GROWTH); + assert_eq!(upscaler_heap_growth(Some("bad")), OWN_UPSCALER_HEAP_GROWTH); + } } From cdad10fa5cf38fd87a2a2bd31b52dadd65dd81f6 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 04:47:47 +0100 Subject: [PATCH 161/175] VFS: keep the views kernelx::lazy::ensure opens until the I/O is done On amd-dev, kernelx::lazy::ensure returns an Opened guard: the views stay open only while it lives. main's ReadFileEx, WriteFile, WriteFileEx and scatter/gather hooks called ensure and dropped the result at once, so after the merge their buffers were closed again before the kernel touched them. Hold the guard across the call and, with an OVERLAPPED, until it no longer says pending (Ex calls return TRUE while their I/O is still queued). --- crates/xcl/src/hle/kernelx.rs | 2 +- crates/xcl/src/vfs_hooks.rs | 69 ++++++++++++++++++++++---------- crates/xcl/tests/lazy_file_io.rs | 2 +- 3 files changed, 49 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4b475ccddd..bcb48a3823 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -4051,7 +4051,7 @@ mod tests { // Freeing the physical page directly must drop the lazy entry so `r` is not // silently committed later by `lazy::ensure` or the VEH handler. assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, &mut page), 1); - lazy::ensure(r, 4); + drop(lazy::ensure(r, 4)); assert!(!committed_page(r), "freed away-mapped page must not remain in lazy::LAZY"); mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); } diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index bfd8b32dc9..ba82b131bf 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -548,51 +548,67 @@ unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, r } +/// The views `kernelx::lazy::ensure` opened for a call's buffer close when the call returns. With +/// an OVERLAPPED they are handed to `guards::open_until_done`, which keeps them until the +/// OVERLAPPED no longer says pending: a pending ReadFile returns FALSE + ERROR_IO_PENDING, but +/// ReadFileEx / WriteFileEx return TRUE while their I/O is still queued. +unsafe fn keep_open_while_pending(opened: Option, r: i32, ov: *mut c_void) { + let error = windows_sys::Win32::Foundation::GetLastError(); + if let Some(opened) = opened { + let failed = r == 0 && error != windows_sys::Win32::Foundation::ERROR_IO_PENDING; + if !ov.is_null() && !failed { + crate::hle::kernelx::guards::open_until_done(opened, ov as usize); + } + } + SetLastError(error); +} + // ReadFileEx, WriteFile and WriteFileEx reach NtReadFile / NtWriteFile without ReadFile, and // the scatter / gather calls NtReadFileScatter / NtWriteFileGather: their buffers too. unsafe extern "system" fn hk_read_file_ex(h: *mut c_void, buf: *mut c_void, n: u32, ov: *mut c_void, done: *const c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, *const c_void) -> i32; let orig = orig!(O_READ_FILE_EX as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); - } - orig(h, buf, n, ov, done) + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); + let r = orig(h, buf, n, ov, done); + keep_open_while_pending(opened, r, ov); + r } unsafe extern "system" fn hk_write_file(h: *mut c_void, buf: *const c_void, n: u32, written: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *const c_void, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_WRITE_FILE as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); - } - orig(h, buf, n, written, ov) + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); + let r = orig(h, buf, n, written, ov); + keep_open_while_pending(opened, r, ov); + r } unsafe extern "system" fn hk_write_file_ex(h: *mut c_void, buf: *const c_void, n: u32, ov: *mut c_void, done: *const c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *const c_void, u32, *mut c_void, *const c_void) -> i32; let orig = orig!(O_WRITE_FILE_EX as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); - } - orig(h, buf, n, ov, done) + let opened = (!buf.is_null()).then(|| crate::hle::kernelx::lazy::ensure(buf as usize, n as usize)); + let r = orig(h, buf, n, ov, done); + keep_open_while_pending(opened, r, ov); + r } /// The buffers of a FILE_SEGMENT_ELEMENT array: one system page each, as many as `n` bytes /// fill (a null one ends the array). Reads each entry through `ReadProcessMemory` so an /// invalid or unreadable segment pointer never faults here and is left for the kernel API to /// reject with its normal error. -unsafe fn ensure_segments(segs: *const u64, n: u32) { +unsafe fn ensure_segments(segs: *const u64, n: u32) -> Vec { const SYSTEM_PAGE: usize = 0x1000; + let mut opened = Vec::new(); if segs.is_null() || n == 0 { - return; + return opened; } let me = windows_sys::Win32::System::Threading::GetCurrentProcess(); let base = segs as usize; for i in 0..(n as usize).div_ceil(SYSTEM_PAGE) { let Some(addr) = base.checked_add(i * std::mem::size_of::()) else { - return; + return opened; }; - crate::hle::kernelx::lazy::ensure(addr, std::mem::size_of::()); + opened.push(crate::hle::kernelx::lazy::ensure(addr, std::mem::size_of::())); let mut entry: u64 = 0; let mut read: usize = 0; let ok = windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory( @@ -603,28 +619,37 @@ unsafe fn ensure_segments(segs: *const u64, n: u32) { &mut read, ); if ok == 0 || read != std::mem::size_of::() { - return; + return opened; } let p = entry as usize; if p == 0 { break; } - crate::hle::kernelx::lazy::ensure(p, SYSTEM_PAGE); + opened.push(crate::hle::kernelx::lazy::ensure(p, SYSTEM_PAGE)); } + opened } unsafe extern "system" fn hk_read_file_scatter(h: *mut c_void, segs: *const u64, n: u32, rsv: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *const u64, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_READ_FILE_SCATTER as F); - ensure_segments(segs, n); - orig(h, segs, n, rsv, ov) + let opened = ensure_segments(segs, n); + let r = orig(h, segs, n, rsv, ov); + for o in opened { + keep_open_while_pending(Some(o), r, ov); + } + r } unsafe extern "system" fn hk_write_file_gather(h: *mut c_void, segs: *const u64, n: u32, rsv: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *const u64, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_WRITE_FILE_GATHER as F); - ensure_segments(segs, n); - orig(h, segs, n, rsv, ov) + let opened = ensure_segments(segs, n); + let r = orig(h, segs, n, rsv, ov); + for o in opened { + keep_open_while_pending(Some(o), r, ov); + } + r } unsafe extern "system" fn hk_delete_file_w(n: *const u16) -> i32 { diff --git a/crates/xcl/tests/lazy_file_io.rs b/crates/xcl/tests/lazy_file_io.rs index a072d2eca6..b481accd93 100644 --- a/crates/xcl/tests/lazy_file_io.rs +++ b/crates/xcl/tests/lazy_file_io.rs @@ -46,7 +46,7 @@ impl Lazy { impl Drop for Lazy { fn drop(&mut self) { - lazy::ensure(self.0, self.1 * PAGE); + drop(lazy::ensure(self.0, self.1 * PAGE)); unsafe { VirtualFree(self.0 as *mut c_void, 0, MEM_RELEASE) }; } } From 944d9914b665a15d37026b7197a0c8b705763c6f Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:03:49 +0100 Subject: [PATCH 162/175] Tests: keep the graphics reload test's loaded values live graphics_stages_emit_a_repeated_load_once (from amd-dev, #2446) counts rawBufferLoad calls in vertex and pixel programs whose loaded SGPRs are never observed: a VS or PS writes no SGPRs back at its end. Main's #3503 (6ff86e30) made rawBufferLoad eligible for dead-code elimination and keeps a single raw load only so the shader flags stay valid, so in the merge every program in the test compiled to exactly one load. The store case then failed (1 vs 1 + 4), and the repeat case passed only because both sides were that one surviving load. Neither side's lowering is wrong and the merge did not combine the reload or window code badly: reload.rs, the follow_loads stages and the s_load path are amd-dev's as is. Each program now stores the sum it computes, so the loads it reads stay live and both assertions measure the reload again. --- crates/xcl/src/gpu/dxil/reload.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/reload.rs b/crates/xcl/src/gpu/dxil/reload.rs index 173c96cecb..ae7526e46b 100644 --- a/crates/xcl/src/gpu/dxil/reload.rs +++ b/crates/xcl/src/gpu/dxil/reload.rs @@ -414,10 +414,15 @@ mod tests { let opts = KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; let sum: I = ("S_ADD_U32", "ENC_SOP2", &[("SDST", 21), ("SSRC0", 20), ("SSRC1", 12)]); let store: I = ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 2), ("SADDR", 125)]); - let once_code = encode(&[LOAD, ADD, END]); - let repeat_code = encode(&[LOAD, ADD, LOAD, sum, END]); - let store_once_code = encode(&[LOAD, ADD, store, sum, END]); - let store_repeat_code = encode(&[LOAD, ADD, store, LOAD, sum, END]); + // A VS or PS keeps no SGPRs at its end: store the result, or the optimizer drops + // every load as dead and the counts say nothing. + let mov20: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 20)]); + let mov21: I = ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 21)]); + let out: I = ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 3), ("SADDR", 125)]); + let once_code = encode(&[LOAD, ADD, mov20, out, END]); + let repeat_code = encode(&[LOAD, ADD, LOAD, sum, mov21, out, END]); + let store_once_code = encode(&[LOAD, ADD, store, sum, mov21, out, END]); + let store_repeat_code = encode(&[LOAD, ADD, store, LOAD, sum, mov21, out, END]); let vs = VsInterface::default(); let vs_once = count_loads(&translate_vertex(&once_code, opts, &vs).expect("VS once").dxil); From 87edfef18c1312d63e28db7ecad8d9f8d99c28c4 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:05:05 +0100 Subject: [PATCH 163/175] Shaders: test split-program preparation with and without kept wholes #3442 (main) made startup preparation build only a split program's ABI whole when its driver blob is kept on disk, and tested it with a scratch cache_dir on an NVIDIA adapter, where the driver-blob cache is on. amd-dev's 0481ad6c gates the same function on whole_form_kept() (XCL_PSO_DISK_CACHE or XCL_PSO_LIBRARY), both off on AMD by default: there the title never takes the ABI whole, so preparation builds the pieces, and the chain-root wholes only for programs dispatched indirectly. The merge kept both, correctly: #3442's path when wholes are kept, amd-dev's otherwise. But #3442's test never set up the kept condition, so on AMD it took amd-dev's path and found the chain blobs. The test now forces the pipeline library on (its existing test hook; the driver-blob cache has none) for #3442's cases, and adds amd-dev's case without kept wholes, asserting the blobs it builds per indirect prewarm. That case is skipped where the driver-blob cache is on. No production code changes. --- crates/xcl/src/shaders.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 064da87c0d..75f7d35195 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -2622,7 +2622,8 @@ mod pipeline_cap_tests { } /// Startup preparation (`prepare_compiled_compute`) of a split program builds its whole once, - /// under the ABI root, and no chain; with the whole over the cap it builds the pieces instead. + /// under the ABI root, and no chain, where whole forms are kept; with the whole over the cap it + /// builds the pieces instead. Without kept whole forms it builds the pieces (`split_builds`). #[test] fn startup_preparation_builds_a_split_programs_whole_and_no_chain() { use super::{Pipelines, recomp}; @@ -2686,6 +2687,11 @@ mod pipeline_cap_tests { Scratch(dir) }; + // kept whole forms, as with `XCL_PSO_LIBRARY=1` (the driver-blob files have no test hook): on + // AMD both are off by default, and preparation would then build for that case (below) + let library_on = crate::shaders::pipeline_library::force_on_for_test(); + assert!(super::whole_form_kept()); + // the whole is built and kept: nothing else, an indirect dispatch included let kept = scratch("kept"); pipelines.cache_dir = Some(kept.0.clone()); @@ -2704,6 +2710,28 @@ mod pipeline_cap_tests { let mut want = vec![driver_cache::name_for(&piece0, 0, true), driver_cache::name_for(&piece1, 0, true)]; want.sort(); assert_eq!(blobs(&capped.0), want, "the pieces only"); + drop(library_on); + + // no kept whole forms (AMD by default): the title runs the pieces and never takes the ABI + // whole, so that is not built; the chain-root wholes only for a program dispatched indirectly + if super::whole_form_kept() { + recomp::runner::skip_test("whole forms are kept on this adapter (XCL_PSO_DISK_CACHE): no case without them"); + return; + } + pipelines.max_dxil = 0; + let chain_name = |dxil: &[u8], root| driver_cache::name_for_chain_root_node(dxil, 0, root, &[], 0); + let (direct, indirect) = (driver_cache::ChainRoot::DirectConstants, driver_cache::ChainRoot::IndirectCbv); + for prewarm_indirect in [false, true] { + let unkept = scratch(if prewarm_indirect { "unkept-indirect" } else { "unkept" }); + pipelines.cache_dir = Some(unkept.0.clone()); + pipelines.prepare_compiled_compute(&compiled, prewarm_indirect).expect("prepared without kept wholes"); + let mut want = vec![chain_name(&piece0, direct), chain_name(&piece1, direct)]; + if prewarm_indirect { + want.extend([chain_name(&whole, direct), chain_name(&piece0, indirect), chain_name(&piece1, indirect), chain_name(&whole, indirect)]); + } + want.sort(); + assert_eq!(blobs(&unkept.0), want, "no ABI whole (indirect: {prewarm_indirect})"); + } } } From 82da371f9ef3b2e008af15f053d568da4e1514e4 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:22:51 +0100 Subject: [PATCH 164/175] Shaders: take the measured commit from kernelx's process counter process_memory() read PROCESS_MEMORY_COUNTERS_EX::PrivateUsage, which Wine leaves 0, so under Wine every --measure-pso commit figure was 0 and the_peak_memory_counts_what_was_given_back failed ("peak 0 MB, before 0 MB"). kernelx::process_private_bytes() already falls back to PagefileUsage when PrivateUsage is 0 (the same number on Windows), so use it here instead of a second copy of the query; any later fix to that fallback then covers the measurement too. --- crates/xcl/src/hle/kernelx.rs | 2 +- crates/xcl/src/shaders.rs | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index bcb48a3823..016853b69f 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1783,7 +1783,7 @@ pub struct TitleMemoryStatusT { pub title_page_table_used: u64, } -fn process_private_bytes() -> u64 { +pub(crate) fn process_private_bytes() -> u64 { use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; unsafe { let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 75f7d35195..07358d3858 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1649,14 +1649,15 @@ fn translated_entry(bytes: &[u8]) -> Result<(Vec, Vec (u64, u64) { - use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; unsafe { - let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + let mut c: PROCESS_MEMORY_COUNTERS = std::mem::zeroed(); c.cb = std::mem::size_of_val(&c) as u32; - K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); - (c.PrivateUsage as u64, c.WorkingSetSize as u64) + K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c, c.cb); + (crate::hle::kernelx::process_private_bytes(), c.WorkingSetSize as u64) } } From 41eaf197914d7f8571e2799f37f30a9645161836 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:25:07 +0100 Subject: [PATCH 165/175] Tests: adopt the list in the released-allocator dispatch chain test a_released_allocator_keeps_its_chains_until_the_gpu_is_done records a split ExecuteIndirect on a list it never adopted. execute_indirect binds the slicer through bind_pipeline_exact, whose slot!(list, "SetPipelineState") looks the list's vtable up among XCL's classes, so the test panicked with "adopted class" whenever no earlier test had filled that call site's slot cache. The panic happened under the CLASSES lock and poisoned it, which then failed failed_binding_keeps_indirect_commands_until_allocator_reset in the same process. Set the list up the way the sibling test does: adopt it, register it with list_x, and close it through the PC slot. Nothing changes in non-test code. --- crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 2f5170b9f5..c22a900d5a 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -895,13 +895,18 @@ mod tests { super::super::adopt(alloc.as_raw(), super::super::Kind::CommandAllocator); } let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + // (a list as XCL has a title's: the slicer is bound through the PC call) + super::super::adopt(list.as_raw(), Kind::CommandList); + super::super::super::list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); alloc_pool::created_on(raw_list, allocator, ty.0); let args = pso::chain_commands_buffer(&dev, 1).unwrap(); // (a failed binding records no ExecuteIndirect, but keeps the recording as a run would) let _ = execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into())); assert!(RECORDINGS.lock().unwrap().contains_key(&allocator)); - list.Close().unwrap(); + type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT; + let close: Close = std::mem::transmute(super::super::orig_fn(list.as_raw(), 9)); + assert!(close(list.as_raw()) >= 0); // the queue runs the list only once `gate` is signalled let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); queue.Wait(&gate, 1).unwrap(); From 7ce7e80394c5fa0e180ba9950ed3aa985f243b1e Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:25:22 +0100 Subject: [PATCH 166/175] Tests: expect the lazy middle tile to keep the CPU's bytes on copy back private_physical_pages_reach_the_gpu_on_mapping came to amd-dev with 87e900b8 (the NVIDIA adaptation of #1916, #3123) unrun. Unlike #1916's fixture it sets XCL_SPARSE_LAZY=1, so the untouched middle page is committed as a LAZY tile with no video memory. A copy back skips such a tile (nothing to copy, the window reads zeros there), which leaves the fixture's own 0xdd CPU overwrite in place, and the zero check failed every time. Check what lazy commits promise instead: the middle tile has no video memory and the CPU's bytes stay. Without lazy commits the old zero check still applies. The written pages are checked as before. This matches the diagnosis on #3123 (thehollowedone, vasanex). --- crates/xcl/src/hle/d3d12x/sparse.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 5dfed92432..b67f2bfa29 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -9457,7 +9457,17 @@ mod tests { assert_eq!(RB_PENDING.load(Ordering::Acquire), 0, "copy back did not finish"); let result = std::slice::from_raw_parts(home as *const u8, n * TILE); assert_eq!(&result[..TILE], &first); - assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0)); + // The untouched middle page got no upload. With lazy commits its tile has no video + // memory (the window reads zeros there), so there is nothing to copy back and the + // CPU's own bytes stay. + let mid = home + TILE; + if lazy_commits() { + let pool = STATE.lock().unwrap().as_ref().and_then(|s| s.mapped.get(&mid).map(|e| e.pool)); + assert_eq!(pool, Some(LAZY), "the untouched page got video memory"); + assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0xdd)); + } else { + assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0)); + } assert_eq!(&result[2 * TILE..], &last); assert_eq!(FreeTitlePhysicalPages(null, n, pages.as_mut_ptr()), 1); } From fae6f90ec4b51e63548632fc4cfd29dce8e2e7cc Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:27:12 +0100 Subject: [PATCH 167/175] kernelx: skip alias tests where a fresh view's first write does not fault Four alias tests rely on the first write through a view of a page never used faulting into `lazy`, which commits the page and sets its commit bit; the guards, reads by number and moves all key off that bit. Under Wine 11.21 that write does not fault: it lands in the section, `VirtualQuery` still reports the view as MEM_RESERVE, the lazy mark stays, and the bit is never set. So the views are never guarded and a read by number or a move sees zeros. The code is right on Windows, where these tests pass; the building blocks (sections, guards, lazy) pass under Wine too. Probe the behaviour itself rather than sniffing for Wine, and skip with the reason when it does not hold. --- crates/xcl/src/hle/kernelx/alias.rs | 39 +++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs index e37319c0d8..1e67370ded 100644 --- a/crates/xcl/src/hle/kernelx/alias.rs +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -528,9 +528,39 @@ mod tests { out } + /// Whether the first write through a view of a page never used faults into `lazy`, which + /// commits the page and sets its bit – what these tests rely on. Wine (11.21) does not + /// fault there: the write lands in the section and `VirtualQuery` still says `MEM_RESERVE`, + /// so the page's bit stays clear and its views are never guarded. + fn first_write_commits() -> bool { + let p = pages(1); + let s = reserve_space(PAGE).unwrap(); + unsafe { + assert!(map(s, &p)); + write64(s, 1); + let ok = committed(p[0]); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + dirty(); + ok + } + } + + /// Skip a test that needs `first_write_commits` where it does not hold. + fn needs_first_write_commit() -> bool { + if first_write_commits() { + return true; + } + crate::gpu::recomp::runner::skip_test("a write to an uncommitted section view does not fault (Wine)"); + false + } + #[test] fn a_page_mapped_into_two_spaces_is_one_page_and_writes_reach_both() { let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if !needs_first_write_commit() { + return; + } let p = pages(4); let cpu = reserve_space(8 * PAGE).unwrap(); let gpu = reserve_space(8 * PAGE).unwrap(); @@ -574,6 +604,9 @@ mod tests { #[test] fn pages_read_and_written_by_number_are_the_pages_the_title_sees() { let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if !needs_first_write_commit() { + return; + } let p = pages(3); let s = reserve_space(3 * PAGE).unwrap(); unsafe { @@ -602,6 +635,9 @@ mod tests { #[test] fn a_page_moved_outside_the_spaces_goes_and_comes_back_with_its_bytes() { let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if !needs_first_write_commit() { + return; + } let p = pages(1); let s = reserve_space(PAGE).unwrap(); // address space outside the spaces (as a title's own placeholder region would be) @@ -627,6 +663,9 @@ mod tests { #[test] fn the_queue_page_mapping_method_shows_the_pool_pages_physical_page_in_the_gpu_view() { let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + if !needs_first_write_commit() { + return; + } let p = pages(2); let pool = reserve_space(4 * PAGE).unwrap(); let cpu = reserve_space(4 * PAGE).unwrap(); From c909fb83d8b07a845e49ded42182d84bd881541f Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 02:24:25 +0100 Subject: [PATCH 168/175] D3D12.X: let split chains' pieces read what the slicer wrote The slicer moved its commands to INDIRECT_ARGUMENT | VERTEX_AND_CONSTANT_BUFFER. vkd3d-proton only counts a transition to exactly INDIRECT_ARGUMENT as a write to indirect arguments; without one it hoists an ExecuteIndirect's preprocessing to the start of its command buffer, or of the whole submit. So the pieces' ExecuteIndirects read the commands before the slicer wrote them: zeros, or the groups and slab origins of an earlier split dispatch recorded with the same storage, run with this program's pieces. On RADV that is a TCP page fault and a gfx ring timeout where the world finishes loading, the removal seen at about 170 s on main and on the guard branch alike. The commands now go to INDIRECT_ARGUMENT alone (the root-constant chain ABI needs no constant buffer state). The split-chain test now also counts the groups the pieces run: 0 before this, 6, 0 and 2 now. (cherry picked from commit 373e22e122523403027f05ccba7ad27506d3dec5) Assisted-by: Codex (gpt-6.2-sol) --- crates/xcl/src/gpu/recomp/pso.rs | 9 +- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 91 ++++++++++++++++++- 2 files changed, 94 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index aaa544328b..e429c5e4b9 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -2055,11 +2055,16 @@ pub(crate) unsafe fn record_indirect_slicer( 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); + // INDIRECT_ARGUMENT alone: vkd3d-proton hoists an ExecuteIndirect's preprocessing to the start + // of its command buffer (or of the submit) unless the list transitions something to exactly + // that state before it, so with any other bit set the pieces read the commands before this + // pass wrote them: zeros or a dispatch before's groups and slab origins (RADV: a TCP page + // fault where a split chain's indirect dispatch runs) 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 | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER }) } }]); + StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT }) } }]); Ok(()) } @@ -2069,7 +2074,7 @@ pub(crate) unsafe fn restore_indirect_commands(list: &ID3D12GraphicsCommandList, list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(commands), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, + StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS }) } }]); } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index c22a900d5a..fc0a225230 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -765,9 +765,11 @@ mod tests { assert_eq!(calls, 2, "the successful retry is retained"); } + const EMPTY_PIECE: &str = "[numthreads(1,1,1)] void main() {}"; + /// A split program whose whole form is ready, under its first piece's address. `None`: no GPU /// or no DXC. - unsafe fn ready_indirect_chain() -> Option<(ID3D12Device, usize)> { + unsafe fn ready_indirect_chain(source: &str) -> Option<(ID3D12Device, usize)> { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; unsafe extern "system" fn never(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } let mut dev = None; @@ -776,7 +778,7 @@ mod tests { return None; } let dev: ID3D12Device = dev.unwrap(); - let Ok(dxil) = crate::gpu::recomp::dxc::compile("[numthreads(1,1,1)] void main() {}", "main", "cs_6_0", &[]) else { + let Ok(dxil) = crate::gpu::recomp::dxc::compile(source, "main", "cs_6_0", &[]) else { crate::gpu::recomp::runner::skip_test("no DXC"); return None; }; @@ -797,7 +799,7 @@ mod tests { #[test] fn failed_binding_keeps_indirect_commands_until_allocator_reset() { unsafe { - let Some((dev, key)) = ready_indirect_chain() else { return }; + let Some((dev, key)) = ready_indirect_chain(EMPTY_PIECE) else { return }; let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); @@ -887,7 +889,7 @@ mod tests { fn a_released_allocator_keeps_its_chains_until_the_gpu_is_done() { use super::super::super::alloc_pool; unsafe { - let Some((dev, key)) = ready_indirect_chain() else { return }; + let Some((dev, key)) = ready_indirect_chain(EMPTY_PIECE) else { return }; let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); @@ -936,6 +938,87 @@ mod tests { } } + /// The pieces read the slicer's commands from this dispatch. On vkd3d-proton they could + /// read the commands before the slicer ran (`pso::record_indirect_slicer`). + #[test] + fn a_split_indirect_dispatch_runs_the_groups_the_slicer_wrote() { + use super::super::super::{alloc_pool, list_x}; + let source = "RWByteAddressBuffer c : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { c.InterlockedAdd(0, 1u); }"; + let cases = [([3, 2, 1], 6), ([1, 1, 0], 0), ([2, 1, 1], 2)]; + unsafe { + let Some((dev, key)) = ready_indirect_chain(source) else { return }; + let rs = CHAINS.lock().unwrap().get(&key).unwrap().builder.signature.clone(); + // buffers the CPU and the GPU see: the title's arguments, the slicer's commands, the + // groups run + let cpu_buffer = |width: u64| { + 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: width, 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 mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let r = r.unwrap(); + let mut p = std::ptr::null_mut(); + r.Map(0, None, Some(&mut p)).unwrap(); + (r, p as *mut u32) + }; + let rounds = indirect_rounds(); + let command_bytes = pso::chain_tail_offset(rounds) + 12; + let ((args, args_at), (sliced, sliced_at), (ran, ran_at)) = (cpu_buffer(256), cpu_buffer(command_bytes), cpu_buffer(256)); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let transition = |r: &ID3D12Resource, before, after| 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(r), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, StateAfter: after }) } }; + for (want, runs) in cases { + for (i, w) in want.iter().enumerate() { + *args_at.add(i) = *w; + } + *ran_at = 0; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + // (a list as XCL has a title's) + super::super::adopt(list.as_raw(), Kind::CommandList); + list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); + let (raw, allocator) = (list.as_raw(), alloc.as_raw() as usize); + alloc_pool::created_on(raw as usize, allocator, ty.0); + let bind = |root: usize| { + assert_eq!(root, rs.as_raw() as usize); + list.SetComputeRootSignature(&rs); + list.SetComputeRootUnorderedAccessView(0, ran.GetGPUVirtualAddress()); + Ok(()) + }; + let chained = execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), bind); + assert_eq!(chained, Ok(Indirect::Ran), "{want:x?}"); + // what the slicer wrote, for the CPU + let commands = RECORDINGS.lock().unwrap().get(&allocator).unwrap().last().unwrap()._indirect_commands.clone().unwrap(); + list.ResourceBarrier(&[transition(&commands.buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&sliced, 0, &commands.buffer, 0, command_bytes); + list.ResourceBarrier(&[transition(&commands.buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT; + let close: Close = std::mem::transmute(super::super::orig_fn(raw, 9)); + assert!(close(raw) >= 0, "{want:x?}: the recorded chain closes"); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 10_000).unwrap(); + // each round's Dispatch arguments, then the whole form's + let groups = |at: u64| (0..3).map(|i| u64::from(std::ptr::read_volatile(sliced_at.add(at as usize / 4 + i)))).product::(); + let total: u64 = (0..rounds).map(|r| groups(pso::chain_tail_offset(r) + pso::CHAIN_DISPATCH_AT)).sum::() + + groups(pso::chain_tail_offset(rounds)); + assert_eq!(total, runs, "{want:x?}: groups sliced"); + // ready_indirect_chain gives the chain two counting pieces. + assert_eq!(u64::from(std::ptr::read_volatile(ran_at)), 2 * runs, "{want:x?}: groups the pieces ran"); + allocator_reset(allocator); + list_reset(raw as usize); + alloc_pool::forget_list(raw as usize); + } + forget(key); + } + } + #[test] fn remap_compile_oom_retries_but_deterministic_failure_is_final() { let at = std::time::Instant::now(); From 1becd37cf17004586960729920fa320d9bf64bec Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 01:43:57 +0100 Subject: [PATCH 169/175] D3D12.X: compile the indirect guard with DXC Wine's D3DCompile cannot compile the guard's Load3 on a raw UAV. Cache the DXC shader before taking GUARD and fall back to D3DCompile if the device rejects DXIL. Keep the existing DRED label and the inline root-SRV path, which now gets checked counts under Wine. Port the guard's DXC tests. Run a split chain against the guard's root SRV in the slicer test and assert that out-of-range counts produce zero groups and that the pieces run the valid groups. (adapted from 9181dd37359e01e7feef29dd6a25778965199dc0) Assisted-by: Codex (gpt-6.2-sol) --- crates/xcl/src/hle/d3d12x/indirect_guard.rs | 75 +++++++++++++++---- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 25 ++++++- 2 files changed, 81 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/indirect_guard.rs b/crates/xcl/src/hle/d3d12x/indirect_guard.rs index 47c4e74e07..d0c81d8f8b 100644 --- a/crates/xcl/src/hle/d3d12x/indirect_guard.rs +++ b/crates/xcl/src/hle/d3d12x/indirect_guard.rs @@ -199,11 +199,13 @@ unsafe fn guard_of(list: &ID3D12GraphicsCommandList) -> Option> { let mut dev: Option = None; list.GetDevice(&mut dev).ok()?; let dev = dev?; + // (before `GUARD`: DXC's pool may make the first ExecuteIndirect wait, `counts` must not) + let dxil = dxil(); let mut g = GUARD.lock().unwrap(); if let Some(g) = g.as_ref().filter(|g| g.dev == dev.as_raw() as usize) { return Some(g.clone()); } - match super::title_textures::own_work(|| make(&dev)) { + match super::title_textures::own_work(|| make(&dev, dxil)) { Ok(n) => { let n = Arc::new(n); *g = Some(n.clone()); @@ -217,11 +219,16 @@ unsafe fn guard_of(list: &ID3D12GraphicsCommandList) -> Option> { } } -unsafe fn make(dev: &ID3D12Device) -> Result { - let cs = real::compile(&program(), "cs_5_0"); - if cs.is_empty() { - return Err("its program does not compile".into()); - } +/// The guard's program as DXIL, compiled once for every device. DXC, not D3DCompile: Wine's +/// d3dcompiler (vkd3d-shader) has no Load3 on a RWByteAddressBuffer, so under Wine the guard +/// never ran and garbage counts reached the GPU (RADV: a ring timeout in a DISPATCH_INDIRECT of a +/// small program). +fn dxil() -> &'static Result, String> { + static DXIL: std::sync::OnceLock, String>> = std::sync::OnceLock::new(); + DXIL.get_or_init(|| crate::gpu::recomp::dxc::compile(&program(), "main", "cs_6_0", &[])) +} + +unsafe fn make(dev: &ID3D12Device, dxil: &Result, String>) -> Result { let root = |ty, anonymous| D3D12_ROOT_PARAMETER { ParameterType: ty, Anonymous: anonymous, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL }; let uav = |k| root(D3D12_ROOT_PARAMETER_TYPE_UAV, D3D12_ROOT_PARAMETER_0 { Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: k, RegisterSpace: 0 } }); let params = [ @@ -236,10 +243,22 @@ unsafe fn make(dev: &ID3D12Device) -> Result { D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).map_err(|e| format!("root signature: {e}"))?; let blob = blob.ok_or("root signature")?; let rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())).map_err(|e| format!("CreateRootSignature: {e}"))?; - let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }; - let pso: ID3D12PipelineState = dev - .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }) - .map_err(|e| format!("CreateComputePipelineState: {e}"))?; + let pso_of = |cs: &[u8]| -> Result { + let code = D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }; + dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: transmute_copy(&rs), CS: code, ..Default::default() }) + .map_err(|e| format!("CreateComputePipelineState: {e}")) + }; + // D3DCompile's when DXC failed, or the device refused its DXIL (unsigned: no dxil.dll) + let pso = match dxil.as_ref().map_err(String::clone).and_then(|cs| pso_of(cs)) { + Ok(pso) => pso, + Err(e) => { + let cs = real::compile(&program(), "cs_5_0"); + if cs.is_empty() { + return Err(format!("its program does not compile ({e})")); + } + pso_of(&cs).map_err(|e5| format!("{e5} (DXC: {e})"))? + } + }; let _ = pso.SetName(&windows::core::HSTRING::from("xcl indirect_guard")); super::dred::label_text(pso.as_raw() as usize, || "xcl indirect_guard".to_string()); let buffer = |heap: D3D12_HEAP_PROPERTIES, width: u64| -> Result { @@ -459,7 +478,7 @@ fn report(g: &Guard) { } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::super::list_x; use super::*; use crate::gpu::{fence, recomp::runner::skip_test}; @@ -468,7 +487,7 @@ mod tests { type Close = unsafe extern "system" fn(*mut c_void) -> windows::core::HRESULT; /// the guard (and its count of what was out of range) is the device's: one test at a time - static ONE: Mutex<()> = Mutex::new(()); + pub(in crate::hle::d3d12x) static ONE: Mutex<()> = Mutex::new(()); unsafe fn device() -> Option { let mut dev: Option = None; @@ -541,6 +560,18 @@ mod tests { assert_eq!(counts_va_in(0x100, in_one_window, va_of), None, "not in a window"); } + /// The guard's program compiles with DXC (`make`): Wine's D3DCompile refuses it, which left + /// the guard off in every run under Wine. + #[test] + fn the_guards_program_compiles_with_dxc() { + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let dxil = crate::gpu::recomp::dxc::compile(&program(), "main", "cs_6_0", &[]).unwrap(); + assert!(!dxil.is_empty()); + } + #[test] fn a_counter_is_logged_at_its_first_values_and_at_each_doubling_however_it_jumps() { assert!(logged_again(0, 1) && logged_again(0, 7) && logged_again(3, 5)); @@ -574,7 +605,12 @@ void main() { c.InterlockedAdd(0, 1u); } unsafe { let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); let Some(dev) = device() else { return }; - let cs = real::compile(src, "cs_5_0"); + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + // (DXC: Wine's D3DCompile has no InterlockedAdd on a RWByteAddressBuffer either) + let cs = crate::gpu::recomp::dxc::compile(src, "main", "cs_6_0", &[]).unwrap(); assert!(!cs.is_empty()); let param = D3D12_ROOT_PARAMETER { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, @@ -605,11 +641,13 @@ void main() { c.InterlockedAdd(0, 1u); } let raw = list.as_raw(); type Ei = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let ei: Ei = std::mem::transmute(real::orig_fn(raw, 59)); - let before = GUARD.lock().unwrap().as_ref().map_or(0, |g| bad_so_far(g)); if let Some(g) = GUARD.lock().unwrap().as_ref() { g.next.store(0, Ordering::Relaxed); } let checked = check(raw, 0, s, 1, a, off, 0).expect("checked"); + // (after `check`: the guard is the device's, and the test before may have left + // another device's; nothing is counted until the list runs) + let before = bad_so_far(&checked.guard); assert!(k == 0 || checked.slot == 0); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); @@ -659,7 +697,14 @@ void main() { c.InterlockedAdd(0, 1u); } let (_alloc, list) = title_list(&dev, ty); let raw = list.as_raw(); let sig = if is_indexed { &indexed } else { &plain }; - let checked = check(raw, 0, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0).expect("checked"); + let Some(checked) = check(raw, 0, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0) else { + // (no guard without a compiler for its program: under Wine that takes DXC) + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + panic!("checked"); + }; // (the arguments, copied out instead of drawn) checked.run(raw, |b, o| { list_x::transition(raw, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index fc0a225230..454689dcbe 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -938,14 +938,17 @@ mod tests { } } + /// The slicer reads the guard's checked counts through its root SRV. Out-of-range counts + /// become zero before the slicer can clamp them into a very large dispatch. /// The pieces read the slicer's commands from this dispatch. On vkd3d-proton they could /// read the commands before the slicer ran (`pso::record_indirect_slicer`). #[test] - fn a_split_indirect_dispatch_runs_the_groups_the_slicer_wrote() { - use super::super::super::{alloc_pool, list_x}; + fn a_split_indirect_dispatch_slices_the_counts_the_guard_let_through() { + use super::super::super::{alloc_pool, indirect_guard, list_x}; let source = "RWByteAddressBuffer c : register(u0);\n[numthreads(1, 1, 1)]\nvoid main() { c.InterlockedAdd(0, 1u); }"; - let cases = [([3, 2, 1], 6), ([1, 1, 0], 0), ([2, 1, 1], 2)]; + let cases = [([3, 2, 1], 6), ([1, 1, 0x1_0000], 0), ([2, 1, 1], 2)]; unsafe { + let _one = indirect_guard::tests::ONE.lock().unwrap_or_else(|e| e.into_inner()); let Some((dev, key)) = ready_indirect_chain(source) else { return }; let rs = CHAINS.lock().unwrap().get(&key).unwrap().builder.signature.clone(); // buffers the CPU and the GPU see: the title's arguments, the slicer's commands, the @@ -966,6 +969,11 @@ mod tests { let rounds = indirect_rounds(); let command_bytes = pso::chain_tail_offset(rounds) + 12; let ((args, args_at), (sliced, sliced_at), (ran, ran_at)) = (cpu_buffer(256), cpu_buffer(command_bytes), cpu_buffer(256)); + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let mut sig: Option = None; + dev.CreateCommandSignature(&D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }, None, &mut sig).unwrap(); + let sig = sig.unwrap(); + indirect_guard::note_signature(sig.as_raw() as usize, &[D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0]); let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); let transition = |r: &ID3D12Resource, before, after| D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, @@ -984,13 +992,21 @@ mod tests { list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, ty); let (raw, allocator) = (list.as_raw(), alloc.as_raw() as usize); alloc_pool::created_on(raw as usize, allocator, ty.0); + let checked = indirect_guard::check(raw, key, sig.as_raw() as usize, 1, args.as_raw() as usize, 0, 0) + .unwrap_or_else(|| panic!("{want:x?}: checked")); + let (out, _) = checked.arguments(); let bind = |root: usize| { assert_eq!(root, rs.as_raw() as usize); list.SetComputeRootSignature(&rs); list.SetComputeRootUnorderedAccessView(0, ran.GetGPUVirtualAddress()); Ok(()) }; - let chained = execute_indirect(&list, key, key, allocator, args.GetGPUVirtualAddress(), bind); + // As in bind::execute_indirect_snapshot, the slicer reads the guard's output as a root SRV. + let (uav, srv) = (D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list_x::transition(raw, out, uav, srv); + let chained = execute_indirect(&list, key, key, allocator, checked.gpu_address(), bind); + list_x::transition(raw, out, srv, uav); + checked.read(raw); assert_eq!(chained, Ok(Indirect::Ran), "{want:x?}"); // what the slicer wrote, for the CPU let commands = RECORDINGS.lock().unwrap().get(&allocator).unwrap().last().unwrap()._indirect_commands.clone().unwrap(); @@ -1015,6 +1031,7 @@ mod tests { list_reset(raw as usize); alloc_pool::forget_list(raw as usize); } + indirect_guard::note_signature(sig.as_raw() as usize, &[]); forget(key); } } From a3b6cf97c5517a2ca499b679768928eb7ff5dd15 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 10:29:59 +0100 Subject: [PATCH 170/175] D3D12.X: cover tile mappings whose Signal failed vram's mapping queue raised its value and then signalled it, ignoring the result. When that Signal failed, the value was one no Signal would reach: every queue's next submit waited for it (before_execute) and a retired texture's NULL unmap counted as done although nothing marked it. The value now moves only when the Signal was queued. A mapping or unmapping whose Signal failed is marked, and gets a later Signal before anything counts on it: before_execute queues one and has the title's queue wait for it, and a retired texture stays out of the pool until one completes. When none can be queued either, before_execute says so, and the submission stops with that cause (MappingUnmarked) instead of going out with mappings nothing covers. Tests: a failed Signal leaves the value a Signal reached; with the mapping queue held behind a test fence, a bind, a held unmap released inside before_execute and a retired texture's unmap whose Signals fail each get a later mark, and the work waits for it or does not go. (cherry picked from commit 69700342ee0b67429a4dbdb771cffa5d708bfde6) On amd-dev, flush recycled zero-fill tiles before marking. A failed zero-fill Signal also leaves its ring slot unmarked. Keep the allocator and alias buffers in use until a later Signal covers the copy. Assisted-by: Codex (gpt-6.2-sol) --- crates/xcl/src/hle/d3d12x/list_x.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 1 + crates/xcl/src/hle/d3d12x/sparse.rs | 3 + crates/xcl/src/hle/d3d12x/title_textures.rs | 12 +- crates/xcl/src/hle/d3d12x/vram.rs | 321 ++++++++++++++++++-- 5 files changed, 313 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 89ca936b6d..7af98d348b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3747,6 +3747,7 @@ unsafe fn mapped_after_wait(queue: *mut c_void) { super::sparse::PreparationOutcome::Ready => {} super::sparse::PreparationOutcome::RetryRequired => stop_for_unresolved_wait("sparse upload preparation after a wait inside a submit still failed after bounded retries"), super::sparse::PreparationOutcome::ExecutedUntracked => stop_for_unresolved_wait("a sparse upload after a wait inside a submit executed without a retirement signal"), + super::sparse::PreparationOutcome::MappingUnmarked => stop_for_unresolved_wait("a texture page mapping after a wait inside a submit has no Signal of the mapping queue"), } } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index b4d2f4c022..34f0a68dfb 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -13289,6 +13289,7 @@ pub(super) unsafe fn prepare_title_submission(queue: *mut c_void, lists: &[*mut let reason = match outcome { PreparationOutcome::RetryRequired => "sparse upload preparation still failed after bounded retries", PreparationOutcome::ExecutedUntracked => "a sparse upload executed without a retirement signal", + PreparationOutcome::MappingUnmarked => "a texture page mapping has no Signal of the mapping queue (its own and a retry failed)", PreparationOutcome::Ready => unreachable!(), }; let message = format!("{reason} – the title is stopped before its GPU submission"); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b67f2bfa29..5f9b2bacdd 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -2681,6 +2681,9 @@ pub(super) enum PreparationOutcome { Ready, RetryRequired, ExecutedUntracked, + /// a tile mapping is queued that no Signal of the mapping queue covers: its own Signal failed + /// and so did a retry (`vram::before_execute`), so nothing may run that reads it + MappingUnmarked, } impl From for PreparationOutcome { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 9b1f2ec4c1..4890ed1871 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2733,7 +2733,9 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut if outcome != super::sparse::PreparationOutcome::Ready { return outcome; } - super::vram::before_execute(q); + if !super::vram::before_execute(q) { + return super::sparse::PreparationOutcome::MappingUnmarked; + } } // a write where a page the queue's page mappings show is kept is a write to the GPU-view pages // that show it: the textures read through their pages find it by their own range (sparse had @@ -3408,7 +3410,9 @@ unsafe fn submit_on(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[tex // another thread after `refresh_once`'s wait, or its levels mapped just now by // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault // on NVIDIA (`DmaPageFaultWrite`). - super::vram::before_execute(queue); + if !super::vram::before_execute(queue) { + return Err("a texture page mapping has no Signal of the mapping queue yet".into()); + } let key = queue.as_raw() as usize; let state = queue_upload_state(key); let mut slot = state.lock().unwrap(); @@ -3827,7 +3831,9 @@ pub unsafe fn probe_gpu_content(res: usize) { dev.GetCopyableFootprints(&rd, 0, levels as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); let result = own_work(|| -> Result>, String> { let queue = upload_queue(dev, device)?; - super::vram::before_execute(&queue); + if !super::vram::before_execute(&queue) { + return Err("a texture page mapping has no Signal of the mapping queue yet".into()); + } let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(|e| e.to_string())?; let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(|e| e.to_string())?; let mut rb: Option = None; diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 97eee0750c..0a20dff6b4 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -809,6 +809,11 @@ impl ReservedPool { } } + #[cfg(test)] + fn count(&self, key: &ReservedKey) -> usize { + self.by_key.get(key).map_or(0, Vec::len) + } + fn take(&mut self, key: &ReservedKey) -> Option<(usize, u32)> { let bucket = self.by_key.get_mut(key)?; let (raw, total, _gen) = bucket.pop()?; @@ -852,6 +857,9 @@ impl ReservedPool { } } +/// A `PendingRecycle::mark` no Signal reaches yet (`Pages::mark_pending_recycles`). +const UNMARKED: u64 = u64::MAX; + /// Owns a retired reserved texture until the tile-mapping queue passes its last update mark. struct PendingRecycle { key: ReservedKey, @@ -901,6 +909,7 @@ pub(super) unsafe fn drain_recycled() { { let mut g = PAGES.lock().unwrap(); for pages in g.values_mut().flatten() { + pages.mark_pending_recycles(); let before = pages.pending_recycles.len(); evicted.extend(promote_pending( &mut pages.reserved_pool, @@ -954,11 +963,13 @@ pub(super) unsafe fn recycle_ready(resource: usize) -> bool { pages.unmap(res, info.total); } } + // (its unmap's Signal failed and so did one now: kept out of the pool until one is queued) + let mark = pages.mark().unwrap_or(UNMARKED); pages.pending_recycles.push_back(PendingRecycle { key: info.key, raw: resource, total: info.total, - mark: pages.value, + mark, }); PENDING_RECYCLES.fetch_add(1, std::sync::atomic::Ordering::Release); } @@ -1802,7 +1813,8 @@ const ZERO_SLOTS: usize = 4; struct ZeroSlot { alloc: ID3D12CommandAllocator, list: ID3D12GraphicsCommandList, - fence_val: u64, + // None while an executed zero-fill is waiting for a successful mapping-queue Signal. + fence_val: Option, kept_bufs: Vec, } @@ -1845,7 +1857,7 @@ impl ZeroRing { Ok((a, l)) }) .ok()?; - slots.push(ZeroSlot { alloc, list, fence_val: 0, kept_bufs: Vec::new() }); + slots.push(ZeroSlot { alloc, list, fence_val: Some(0), kept_bufs: Vec::new() }); } Some(ZeroRing { zero_src, slots }) } @@ -1907,6 +1919,8 @@ struct Pages { held_unmaps: Vec, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// a mapping was queued whose Signal failed: `value` does not cover it (`mark`) + unmarked: bool, /// idle reserved sampled textures kept for reuse by `(desc, state)` (#1268) reserved_pool: ReservedPool, /// retired reserved textures held until the tile-mapping queue passes their unmap fence mark @@ -2062,6 +2076,7 @@ impl Pages { unmap_fences: std::collections::HashMap::new(), held_unmaps: Vec::new(), reservable_cache: std::collections::HashMap::new(), + unmarked: false, reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), pending_recycles: std::collections::VecDeque::new(), scratch_heaps: Vec::new(), @@ -2114,11 +2129,15 @@ impl Pages { // (XCL's own fence: not through the title's GetCompletedValue hook) let done = super::real::fence_completed(&self.fence); let ring = self.zero_ring.as_mut().unwrap(); - let slot_idx = match ring.slots.iter().position(|s| s.fence_val <= done) { + let slot_idx = match ring.slots.iter().position(|s| s.fence_val.is_some_and(|v| v <= done)) { Some(i) => i, None => { - let (oldest_idx, oldest_val) = - ring.slots.iter().enumerate().min_by_key(|(_, s)| s.fence_val).map(|(i, s)| (i, s.fence_val)).unwrap(); + let Some((oldest_idx, oldest_val)) = ring.slots.iter().enumerate() + .filter_map(|(i, slot)| slot.fence_val.map(|value| (i, value))) + .min_by_key(|&(_, value)| value) else { + crate::xlog_warn!("D3D12.X: zero-fill of recycled texture pages skipped: no ring slot has a fence mark"); + return; + }; // (the mapping queue waits for nothing of the title's: its work gets done) if let Err(e) = crate::gpu::fence::wait(&self.fence, oldest_val, dev, None, 5_000) { crate::xlog_warn!("D3D12.X: zero-fill of recycled texture pages skipped: its ring slot is still on the GPU ({e})"); @@ -2170,9 +2189,9 @@ impl Pages { }) .is_ok(); if ok { - self.value += 1; - let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); - slot.fence_val = self.value; + slot.fence_val = None; + self.unmarked = true; + let _ = self.signal_now(); } } @@ -2248,8 +2267,54 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); } - self.value += 1; - let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + // (a failed Signal leaves the mapping `unmarked`: `mark` gets it a later one) + self.unmarked = true; + let _ = self.signal_now(); + } + + /// A Signal of `fence` with the next value now. `value` moves only when the Signal was + /// queued: queues wait for `value` (`before_execute`), and a value no Signal reaches would + /// hold them forever. A mapping whose Signal failed is covered by the next one that succeeds + /// (the queue runs in order). + unsafe fn signal_now(&mut self) -> Option { + let next = self.value + 1; + #[cfg(test)] + if FAIL_SIGNALS.with(|f| f.get() > 0 && { f.set(f.get() - 1); true }) { + return None; + } + super::real::native_queue_signal(&self.queue, &self.fence, next).ok()?; + self.value = next; + self.unmarked = false; + if let Some(ring) = &mut self.zero_ring { + for slot in &mut ring.slots { + slot.fence_val.get_or_insert(next); + } + } + Some(next) + } + + /// The value that covers every mapping queued so far: `value`, or a new Signal if a mapping's + /// own Signal failed (`unmarked`). None: no Signal could be queued for it - nothing may count + /// on that mapping yet (a queue's work, a texture back to the pool). + unsafe fn mark(&mut self) -> Option { + if self.unmarked { + self.signal_now() + } else { + Some(self.value) + } + } + + /// Retired textures queued with `UNMARKED` (their unmap had no Signal) get the mark of one now, + /// if one can be queued; till then they stay out of the pool. + unsafe fn mark_pending_recycles(&mut self) { + if !self.pending_recycles.iter().any(|p| p.mark == UNMARKED) { + return; + } + if let Some(mark) = self.mark() { + for p in self.pending_recycles.iter_mut().filter(|p| p.mark == UNMARKED) { + p.mark = mark; + } + } } /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return @@ -2279,8 +2344,9 @@ impl Pages { Some(&total), D3D12_TILE_MAPPING_FLAG_NONE, ); - self.value += 1; - let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + // (a failed Signal leaves the mapping `unmarked`: `mark` gets it a later one) + self.unmarked = true; + let _ = self.signal_now(); } /// Mark work submitted so far on every active queue. Retirement marks cover queues which @@ -3043,7 +3109,10 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla /// release any previously retired heaps whose GPU fences have completed, and periodically (once /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind /// per-queue GPU fence signals across all live queues on the device. -pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { +/// +/// false: a tile mapping is queued that no Signal of the mapping queue covers (its own failed, and +/// so did one queued now): the work must not go (`PreparationOutcome::MappingUnmarked`). +pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) -> bool { let measure = before_execute_timing_active(); let mut measured = BeforeExecuteTiming { calls: measure as usize, ..Default::default() }; let gate_started = measure.then(std::time::Instant::now); @@ -3071,7 +3140,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if measure { record_before_execute_timing(measured); } - return; + return true; }; if let Some(started) = device_started { measured.device = started.elapsed(); @@ -3088,6 +3157,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; let mut completed_unmaps = Vec::new(); let mut wait = None; + let mut unmarked = false; let state_started = measure.then(std::time::Instant::now); { let mut g = PAGES.lock().unwrap(); @@ -3097,11 +3167,15 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { }); // (the recycled tiles of textures mapped since: zeroed before the queue's work uses them) pages.flush_zero_tiles(&dev); - let value = pages.value; - if reserve_page_wait(&mut pages.waited, queue_key, value) { - wait = Some((pages.fence.clone(), value)); + match pages.mark() { + Some(value) => { + if reserve_page_wait(&mut pages.waited, queue_key, value) { + wait = Some((pages.fence.clone(), value)); + } + } + None => unmarked = true, } - if now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { + if !unmarked && now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { pages.last_reclaim = now; do_reclaim = true; newly_reclaimed = pages.sweep_and_reclaim(now); @@ -3143,6 +3217,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if measure { record_before_execute_timing(measured); } + !unmarked } #[cfg(test)] @@ -3155,9 +3230,13 @@ pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); pub(super) unsafe fn note_mapping_for_test(dev: &ID3D12Device) -> Option { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; - pages.value += 1; - super::real::native_queue_signal(&pages.queue, &pages.fence, pages.value).ok()?; - Some(pages.value) + pages.signal_now() +} + +#[cfg(test)] +thread_local! { + /// `signal_now` fails this many times on this thread (tests of a failed Signal) + static FAIL_SIGNALS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The page mapping value of `dev` now: every mapping and unmapping on the device raises it. @@ -4849,8 +4928,17 @@ mod tests { let second = reserved(); let (used2, extra2) = pages.bind(&dev, &second, 0x2010_0000, Some(PAGE as u64), 1).expect("bind again"); assert_eq!(pages.pending_zero_tiles, vec![(0, 0)], "the second texture got the first one's page"); + let mapped = pages.value; + FAIL_SIGNALS.with(|f| f.set(1)); pages.flush_zero_tiles(&dev); assert!(pages.pending_zero_tiles.is_empty()); + assert!(pages.unmarked); + assert_eq!(pages.value, mapped, "a failed zero-fill Signal cannot advance the mapping fence"); + let slot = pages.zero_ring.as_ref().unwrap().slots.iter().position(|s| s.fence_val.is_none()) + .expect("the zero-fill slot stays in flight until it has a mark"); + let mark = pages.mark().expect("a later Signal covers the zero-fill"); + assert_eq!(mark, mapped + 1); + assert_eq!(pages.zero_ring.as_ref().unwrap().slots[slot].fence_val, Some(mark)); let rb = committed(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); copy(&pages, &rb, &second, 2); @@ -6167,4 +6255,193 @@ mod tests { late_release::drain_known(true); } } + + /// A Signal that fails leaves `value` where a Signal reached it, so queues waiting for it + /// (`before_execute`) are not held forever. + #[test] + fn a_failed_signal_leaves_the_value_a_signal_reached() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + let reached_value = p.signal_now().expect("a Signal"); + FAIL_SIGNALS.with(|f| f.set(1)); + assert_eq!(p.signal_now(), None); + assert_eq!(p.value, reached_value, "a failed Signal does not move the value queues wait for"); + assert!(reached(&p.fence, p.value, 5000), "the value is reached"); + FAIL_SIGNALS.with(|f| f.set(0)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// `fence` reaches `value` within `ms` (polled). + fn reached(fence: &ID3D12Fence, value: u64, ms: u64) -> bool { + let end = std::time::Instant::now() + std::time::Duration::from_millis(ms); + loop { + if unsafe { fence.GetCompletedValue() } >= value { + return true; + } + if std::time::Instant::now() >= end { + return false; + } + std::thread::sleep(std::time::Duration::from_micros(200)); + } + } + + /// A bind and a NULL unmap whose Signals fail are covered by a later Signal before anything + /// counts on them: `before_execute` queues one and has the title's queue wait for it (or says + /// the work must not go when it cannot), and a retired texture stays out of the pool until one + /// completes. The mapping queue is held behind a test fence meanwhile. + #[test] + fn mappings_whose_signal_failed_get_a_later_mark_before_use() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let (mq, mfence) = (pages.queue.clone(), pages.fence.clone()); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let res = r.unwrap(); + let mut total = 0u32; + dev.GetResourceTiling(&res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + let title: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let title_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let done = |f: &ID3D12Fence, v: u64| reached(f, v, 5000); + + // mark N, completed + let mut n = 0; + with(&mut |p| n = p.signal_now().unwrap()); + assert!(done(&mfence, n)); + assert!(before_execute(&title)); + + // a bind whose Signal fails, behind a held mapping queue + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + mq.Wait(&gate, 1).unwrap(); + FAIL_SIGNALS.with(|f| f.set(1)); + let mut bound = None; + with(&mut |p| bound = p.bind(&dev, &res, 0x6000_0000, Some(total as u64 * PAGE as u64), total)); + let (used, extra) = bound.expect("bound"); + with(&mut |p| assert!(p.unmarked && p.value == n, "the bind has no mark of its own")); + + // the title's next work: a Signal N+1 is queued now and the work waits for it + assert!(before_execute(&title), "a later Signal could be queued"); + with(&mut |p| assert!(!p.unmarked && p.value == n + 1)); + super::super::real::native_queue_signal(&title, &title_fence, 1).unwrap(); + assert!(!reached(&title_fence, 1, 100), "the title's work waits for N+1"); + gate.Signal(1).unwrap(); + assert!(done(&title_fence, 1), "and goes once N+1 is done"); + + // no Signal at all: the work must not go + with(&mut |p| p.unmarked = true); + FAIL_SIGNALS.with(|f| f.set(1)); + assert!(!before_execute(&title), "no mark: the submit must wait for one"); + FAIL_SIGNALS.with(|f| f.set(0)); + + // a held unmap that becomes releasable inside before_execute, its NULL mapping's Signal + // failing: before_execute queues a later mark after it and the work waits for that + let held = |va: usize| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let r = r.unwrap(); + let done_fence: ID3D12Fence = dev.CreateFence(1, D3D12_FENCE_FLAG_NONE).unwrap(); + with(&mut |p| { + let (used, used_extra) = p.bind(&dev, &r, va, Some(total as u64 * PAGE as u64), total).expect("bound"); + let mark = p.signal_now().expect("a Signal"); + assert!(reached(&p.fence, mark, 5000)); + p.held_unmaps.push(HeldUnmap { res: r.clone(), total, used, used_extra, level_tiles: Vec::new(), marks: vec![(done_fence.clone(), 1)], immediate_cool: false }); + }); + r + }; + let held_a = held(0x6100_0000); + let mut before = 0; + with(&mut |p| before = p.value); + let gate3: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + mq.Wait(&gate3, 1).unwrap(); + FAIL_SIGNALS.with(|f| f.set(1)); + assert!(before_execute(&title), "a later Signal could be queued"); + FAIL_SIGNALS.with(|f| f.set(0)); + with(&mut |p| { + assert!(p.held_unmaps.is_empty(), "the held unmap was released"); + assert!(!p.unmarked && p.value == before + 1, "and a later Signal covers its NULL mapping"); + }); + super::super::real::native_queue_signal(&title, &title_fence, 2).unwrap(); + assert!(!reached(&title_fence, 2, 100), "the title's work waits for it"); + gate3.Signal(1).unwrap(); + assert!(done(&title_fence, 2)); + // the same with no Signal at all: the work must not go + let held_b = held(0x6200_0000); + FAIL_SIGNALS.with(|f| f.set(2)); + assert!(!before_execute(&title), "no mark for the released unmap: the submit waits for one"); + FAIL_SIGNALS.with(|f| f.set(0)); + with(&mut |p| assert!(p.held_unmaps.is_empty() && p.unmarked)); + assert!(before_execute(&title), "a Signal again: the work goes"); + drop((held_a, held_b)); + + // a retired texture's NULL unmap whose Signal fails, and the retry too + let raw = res.clone().into_raw() as usize; + with(&mut |p| { + p.release_tiles(used.clone(), extra.clone(), std::time::Instant::now(), false); + }); + let gate2: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + mq.Wait(&gate2, 1).unwrap(); + let key = ReservedKey::from_desc(&desc, 0); + park_recyclable(raw, RecycleInfo { dev_key, key, total, was_mapped: true }, 0); + FAIL_SIGNALS.with(|f| f.set(2)); + assert!(recycle_ready(raw)); + FAIL_SIGNALS.with(|f| f.set(0)); + with(&mut |p| assert!(p.pending_recycles.iter().any(|r| r.raw == raw && r.mark == UNMARKED), "no mark yet")); + drain_recycled(); + let mut later = 0; + with(&mut |p| { + assert_eq!(p.reserved_pool.count(&key), 0, "not in the pool before a mark completes"); + later = p.pending_recycles.iter().find(|r| r.raw == raw).expect("still pending").mark; + assert!(later != UNMARKED && later > n + 1, "a later Signal was queued for it"); + }); + gate2.Signal(1).unwrap(); + assert!(done(&mfence, later)); + drain_recycled(); + let mut back = None; + with(&mut |p| { + assert_eq!(p.reserved_pool.count(&key), 1, "in the pool once its mark completed"); + back = p.reserved_pool.take(&key); + }); + assert_eq!(back.map(|b| b.0), Some(raw)); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + drop(res); + PAGES.lock().unwrap().remove(&dev_key); + } + } } From d1ba113b8427702aed2f38bf1bab4e1cc0c02e6e Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:40:11 +0100 Subject: [PATCH 171/175] D3D12.X: hand the title reserved textures with live page tables amdgpu, the Linux kernel driver, runs a process's page-table updates in order on one queue, and every unmap and every sparse rebind (REPLACE frees the old range) waits for all command submissions of the VM first. While a frame is in flight, a reserved texture made after its submit has no page-table entries, not even the PRT ones, until that frame is done. A console title may write a descriptor of a texture it has just placed that work it already submitted reads; on the console the memory is there, here the read is a GPU page fault (TCP, PERMISSION_FAULTS 0x3) and the device is lost. RADV_DEBUG=bo_history and the kernel log put the faulting virtual BO 32-38 ms after its creation, by a new placement, with the hung IB older than the texture. A texture from the pool has had its entries since before: its rebind still lands late, but the work in flight reads a NULL tile meanwhile. So: - the pool also takes render targets, depth and UAV textures and those with a clear value, keyed by its meaningful bytes; - every placement tops its description up to XCL_RESERVED_SPARES (default 2) spares made ahead, reserved under the pages lock and pooled only once a Signal of the mapping queue after them completes; - a placement that still has to make a new texture waits up to XCL_PLACE_MAP_WAIT_MS (default 1000) for such a Signal, polling the fence; when no Signal can be queued for it, the placement fails as a failed creation does. It is one change because the parts only work together: without the wait a burst of new textures outruns the spares and faults; without the spares every new placement waits a frame. It builds on the marks for mappings whose Signal failed (the commit before): spares and new placements count on a Signal reaching their mappings. On by default only under Wine with an AMD GPU, judged by the Vulkan physical device vkd3d-proton drives (DXVK's DXGI may report an NVIDIA GPU as AMD), else by the DXGI adapter: Windows drivers do not order page-table updates like this, and the extra creations and waits cost time on the title's thread (the log says how much: the placements, the spares made and the time spent making them, and the waits). XCL_LIVE_RESERVED=1/0 forces it either way. Tests: the gate and the vendor source, clear keys, the fence wait, placements with the gate on and off, concurrent placements and their spares, spares and a cold lazy placement whose Signal fails, and spares kept out of dump tracking. (cherry picked from commit ee13d5ada0b55f7348f4da27cd514936c9839e2f) --- crates/xcl/src/hle/d3d12x/lut3d.rs | 14 + crates/xcl/src/hle/d3d12x/real.rs | 13 + crates/xcl/src/hle/d3d12x/vram.rs | 1101 +++++++++++++++++++++++++++- 3 files changed, 1121 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/lut3d.rs b/crates/xcl/src/hle/d3d12x/lut3d.rs index 6f969c56b6..2f049375e0 100644 --- a/crates/xcl/src/hle/d3d12x/lut3d.rs +++ b/crates/xcl/src/hle/d3d12x/lut3d.rs @@ -29,9 +29,23 @@ const DUMPED_MOST: usize = 256; const WRITES_LOGGED: u64 = 12; pub fn on() -> bool { + #[cfg(test)] + if FORCE_ON.load(Ordering::Relaxed) { + return true; + } super::targets::enabled() } +/// Tests: track 3D textures as `XCL_DUMP_TARGETS` does. +#[cfg(test)] +pub static FORCE_ON: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Tests: `res` is one of the 3D textures a dump enumerates. +#[cfg(test)] +pub fn tracked(res: usize) -> bool { + VOLS.lock().unwrap().contains_key(&res) +} + /// Whether `created` is to be told of a resource made (`on`, or `XCL_CAPTURE_FRAME`). pub fn created_on() -> bool { on() || super::capture::enabled() diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 34f0a68dfb..478f69b742 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5365,6 +5365,19 @@ pub(super) unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESUL hr } +/// `res` is no longer one of the reserved resources `note_reserved` keeps (a spare or an evicted one +/// of `vram`'s pool, which goes without the title's Release). +pub(super) fn forget_reserved(res: usize) { + if let Some(s) = RESERVED.lock().unwrap().as_mut() { + s.remove(&res); + } +} + +#[cfg(test)] +pub(super) fn is_noted_reserved(res: usize) -> bool { + RESERVED.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&res)) +} + unsafe fn is_reserved(res: *mut c_void) -> bool { let kept = RESERVED.lock().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()); kept.is_some_and(|k| desc_of(res) == Some(k)) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 0a20dff6b4..f431944681 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -737,6 +737,294 @@ fn reserved_pool_enabled() -> bool { *ON.get_or_init(|| std::env::var("XCL_RESERVED_POOL").ok().as_deref() != Some("0")) } +/// Hand the title reserved textures whose VA predates the work in flight where possible: the +/// pool also takes render targets, depth and UAV textures, spares are made ahead per description +/// (`reserved_spares`), and a placement that still has to make a new one waits for its page +/// tables (`wait_new_placement`). +/// +/// This works around amdgpu, the Linux kernel driver: it runs a process's page-table updates in +/// order on one queue, and every unmap and every sparse rebind (REPLACE frees the old range) waits +/// for all command submissions of the VM first. So while a frame is in flight, a reserved texture +/// made after its submit has no page-table entries at all, not even PRT ones, until that frame is +/// done. A console title may write a descriptor of a texture it has just placed that work it +/// already submitted reads (on the console the memory is there): a GPU page fault (a retail title on +/// Wine + RADV). A texture from the pool has had its entries since before: a rebind still lands +/// late, but the work in flight reads the NULL (PRT) tile meanwhile, not an invalid page. +/// +/// Windows drivers do not order page-table updates behind running work like that, and the extra +/// CreateReservedResource calls and waits cost time on the title's thread, so it is on by default +/// only under Wine on an AMD adapter (`live_decide`). `XCL_LIVE_RESERVED=1` / `0` forces it on or +/// off anywhere; `XCL_RESERVED_POOL=0` turns it off with the pool. +fn live_reserved_for(dev: &ID3D12Device) -> bool { + let forced = std::env::var("XCL_LIVE_RESERVED").ok(); + reserved_pool_enabled() && live_decide(forced.as_deref(), crate::util::under_wine(), || unsafe { pick_vendor(vulkan_vendor(dev), || adapter_vendor(dev)) }) +} + +/// The GPU's vendor: the Vulkan physical device's when known, else DXGI's. Under Proton, DXVK's +/// DXGI may report an NVIDIA GPU as AMD (for games that check), while the Vulkan device that +/// vkd3d-proton drives (and the kernel driver behind it) is the real one. +fn pick_vendor(vulkan: Option, dxgi: impl FnOnce() -> Option) -> Option { + vulkan.or_else(dxgi) +} + +/// `VkPhysicalDeviceProperties::vendorID` of the physical device vkd3d-proton made `dev` on, +/// through its `ID3D12DXVKInteropDevice` (None: not vkd3d-proton, or no Vulkan loader). +unsafe fn vulkan_vendor(dev: &ID3D12Device) -> Option { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress, LoadLibraryA}; + // ID3D12DXVKInteropDevice (vkd3d-proton's include/vkd3d_device_vkd3d_ext.idl) + const IID_INTEROP: windows::core::GUID = windows::core::GUID::from_u128(0x39da4e09_bd1c_4198_9fae_86bbe3be41fd); + let mut interop: *mut c_void = std::ptr::null_mut(); + if dev.query(&IID_INTEROP, &mut interop).is_err() || interop.is_null() { + return None; + } + let interop = windows::core::IUnknown::from_raw(interop); + let vtbl = *(interop.as_raw() as *const *const usize); + // IUnknown (3), GetDXGIAdapter, GetInstanceExtensions, GetDeviceExtensions, GetDeviceFeatures, + // then GetVulkanHandles(VkInstance *, VkPhysicalDevice *, VkDevice *) + type Handles = unsafe extern "system" fn(*mut c_void, *mut usize, *mut usize, *mut usize) -> windows::core::HRESULT; + let get_handles: Handles = std::mem::transmute(*vtbl.add(7)); + let (mut instance, mut physical, mut device) = (0usize, 0usize, 0usize); + get_handles(interop.as_raw(), &mut instance, &mut physical, &mut device).ok().ok()?; + if physical == 0 { + return None; + } + let mut vulkan = GetModuleHandleA(c"vulkan-1.dll".as_ptr() as *const u8); + if vulkan.is_null() { + vulkan = LoadLibraryA(c"vulkan-1.dll".as_ptr() as *const u8); + } + if vulkan.is_null() { + return None; + } + let f = GetProcAddress(vulkan, c"vkGetPhysicalDeviceProperties".as_ptr() as *const u8)?; + type Props = unsafe extern "system" fn(usize, *mut u8); + let props: Props = std::mem::transmute(f); + // VkPhysicalDeviceProperties: apiVersion, driverVersion, vendorID, ... (824 bytes; room to spare) + let mut buf = vec![0u8; 4096]; + props(physical, buf.as_mut_ptr()); + let vendor = u32::from_le_bytes(buf[8..12].try_into().unwrap()); + (vendor != 0).then_some(vendor) +} + +/// `live_reserved_for`'s choice: `forced` from `XCL_LIVE_RESERVED`, else Wine on AMD (0x1002). +fn live_decide(forced: Option<&str>, wine: bool, vendor: impl FnOnce() -> Option) -> bool { + match forced.map(str::trim) { + Some("1") => true, + Some("0") => false, + _ => wine && vendor() == Some(0x1002), + } +} + +/// PCI vendor id of `dev`'s adapter. +unsafe fn adapter_vendor(dev: &ID3D12Device) -> Option { + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter = factory.EnumAdapterByLuid(dev.GetAdapterLuid()).ok()?; + Some(adapter.GetDesc().ok()?.VendorId) +} + +/// Spare reserved textures kept made ahead per description (`XCL_RESERVED_SPARES`, default 2; +/// only where `live_reserved_for` holds): made next to a placement, they enter the pool once the +/// mapping queue passes a Signal after them, which is once their page-table entries exist. +fn reserved_spares() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_RESERVED_SPARES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2).min(16)) +} + +/// How many spares to make for a description with `have` pooled or pending ones. +fn spares_to_make(have: usize, want: usize) -> usize { + want.saturating_sub(have) +} + +/// (placements from the pool, new ones, spares made, µs spent making them, longest one call) +static LIVE_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +fn note_live_stats(pooled: bool) { + use std::sync::atomic::Ordering::Relaxed; + let n = LIVE_STATS[if pooled { 0 } else { 1 }].fetch_add(1, Relaxed) + LIVE_STATS[if pooled { 1 } else { 0 }].load(Relaxed) + 1; + if n.is_power_of_two() && n >= 64 { + crate::xlog_info!( + "D3D12.X: reserved textures placed: {} from the pool (VA live before), {} new (VA maybe not live for work in flight); {} spares made ahead, in {} ms on the placing threads (longest call {} µs)", + LIVE_STATS[0].load(Relaxed), + LIVE_STATS[1].load(Relaxed), + LIVE_STATS[2].load(Relaxed), + LIVE_STATS[3].load(Relaxed) / 1000, + LIVE_STATS[4].load(Relaxed) + ); + } +} + +/// How long a placement that had to make a new reserved texture waits on the CPU for a Signal of +/// the mapping queue sent after it (`XCL_PLACE_MAP_WAIT_MS`, default 1000; 0: no wait). That +/// Signal completes once the texture's page-table entries exist, which is once the work in flight +/// before it is done, so the title cannot write a descriptor of it that work reads. Each such +/// placement waits on its own, also after one that timed out. +fn place_map_wait_ms() -> u64 { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + *MS.get_or_init(|| std::env::var("XCL_PLACE_MAP_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1000)) +} + +/// (new placements that waited, of them timed out, total µs, longest µs) +static NEW_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// How a wait for a fence value ended. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum FenceWait { + /// it had completed already + Done, + /// it completed within the time, after this long + Waited(std::time::Duration), + /// it had not completed after this long + TimedOut(std::time::Duration), +} + +/// Wait up to `ms` for `fence` to reach `value`, polling it with short sleeps. No event is +/// registered with the fence: vkd3d-proton keeps a registered handle until the value is reached, +/// so an event closed after a timeout could be signalled later under a reused handle. +unsafe fn wait_fence(fence: &ID3D12Fence, value: u64, ms: u64) -> FenceWait { + if super::real::fence_completed(fence) >= value { + return FenceWait::Done; + } + let t0 = std::time::Instant::now(); + let limit = std::time::Duration::from_millis(ms); + loop { + if super::real::fence_completed(fence) >= value { + return FenceWait::Waited(t0.elapsed()); + } + let left = limit.saturating_sub(t0.elapsed()); + if left.is_zero() { + return FenceWait::TimedOut(t0.elapsed()); + } + std::thread::sleep(left.min(std::time::Duration::from_micros(500))); + } +} + +/// How `wait_new_placement` ended. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum NewWait { + /// `XCL_PLACE_MAP_WAIT_MS=0`: no wait asked for + Off, + /// a Signal was queued and waited for (or timed out) + Signalled(FenceWait), + /// no Signal could be queued, twice: nothing tells when the texture's page tables exist + Failed, +} + +/// A placement that had to make a new reserved texture: a Signal of the mapping queue after it +/// (one retry if it cannot be queued), and a wait for it up to `place_map_wait_ms`. +unsafe fn wait_new_placement(dev_key: usize) -> NewWait { + use std::sync::atomic::Ordering::Relaxed; + let ms = place_map_wait_ms(); + if ms == 0 { + return NewWait::Off; + } + let (fence, value) = { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return NewWait::Failed }; + let Some(value) = pages.signal_now().or_else(|| pages.signal_now()) else { return NewWait::Failed }; + (pages.fence.clone(), value) + }; + let end = wait_fence(&fence, value, ms); + let (took, timed_out) = match end { + FenceWait::Done => return NewWait::Signalled(end), + FenceWait::Waited(d) => (d, false), + FenceWait::TimedOut(d) => (d, true), + }; + let us = took.as_micros().min(u64::MAX as u128) as u64; + let n = NEW_WAITS[0].fetch_add(1, Relaxed) + 1; + if timed_out { + NEW_WAITS[1].fetch_add(1, Relaxed); + } + NEW_WAITS[2].fetch_add(us, Relaxed); + NEW_WAITS[3].fetch_max(us, Relaxed); + if n.is_power_of_two() || timed_out { + crate::xlog_info!( + "D3D12.X: new reserved textures waited for their page tables: {n} ({} timed out after {ms} ms), {} ms in all, longest {} ms", + NEW_WAITS[1].load(Relaxed), + NEW_WAITS[2].load(Relaxed) / 1000, + NEW_WAITS[3].load(Relaxed) / 1000 + ); + } + NewWait::Signalled(end) +} + +/// Spares `place_on_pages` reserved; dropped before `take`, the reservation is given back. +struct SpareReservation { + dev_key: usize, + key: Option, + n: usize, +} + +impl SpareReservation { + /// The reserved count, now `make_spares`' to give back. + fn take(&mut self) -> usize { + std::mem::take(&mut self.n) + } +} + +impl Drop for SpareReservation { + fn drop(&mut self) { + if let (Some(key), true) = (self.key, self.n != 0) { + if let Some(Some(pages)) = PAGES.lock().unwrap().get_mut(&self.dev_key) { + pages.end_spare_reservation(key, self.n); + } + } + } +} + +/// Make the `n` spare reserved textures like `tiled` that `place_on_pages` reserved under +/// `PAGES.lock()` (`Pages::spares_in_flight`), and queue them for the pool behind one Signal of +/// the mapping queue (`reserved_spares`). The reservation is given back whatever happens; spares +/// without a Signal (it failed) are released instead. +unsafe fn make_spares(dev: &ID3D12Device, this: *mut c_void, tiled: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void, key: ReservedKey, n: usize) { + if n == 0 { + return; + } + let started = std::time::Instant::now(); + let mut made: Vec<(usize, u32)> = Vec::with_capacity(n); + for _ in 0..n { + let mut p: *mut c_void = std::ptr::null_mut(); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + // (the PC creator, not the title-facing one: an idle spare is no resource of the title's, + // so nothing that tracks those - `note_reserved`, `lut3d` - may know it; it is registered + // when handed out, as a title's released one is: `place_on_pages`, then `device_x`) + let hr = super::real::pc_create_reserved_resource(this, tiled as *const _ as usize, state as usize, clear as usize, riid, &mut p); + if hr < 0 || p.is_null() { + break; + } + let Some(res) = ID3D12Resource::from_raw_borrowed(&p) else { break }; + let mut total = 0u32; + dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + made.push((p as usize, total)); + } + let unsignalled = { + let mut g = PAGES.lock().unwrap(); + match g.get_mut(&(dev.as_raw() as usize)) { + Some(Some(pages)) => { + pages.end_spare_reservation(key, n); + match (made.is_empty(), pages.signal_now()) { + (true, _) => Vec::new(), + (false, Some(mark)) => { + LIVE_STATS[2].fetch_add(made.len() as u64, std::sync::atomic::Ordering::Relaxed); + PENDING_RECYCLES.fetch_add(made.len(), std::sync::atomic::Ordering::Release); + for &(raw, total) in &made { + pages.pending_recycles.push_back(PendingRecycle { key, raw, total, mark }); + } + Vec::new() + } + (false, None) => made, + } + } + _ => made, + } + }; + for (raw, _) in unsignalled { + drop(windows::core::IUnknown::from_raw(raw as *mut c_void)); + } + let us = started.elapsed().as_micros() as u64; + LIVE_STATS[3].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + LIVE_STATS[4].fetch_max(us, std::sync::atomic::Ordering::Relaxed); +} + /// Exact description and uniform D3D12 resource state of a recyclable reserved sampled texture. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] struct ReservedKey { @@ -751,11 +1039,29 @@ struct ReservedKey { sample_quality: u32, flags: i32, state: u32, + /// the optimized clear value's bytes (`D3D12_CLEAR_VALUE`), all zero without one + clear: [u8; CLEAR_VALUE_BYTES], } +const CLEAR_VALUE_BYTES: usize = std::mem::size_of::(); + impl ReservedKey { + /// `clear`: null or a `D3D12_CLEAR_VALUE`. Only its meaningful bytes count: the format, and + /// the four colour floats, or for a depth-stencil texture the depth float and the stencil + /// byte (the rest of the union is not initialised then). + unsafe fn from_desc_clear(desc: &D3D12_RESOURCE_DESC, state: u32, clear: *const c_void) -> Self { + let mut key = Self::from_desc(desc, state); + if !clear.is_null() { + // (only those bytes are read: the rest may not even be readable memory) + let used = if desc.Flags.contains(D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { 4 + 4 + 1 } else { CLEAR_VALUE_BYTES }; + std::ptr::copy_nonoverlapping(clear as *const u8, key.clear.as_mut_ptr(), used); + } + key + } + fn from_desc(desc: &D3D12_RESOURCE_DESC, state: u32) -> Self { Self { + clear: [0; CLEAR_VALUE_BYTES], dimension: desc.Dimension.0, alignment: desc.Alignment, width: desc.Width, @@ -809,7 +1115,6 @@ impl ReservedPool { } } - #[cfg(test)] fn count(&self, key: &ReservedKey) -> usize { self.by_key.get(key).map_or(0, Vec::len) } @@ -919,7 +1224,14 @@ pub(super) unsafe fn drain_recycled() { PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release); } } + release_evicted(evicted); +} + +/// Release reserved textures evicted from the pool (outside `PAGES.lock()`), with nothing of +/// XCL's left that names them. +unsafe fn release_evicted(evicted: Vec) { for old in evicted { + super::real::forget_reserved(old); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(old as *mut c_void, 2)); f(old as *mut c_void); } @@ -1919,8 +2231,12 @@ struct Pages { held_unmaps: Vec, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// `live_reserved_for` this device + live: bool, /// a mapping was queued whose Signal failed: `value` does not cover it (`mark`) unmarked: bool, + /// spares `place_on_pages` reserved and `make_spares` is making, by description + spares_in_flight: std::collections::HashMap, /// idle reserved sampled textures kept for reuse by `(desc, state)` (#1268) reserved_pool: ReservedPool, /// retired reserved textures held until the tile-mapping queue passes their unmap fence mark @@ -2076,7 +2392,9 @@ impl Pages { unmap_fences: std::collections::HashMap::new(), held_unmaps: Vec::new(), reservable_cache: std::collections::HashMap::new(), + live: live_reserved_for(dev), unmarked: false, + spares_in_flight: std::collections::HashMap::new(), reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), pending_recycles: std::collections::VecDeque::new(), scratch_heaps: Vec::new(), @@ -2272,10 +2590,33 @@ impl Pages { let _ = self.signal_now(); } - /// A Signal of `fence` with the next value now. `value` moves only when the Signal was - /// queued: queues wait for `value` (`before_execute`), and a value no Signal reaches would - /// hold them forever. A mapping whose Signal failed is covered by the next one that succeeds - /// (the queue runs in order). + /// Reserve the spares `key` lacks (pooled, pending and in-flight ones count), up to `want`. + fn reserve_spares(&mut self, key: ReservedKey, want: usize) -> usize { + let in_flight = self.spares_in_flight.get(&key).copied().unwrap_or(0); + let have = self.reserved_pool.count(&key) + self.pending_recycles.iter().filter(|p| p.key == key).count() + in_flight; + let n = spares_to_make(have, want); + if n != 0 { + self.spares_in_flight.insert(key, in_flight + n); + } + n + } + + /// Give back `n` reserved spares of `key` (`make_spares` made or failed them). + fn end_spare_reservation(&mut self, key: ReservedKey, n: usize) { + if let Some(v) = self.spares_in_flight.get_mut(&key) { + *v = v.saturating_sub(n); + if *v == 0 { + self.spares_in_flight.remove(&key); + } + } + } + + /// A Signal of `fence` with the next value now: its submission waits for every page-table + /// update the process queued before (amdgpu syncs a submit to the VM's last update), so the + /// value completes once reserved textures made before have their entries (`make_spares`). + /// `value` moves only when the Signal was queued: queues wait for `value` (`before_execute`), + /// and a value no Signal reaches would hold them forever. A mapping whose Signal failed is + /// covered by the next one that succeeds (the queue runs in order). unsafe fn signal_now(&mut self) -> Option { let next = self.value + 1; #[cfg(test)] @@ -2684,20 +3025,41 @@ unsafe fn place_on_pages( } }; let dev_key = dev.as_raw() as usize; - let recycle_key = (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()) - .then(|| ReservedKey::from_desc(&tiled, state)); + let live; + let recycle_key; let mut pooled = None; + let mut spares = 0usize; + let mut evicted = Vec::new(); let is_reservable = { let mut g = PAGES.lock().unwrap(); let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; let ok = *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)); + live = pages.live; + // (`live_reserved_for`: render targets, depth and UAV textures, those with a clear value, too) + recycle_key = if live { + Some(ReservedKey::from_desc_clear(&tiled, state, clear)) + } else { + (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()).then(|| ReservedKey::from_desc(&tiled, state)) + }; if ok { if let Some(key) = recycle_key { + if live && pending_recycles() { + pages.mark_pending_recycles(); + let before = pages.pending_recycles.len(); + evicted = promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()); + PENDING_RECYCLES.fetch_sub(before - pages.pending_recycles.len(), std::sync::atomic::Ordering::Release); + } pooled = pages.reserved_pool.take(&key); + if live { + spares = pages.reserve_spares(key, reserved_spares()); + } } } ok }; + release_evicted(evicted); + // (given back on every way out of here but `make_spares`) + let mut reservation = SpareReservation { dev_key, key: recycle_key, n: spares }; if !is_reservable { log("no tiled support for its format or sample count"); return None; @@ -2750,6 +3112,16 @@ unsafe fn place_on_pages( None }; let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); + // (no live one in the pool: wait until its VA has page-table entries, before the pages know + // it. A texture with lazy levels queues no mapping here, so that Signal is all that tells; + // when none can be queued the placement fails as a failed creation does: nothing is mapped + // or noted yet, and the spare reservation goes back with `reservation`.) + if cached_total.is_none() && live && wait_new_placement(dev_key) == NewWait::Failed { + crate::xlog_warn!("D3D12.X: texture at {va:#x}: no Signal of the mapping queue after its new reserved texture - not placed on pages"); + drop(windows::core::IUnknown::from_raw(raw)); + *ppv = std::ptr::null_mut(); + return None; + } let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -2783,6 +3155,10 @@ unsafe fn place_on_pages( for r in super::placements::placed(raw as usize, va, (first, first + own * PAGE), super::placements::Backing::Pages(dev_key), kind, desc) { super::late_release::hold_unmap(r); } + if let (true, Some(key)) = (live, recycle_key) { + note_live_stats(cached_total.is_some()); + make_spares(dev, this, &tiled, state, clear, key, reservation.take()); + } Some(hr) } @@ -6062,6 +6438,644 @@ mod tests { assert_eq!(cap3.take(&k_b), Some((0x2000, 1))); } + #[test] + fn reserved_key_tells_clear_values_apart_and_spares_top_up() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + let black = D3D12_CLEAR_VALUE { Format: desc.Format, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0, 0.0, 0.0, 1.0] } }; + let white = D3D12_CLEAR_VALUE { Format: desc.Format, Anonymous: D3D12_CLEAR_VALUE_0 { Color: [1.0; 4] } }; + let (none, k_black, k_white, k_black2) = unsafe { + ( + ReservedKey::from_desc_clear(&desc, state, std::ptr::null()), + ReservedKey::from_desc_clear(&desc, state, &black as *const _ as *const c_void), + ReservedKey::from_desc_clear(&desc, state, &white as *const _ as *const c_void), + ReservedKey::from_desc_clear(&desc, state, &black as *const _ as *const c_void), + ) + }; + assert_eq!(none, ReservedKey::from_desc(&desc, state)); + assert_ne!(none, k_black); + assert_ne!(k_black, k_white); + assert_eq!(k_black, k_black2); + + let mut pool = ReservedPool::new(8); + assert_eq!(pool.count(&k_black), 0); + assert_eq!(pool.push(k_black, 0x1000, 1), None); + assert_eq!(pool.push(k_black, 0x2000, 1), None); + assert_eq!(pool.count(&k_black), 2); + assert_eq!(pool.count(&k_white), 0); + assert!(pool.take(&k_white).is_none()); + assert!(pool.take(&k_black).is_some()); + assert_eq!(pool.count(&k_black), 1); + + assert_eq!(spares_to_make(0, 2), 2); + assert_eq!(spares_to_make(1, 2), 1); + assert_eq!(spares_to_make(5, 2), 0); + assert_eq!(spares_to_make(0, 0), 0); + } + + #[test] + fn live_reserved_is_on_by_default_only_under_wine_on_amd() { + assert!(live_decide(None, true, || Some(0x1002))); + assert!(!live_decide(None, true, || Some(0x10de)), "NVIDIA under Wine"); + assert!(!live_decide(None, false, || Some(0x1002)), "AMD on Windows"); + assert!(!live_decide(None, true, || None), "no adapter"); + assert!(!live_decide(Some(""), false, || Some(0x10de))); + assert!(live_decide(Some("1"), false, || Some(0x10de)), "forced on"); + assert!(live_decide(Some(" 1 "), false, || None), "forced on"); + assert!(!live_decide(Some("0"), true, || Some(0x1002)), "forced off"); + // (forced either way: the adapter is not even asked) + assert!(live_decide(Some("1"), false, || panic!("asked"))); + // DXVK's DXGI says AMD, the Vulkan device is NVIDIA's: off + assert!(!live_decide(None, true, || pick_vendor(Some(0x10de), || Some(0x1002)))); + assert!(live_decide(None, true, || pick_vendor(Some(0x1002), || Some(0x10de)))); + // no Vulkan device known: DXGI's vendor + assert!(live_decide(None, true, || pick_vendor(None, || Some(0x1002)))); + } + + /// Under vkd3d-proton the vendor comes from the Vulkan physical device. + #[test] + fn the_vendor_comes_from_vkd3d_protons_vulkan_device() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + match vulkan_vendor(&dev) { + Some(v) => assert!(v != 0 && Some(v) == pick_vendor(Some(v), || None)), + None => assert!(!crate::util::under_wine(), "vkd3d-proton under Wine has a Vulkan device"), + } + } + } + + #[test] + fn a_depth_clear_key_ignores_the_union_tail() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_DEPTH_WRITE.0 as u32; + // format DXGI_FORMAT_D32_FLOAT (40), depth 1.0, stencil 7, then garbage + let clear = |stencil: u8, tail: u8| { + let mut b = [tail; CLEAR_VALUE_BYTES]; + b[..4].copy_from_slice(&40u32.to_le_bytes()); + b[4..8].copy_from_slice(&1.0f32.to_le_bytes()); + b[8] = stencil; + b + }; + let key = |b: &[u8; CLEAR_VALUE_BYTES]| unsafe { ReservedKey::from_desc_clear(&desc, state, b.as_ptr() as *const c_void) }; + assert_eq!(key(&clear(7, 0x00)), key(&clear(7, 0xCD)), "the uninitialised tail must not split keys"); + assert_ne!(key(&clear(7, 0x00)), key(&clear(8, 0x00)), "the stencil value counts"); + let mut deeper = clear(7, 0); + deeper[4..8].copy_from_slice(&0.0f32.to_le_bytes()); + assert_ne!(key(&clear(7, 0)), key(&deeper), "the depth value counts"); + // a colour clear uses all four floats + let mut colour_desc = desc; + colour_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + let mut c1 = clear(7, 0); + let mut c2 = c1; + c2[19] = 0x3F; + c1[19] = 0x00; + unsafe { + assert_ne!( + ReservedKey::from_desc_clear(&colour_desc, state, c1.as_ptr() as *const c_void), + ReservedKey::from_desc_clear(&colour_desc, state, c2.as_ptr() as *const c_void), + "a colour clear's alpha counts" + ); + } + } + + /// The mapping queue's fence of `dev_key`. + fn queue_fence(dev_key: usize) -> ID3D12Fence { + match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => p.fence.clone(), + _ => panic!("no pages"), + } + } + + /// Owns a fence for a thread that signals it later. + struct SendFence(ID3D12Fence); + unsafe impl Send for SendFence {} + + fn signal_later(fence: &ID3D12Fence, value: u64, after_ms: u64) -> std::thread::JoinHandle<()> { + let f = SendFence(fence.clone()); + std::thread::spawn(move || { + let f = f; + std::thread::sleep(std::time::Duration::from_millis(after_ms)); + unsafe { f.0.Signal(value).unwrap() }; + }) + } + + #[test] + fn wait_fence_returns_at_the_signal_or_times_out() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + assert_eq!(wait_fence(&fence, 0, 1000), FenceWait::Done); + let t = signal_later(&fence, 1, 40); + match wait_fence(&fence, 1, 5000) { + FenceWait::Waited(d) => assert!(d >= std::time::Duration::from_millis(30) && d < std::time::Duration::from_millis(4000), "{d:?}"), + other => panic!("{other:?}"), + } + t.join().unwrap(); + match wait_fence(&fence, 2, 30) { + FenceWait::TimedOut(d) => assert!(d >= std::time::Duration::from_millis(25), "{d:?}"), + other => panic!("{other:?}"), + } + // the timed-out wait left nothing registered: a new event is not signalled when the + // fence reaches that value afterwards + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + let event = CreateEventW(None, false, false, None).unwrap(); + fence.Signal(2).unwrap(); + let got = WaitForSingleObject(event, 50); + let _ = windows::Win32::Foundation::CloseHandle(event); + assert_eq!(got, windows::Win32::Foundation::WAIT_TIMEOUT, "an old wait signalled a new event"); + } + } + + /// A clear value is read only as far as it means something: a depth-stencil one that ends + /// right before an unreadable page. + #[test] + fn a_depth_clear_key_reads_only_its_prefix() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 0x2000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + assert!(!base.is_null()); + let mut old = 0; + assert!(VirtualProtect(base.add(0x1000) as *const c_void, 0x1000, PAGE_NOACCESS, &mut old) != 0); + let at = base.add(0x1000 - 9); + at.copy_from_nonoverlapping([40u8, 0, 0, 0].as_ptr(), 4); + at.add(4).copy_from_nonoverlapping(1.0f32.to_le_bytes().as_ptr(), 4); + *at.add(8) = 7; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let key = ReservedKey::from_desc_clear(&desc, 0, at as *const c_void); + assert_eq!(&key.clear[..9], std::slice::from_raw_parts(at, 9)); + assert!(key.clear[9..].iter().all(|&b| b == 0)); + VirtualFree(base as *mut c_void, 0, MEM_RELEASE); + } + } + + /// With 3D textures tracked for dumps (`XCL_DUMP_TARGETS`): spares are made by the PC creator, + /// so an idle one is neither a title's reserved resource nor a dumped 3D texture, and one + /// released from the pool leaves nothing the dump enumerates; a spare handed to the title by + /// a placement is tracked. + #[test] + fn spares_stay_out_of_dump_tracking_until_handed_out() { + use std::sync::atomic::Ordering::Relaxed; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let Some(uma) = crate::gpu::uma::get() else { + return crate::gpu::recomp::runner::skip_test("no UMA"); + }; + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + super::super::lut3d::FORCE_ON.store(true, Relaxed); + let console = super::super::title_textures::tests::console_desc(4, 32, 32, 32, 1, 28, 0x105); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let Some(base) = uma.alloc(4 << 20, 0x1_0000).map(|p| p as usize) else { + super::super::lut3d::FORCE_ON.store(false, Relaxed); + PAGES.lock().unwrap().remove(&dev_key); + return crate::gpu::recomp::runner::skip_test("no UMA block"); + }; + let place = |va: usize| -> Option { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, console.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p); + (hr >= 0 && !p.is_null()).then(|| ID3D12Resource::from_raw(p)) + }; + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let pending = || { + let mut v = Vec::new(); + with(&mut |p| v = p.pending_recycles.iter().map(|r| (r.key, r.raw)).collect()); + v + }; + + // 1. a new 3D texture: tracked; the spares made for its description are not + let Some(first) = place(base) else { + super::super::lut3d::FORCE_ON.store(false, Relaxed); + PAGES.lock().unwrap().remove(&dev_key); + return crate::gpu::recomp::runner::skip_test("no reserved 3D texture on pages here"); + }; + assert!(first.GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D); + assert!(super::super::lut3d::tracked(first.as_raw() as usize), "the title's 3D texture is tracked"); + let spares = pending(); + assert!(!spares.is_empty(), "spares were made for it"); + for &(_, raw) in &spares { + assert!(!super::super::lut3d::tracked(raw), "an idle spare is not dumped"); + assert!(!super::super::real::is_noted_reserved(raw), "nor kept as a title's reserved resource"); + } + + // 2. its spares reach the pool; one is released as an eviction releases it: the dump's + // enumeration does not know it + with(&mut |p| { + let last = p.signal_now().unwrap(); + assert!(matches!(wait_fence(&p.fence, last, 5000), FenceWait::Done | FenceWait::Waited(_))); + }); + drain_recycled(); + let key = spares[0].0; + let mut evicted = None; + with(&mut |p| evicted = p.reserved_pool.take(&key)); + let (evicted, _) = evicted.expect("a spare in the pool"); + release_evicted(vec![evicted]); + assert!(!super::super::lut3d::tracked(evicted)); + assert!(super::super::lut3d::to_dump().iter().all(|(_, r, _, _)| r.as_raw() as usize != evicted), "a released spare is not enumerated"); + + // 3. the next placement of that description takes a spare from the pool: tracked now + let left: Vec = spares.iter().map(|s| s.1).filter(|&r| r != evicted).collect(); + let second = place(base + (1 << 20)).expect("placed"); + let raw2 = second.as_raw() as usize; + assert!(left.contains(&raw2), "the placement took a spare"); + assert!(super::super::lut3d::tracked(raw2), "a spare handed to the title is tracked"); + assert!(super::super::real::is_noted_reserved(raw2), "and kept as its reserved resource"); + + super::super::lut3d::FORCE_ON.store(false, Relaxed); + drop((first, second)); + let rest: Vec = { + let mut v = Vec::new(); + with(&mut |p| { + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + v = p.pending_recycles.drain(..).map(|r| r.raw).collect(); + while let Some((raw, _)) = p.reserved_pool.take(&key) { + v.push(raw); + } + }); + v + }; + release_evicted(rest); + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// A cold texture with lazy levels queues no mapping, so the Signal after its new reserved + /// texture is all that says its page tables exist: when it cannot be queued a retry is, and + /// waited for; when that fails too the placement fails with nothing left behind. + #[test] + fn a_lazy_placement_without_a_readiness_signal_is_not_handed_out() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let queue = pages.queue.clone(); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let desc = |w: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 10, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place = |va: usize, d: &D3D12_RESOURCE_DESC| -> (Option, *mut c_void) { + let mut p = std::ptr::null_mut(); + let hr = place_on_pages(&dev, dev.as_raw(), va, d, 0, std::ptr::null(), Some(4 << 20), false, true, riid, &mut p); + (hr, p) + }; + let snapshot = || { + let mut t = (0, 0, 0, 0); + with(&mut |p| t = (p.value, p.targets.len(), p.pending_recycles.len(), p.spares_in_flight.len())); + t + }; + + // 1. the first Signal fails, the retry is queued behind a held mapping queue: the + // placement returns only once that retry has completed + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + let (v0, ..) = snapshot(); + FAIL_SIGNALS.with(|f| f.set(1)); + let opener = signal_later(&gate, 1, 80); + let t0 = std::time::Instant::now(); + let (hr, p) = place(0x7000_0000, &desc(512)); + let took = t0.elapsed(); + FAIL_SIGNALS.with(|f| f.set(0)); + opener.join().unwrap(); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "placed after the retry"); + assert!(took >= std::time::Duration::from_millis(60), "it waited for the retried Signal: {took:?}"); + let mut retried = 0; + with(&mut |pg| retried = pg.value); + assert!(retried > v0, "a later Signal was queued"); + assert!(matches!(wait_fence(&queue_fence(dev_key), v0 + 1, 0), FenceWait::Done), "and completed before the title got the texture"); + assert!(has_lazy_levels(p as usize), "a lazy-level texture"); + let first = ID3D12Resource::from_raw(p); + + // 2. no Signal at all: no resource, nothing kept of it (the spares of 1. in the pool + // first, so nothing moves meanwhile) + with(&mut |pg| { + let v = pg.value; + let _ = wait_fence(&pg.fence, v, 5000); + }); + drain_recycled(); + let before = snapshot(); + let placed_before = PLACED_TEXTURES.lock().unwrap().as_ref().map_or(0, |t| t.len()); + FAIL_SIGNALS.with(|f| f.set(2)); + let (hr, p) = place(0x7100_0000, &desc(256)); + FAIL_SIGNALS.with(|f| f.set(0)); + assert!(hr.is_none() && p.is_null(), "no texture without a readiness Signal"); + assert_eq!(snapshot(), before, "no value, target, spare or reservation left behind"); + assert_eq!(PLACED_TEXTURES.lock().unwrap().as_ref().map_or(0, |t| t.len()), placed_before); + + drop(first); + let spares: Vec = { + let mut v = Vec::new(); + with(&mut |pg| { + let last = pg.signal_now().unwrap(); + let _ = wait_fence(&pg.fence, last, 5000); + v = pg.pending_recycles.drain(..).map(|r| r.raw).collect(); + v.extend(pg.reserved_pool.by_key.drain().flat_map(|(_, b)| b.into_iter().map(|e| e.0))); + pg.reserved_pool.live_gen.clear(); + pg.reserved_pool.order.clear(); + }); + v + }; + release_evicted(spares); + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// Placements of one description at once reserve their spares under the lock: together they + /// make no more than `reserved_spares`. The mapping queue is held, so no spare reaches the pool + /// (and gets topped up again) meanwhile. + #[test] + fn concurrent_placements_make_at_most_the_spares_of_one() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use std::sync::atomic::Ordering::Relaxed; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + pages.queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + const THREADS: usize = 4; + let made0 = LIVE_STATS[2].load(Relaxed); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS)); + struct SendDev(ID3D12Device); + unsafe impl Send for SendDev {} + let workers: Vec<_> = (0..THREADS) + .map(|i| { + let (d, b) = (SendDev(dev.clone()), barrier.clone()); + std::thread::spawn(move || { + let d = d; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut p = std::ptr::null_mut(); + b.wait(); + let hr = place_on_pages(&d.0, d.0.as_raw(), 0x5000_0000 + i * 0x10_0000, &desc, 0, std::ptr::null(), Some(256 * 256 * 4), false, false, riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null()); + p as usize + }) + }) + .collect(); + // (every placement waits for its page tables behind the gate; open it once all reserved) + std::thread::sleep(std::time::Duration::from_millis(300)); + gate.Signal(1).unwrap(); + let placed: Vec = workers.into_iter().map(|w| w.join().unwrap()).collect(); + let made = LIVE_STATS[2].load(Relaxed) - made0; + assert!(made <= reserved_spares() as u64, "{made} spares made for {THREADS} placements at once"); + for raw in placed { + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + let spares: Vec = match PAGES.lock().unwrap().get_mut(&dev_key) { + Some(Some(p)) => { + assert!(p.spares_in_flight.is_empty(), "all reservations given back"); + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + p.pending_recycles.drain(..).map(|r| r.raw).collect() + } + _ => Vec::new(), + }; + for raw in spares { + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// `place_on_pages` with the device's `live` flag set: a new texture waits for its page tables + /// and tops its description up with spares; the next one comes from the pool without a wait; + /// with the flag off, no spares and no wait. + #[test] + fn live_placements_wait_when_new_and_take_spares_without_waiting() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use std::sync::atomic::Ordering::Relaxed; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + pages.live = true; + let queue = pages.queue.clone(); + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let desc = |w: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_COMMON.0 as u32; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let place = |va: usize, d: &D3D12_RESOURCE_DESC| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = place_on_pages(&dev, dev.as_raw(), va, d, state, std::ptr::null(), Some(d.Width * 256 * 4), false, false, riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "placed at {va:#x}"); + ID3D12Resource::from_raw(p) + }; + let key = |d: &D3D12_RESOURCE_DESC| ReservedKey::from_desc(&D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*d }, state); + let pending = |k: &ReservedKey| match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => p.pending_recycles.iter().filter(|r| r.key == *k).count() + p.reserved_pool.count(k), + _ => 0, + }; + let waits = || NEW_WAITS[0].load(Relaxed); + + // 1. new: held behind a gate on the mapping queue, it waits until the gate opens + let d256 = desc(256); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); + let opener = signal_later(&gate, 1, 60); + let (w0, t0) = (waits(), std::time::Instant::now()); + let first = place(0x4000_0000, &d256); + let took = t0.elapsed(); + opener.join().unwrap(); + assert_eq!(waits(), w0 + 1, "a new reserved texture waits for its page tables"); + assert!(took >= std::time::Duration::from_millis(40), "it waited for the gate: {took:?}"); + assert_eq!(pending(&key(&d256)), 2, "two spares made ahead"); + + // 2. the next one of that description: a spare from the pool, no wait + let (fence, value) = match PAGES.lock().unwrap().get(&dev_key) { + Some(Some(p)) => (p.fence.clone(), p.value), + _ => unreachable!(), + }; + assert!(matches!(wait_fence(&fence, value, 5000), FenceWait::Done | FenceWait::Waited(_))); + let w1 = waits(); + let second = place(0x4010_0000, &d256); + assert_eq!(waits(), w1, "a spare from the pool does not wait"); + assert_eq!(pending(&key(&d256)), 2, "and its description is topped up again"); + + // 3. gated off: no spares, no wait + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + p.live = false; + } + let d512 = desc(512); + let w2 = waits(); + let third = place(0x4020_0000, &d512); + assert_eq!(waits(), w2, "no wait when off"); + assert_eq!(pending(&key(&d512)), 0, "no spares when off"); + + drop((first, second, third)); + let _ = queue; + let spares: Vec = match PAGES.lock().unwrap().get_mut(&dev_key) { + Some(Some(p)) => { + let last = p.signal_now().unwrap(); + let _ = wait_fence(&p.fence, last, 5000); + let mut v: Vec = p.pending_recycles.drain(..).map(|r| r.raw).collect(); + for k in [key(&d256), key(&d512)] { + while let Some((raw, _)) = p.reserved_pool.take(&k) { + v.push(raw); + } + } + v + } + _ => Vec::new(), + }; + for raw in spares { + assert!(!super::super::real::is_noted_reserved(raw), "a spare is not kept as a title's reserved resource"); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + PAGES.lock().unwrap().remove(&dev_key); + } + } + + /// A spare made while the mapping queue is held enters the pool only once a Signal sent + /// after it completes - before that its VA may have no page table entries. + #[test] + fn a_spare_reaches_the_pool_only_after_its_signal() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let state = D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32; + let key = ReservedKey::from_desc(&desc, state); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + pages.queue.Wait(&gate, 1).unwrap(); + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut r).unwrap(); + let raw = r.unwrap().into_raw() as usize; + let mark = pages.signal_now().unwrap(); + pages.pending_recycles.push_back(PendingRecycle { key, raw, total: 1, mark }); + assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty()); + assert_eq!(pages.reserved_pool.count(&key), 0, "a spare behind the held queue is not live yet"); + gate.Signal(1).unwrap(); + let _ = pages.fence.SetEventOnCompletion(mark, windows::Win32::Foundation::HANDLE::default()); + assert!(promote_pending(&mut pages.reserved_pool, &mut pages.pending_recycles, pages.fence.GetCompletedValue()).is_empty()); + assert_eq!(pages.reserved_pool.take(&key), Some((raw, 1))); + drop(ID3D12Resource::from_raw(raw as *mut c_void)); + } + } + #[test] fn reserved_resource_recycle_unmaps_reuses_and_remaps_on_gpu() { use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; @@ -6136,6 +7150,7 @@ mod tests { fn reserved_resource_with_private_data_is_excluded_from_recycle() { use crate::hle::d3d12x::{late_release, real, title_textures}; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); unsafe { let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { return crate::gpu::recomp::runner::skip_test("no GPU"); @@ -6283,6 +7298,23 @@ mod tests { } } + /// A watchdog for a test fence that holds a queue: it opens it after 10 s at the latest, so a + /// test that holds a shared device's mapping queue can fail but never hang the test process. + fn open_at_the_latest(fence: &ID3D12Fence) { + struct F(ID3D12Fence); + unsafe impl Send for F {} + let f = F(fence.clone()); + std::thread::spawn(move || { + let f = f; + std::thread::sleep(std::time::Duration::from_secs(10)); + unsafe { + if f.0.GetCompletedValue() < 1 { + let _ = f.0.Signal(1); + } + } + }); + } + /// `fence` reaches `value` within `ms` (polled). fn reached(fence: &ID3D12Fence, value: u64, ms: u64) -> bool { let end = std::time::Instant::now() + std::time::Duration::from_millis(ms); @@ -6350,6 +7382,7 @@ mod tests { // a bind whose Signal fails, behind a held mapping queue let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); mq.Wait(&gate, 1).unwrap(); + open_at_the_latest(&gate); FAIL_SIGNALS.with(|f| f.set(1)); let mut bound = None; with(&mut |p| bound = p.bind(&dev, &res, 0x6000_0000, Some(total as u64 * PAGE as u64), total)); @@ -6390,6 +7423,7 @@ mod tests { with(&mut |p| before = p.value); let gate3: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); mq.Wait(&gate3, 1).unwrap(); + open_at_the_latest(&gate3); FAIL_SIGNALS.with(|f| f.set(1)); assert!(before_execute(&title), "a later Signal could be queued"); FAIL_SIGNALS.with(|f| f.set(0)); @@ -6417,6 +7451,7 @@ mod tests { }); let gate2: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); mq.Wait(&gate2, 1).unwrap(); + open_at_the_latest(&gate2); let key = ReservedKey::from_desc(&desc, 0); park_recyclable(raw, RecycleInfo { dev_key, key, total, was_mapped: true }, 0); FAIL_SIGNALS.with(|f| f.set(2)); @@ -6444,4 +7479,56 @@ mod tests { PAGES.lock().unwrap().remove(&dev_key); } } + + /// Spares whose Signal fails are released instead of queued for the pool, no value is published + /// for them, and their reservation is given back. + #[test] + fn spares_without_their_signal_are_released() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let Some(pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + PAGES.lock().unwrap().insert(dev_key, Some(pages)); + let with = |f: &mut dyn FnMut(&mut Pages)| { + if let Some(Some(p)) = PAGES.lock().unwrap().get_mut(&dev_key) { + f(p) + } + }; + let mut reached_value = 0; + with(&mut |p| reached_value = p.signal_now().expect("a Signal")); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + ..Default::default() + }; + let key = ReservedKey::from_desc(&desc, 0); + let mut n = 0; + with(&mut |p| n = p.reserve_spares(key, 2)); + assert_eq!(n, 2); + FAIL_SIGNALS.with(|f| f.set(1)); + make_spares(&dev, dev.as_raw(), &desc, 0, std::ptr::null(), key, n); + with(&mut |p| { + assert_eq!(p.value, reached_value, "no value published for the spares"); + assert!(p.pending_recycles.iter().all(|r| r.key != key), "no spares queued without their Signal"); + assert!(!p.spares_in_flight.contains_key(&key), "the reservation is given back"); + assert_eq!(p.reserve_spares(key, 2), 2, "so the next placement reserves them again"); + p.end_spare_reservation(key, 2); + }); + FAIL_SIGNALS.with(|f| f.set(0)); + PAGES.lock().unwrap().remove(&dev_key); + } + } } From e78c0a436d5b6a9e977a52d77d4c695c4a363293 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 12:30:00 +0100 Subject: [PATCH 172/175] D3D12.X: release PC allocators that had a heavy cycle vkd3d-proton keeps every command buffer an allocator needed in one cycle (recycled up to 256 per pool, never freed by a Reset), and RADV keeps each one's IB (80 KiB, growing to 640 KiB) and 16 KiB upload buffer in host-visible VRAM. GTA VI records 40-110 lists on one allocator in a world frame (4 while loading). alloc_pool's swaps spread those frames over hundreds of PC allocators, and every one that hosted a heavy frame kept its ~80 command buffers for good. That is the world's growing "other" video memory. Evidence (RADV uprobes via bpftrace plus amdgpu_gem_info): - live VkCommandBuffers 3016 vs 80K+160K+320K+640K USWC BOs 2989, 16 KiB upload BOs the same count; vkFreeCommandBuffers was never called. - ~1000 new command buffers a minute in the world, 5.0k of 5.25k in title-namespace pools. Each pool sat at ~6, took one burst of ~80 within 30 s while still being reset, and kept them. - every heavy cycle (42-112 recordings between two driver Resets of one PC allocator) is title list Resets; 39 of the first 66 were on the title's own allocators, 27 on ones alloc_pool made. So the title's own allocator now records only until its first Reset; after that alloc_pool records on allocators it made. Up to XCL_ALLOC_HEAVY_KEEP (16) allocators made here whose cycle reached XCL_ALLOC_HEAVY (16) recordings stay alive as spares, and a swap in a heavy namespace prefers one of them, so it does not grow a fresh allocator to ~80 command buffers again. An idle heavy allocator above that budget is released, and its command buffers go with it. reset_list pins the backing across the unlocked native list Reset, so a concurrent reclaim of the namespace can neither Reset nor release it under the recording that starts. Bundle allocators are left alone: vkd3d-proton keeps no command buffers for them. XCL_ALLOC_RETIRE=0 restores the old behaviour. --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 302 +++++++++++++++++++++++- 1 file changed, 290 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 3533da945a..f6685252be 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -40,6 +40,13 @@ struct Backing { retire_when_free: bool, /// The driver Reset this backing while idle, and no recording has used it since. already_reset: bool, + /// Made here (`ResetWork::Create`), so ours to release. + made: bool, + /// List Resets on it in progress outside STATE (`reset_list`): neither Reset nor released then. + list_resets: usize, + /// Recordings since its last driver Reset, and the most one cycle had. + cycle: u32, + peak: u32, } #[derive(Default)] @@ -133,6 +140,7 @@ struct BackingProbe { release_owner: Option, retire_when_free: bool, already_reset: bool, + list_resets: usize, } impl BackingProbe { @@ -146,11 +154,12 @@ impl BackingProbe { release_owner: backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize), retire_when_free: backing.retire_when_free, already_reset: backing.already_reset, + list_resets: backing.list_resets, } } unsafe fn free(&self) -> bool { - self.users.is_empty() && self.submit_pins == 0 && self.marks.iter().all(|(_, fence, value)| super::real::fence_completed(fence) >= *value) + self.users.is_empty() && self.submit_pins == 0 && self.list_resets == 0 && self.marks.iter().all(|(_, fence, value)| super::real::fence_completed(fence) >= *value) } unsafe fn in_flight(&self) -> bool { @@ -164,6 +173,7 @@ impl BackingProbe { && self.release_owner == backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize) && self.retire_when_free == backing.retire_when_free && self.already_reset == backing.already_reset + && self.list_resets == backing.list_resets && self.marks.len() == backing.marks.len() && self.marks.iter().all(|(queue, fence, value)| { backing.marks.get(queue).is_some_and(|(current, current_value)| current.as_raw() == fence.as_raw() && current_value == value) @@ -914,6 +924,7 @@ fn move_list(s: &mut State, list: usize, backing: usize) { let backing = backing_mut(s, backing); backing.users.insert(list); backing.already_reset = false; + backing.cycle = backing.cycle.saturating_add(1); } /// Detach a recording that is no longer in the title list's submission graph. Its object @@ -957,16 +968,33 @@ pub(super) fn forget_list(list: usize) { /// Reset `list` on the title's allocator `alloc`, committing its new recording association /// only after native Reset succeeds. No pool lock is held across the driver call. pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) -> HRESULT) -> HRESULT { - let backing = current(alloc); + // (the backing is pinned across the driver call: a reclaim of the namespace meanwhile neither + // Resets nor releases it under the recording that starts) + let pinned = enabled() && alloc != 0; + let backing = if pinned { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + let b = s.cur.get(&alloc).copied().unwrap_or(alloc); + backing_mut(s, b).list_resets += 1; + b + } else { + current(alloc) + }; let hr = { let _in_reset = super::late_release::InListReset::enter(); reset(backing) }; - if hr < 0 || !enabled() || alloc == 0 { + if !pinned { return hr; } let mut g = STATE.lock().unwrap(); let s = g.get_or_insert_with(State::default); + if let Some(b) = s.backings.get_mut(&backing) { + b.list_resets -= 1; + } + if hr < 0 { + return hr; + } if ty >= 0 { s.types.insert(alloc, ty); } @@ -1309,6 +1337,100 @@ pub unsafe fn forget(alloc: usize) { } } +/// Recordings in one cycle from which a PC allocator made here counts as heavy (`XCL_ALLOC_HEAVY`): +/// an idle heavy one is released rather than kept as a spare while more than `heavy_keep` are +/// alive. `XCL_ALLOC_RETIRE=0` keeps them all and lets the title's own allocator record past its +/// first Reset, as before. +/// +/// vkd3d-proton keeps every command buffer an allocator needed in one cycle (up to 256), each +/// with its IB (80 KiB and up) and upload buffer in host-visible VRAM, until the allocator goes. +/// GTA VI records 40–110 lists on one allocator in a world frame (4 while loading), and the +/// swaps here spread those frames over hundreds of PC allocators: each kept ~80 command buffers +/// of its one heavy frame, and video memory grew by ~1000 command buffers a minute. +fn heavy_cycle() -> u32 { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_ALLOC_HEAVY").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(16)) +} + +/// Heavy allocators made here that may stay alive (`XCL_ALLOC_HEAVY_KEEP`, 16): an idle heavy +/// spare is released only above this, so a swap can take one again (its command buffers are +/// there already) rather than make an allocator that grows them anew. +fn heavy_keep() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("XCL_ALLOC_HEAVY_KEEP").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(16)) +} + +fn is_bundle(s: &State, alloc: usize) -> bool { + s.types.get(&alloc) == Some(&D3D12_COMMAND_LIST_TYPE_BUNDLE.0) +} + +fn retire_heavy() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_ALLOC_RETIRE").is_ok_and(|v| v.trim() == "0")) +} + +static HEAVY_RELEASED: AtomicU64 = AtomicU64::new(0); + +/// Take out of `alloc`'s namespace the idle (`free`) aside backings made here that had a heavy +/// cycle; the caller releases them outside STATE (`release_heavy`). +fn retire_heavy_in(s: &mut State, alloc: usize, free: &HashSet) -> Vec<(usize, Backing)> { + if !retire_heavy() { + return Vec::new(); + } + #[cfg(test)] + if let Some((limit, keep)) = TEST_HEAVY.with(|t| t.get()) { + return retire_heavy_with(s, alloc, free, limit, keep); + } + retire_heavy_with(s, alloc, free, heavy_cycle(), heavy_keep()) +} + +#[cfg(test)] +thread_local! { + /// (heavy cycle, heavy kept) for the reclaims on this test's thread + static TEST_HEAVY: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +fn retire_heavy_with(s: &mut State, alloc: usize, free: &HashSet, limit: u32, keep: usize) -> Vec<(usize, Backing)> { + // (bundles: vkd3d-proton keeps no command buffers for them, they replay on the CPU) + if is_bundle(s, alloc) { + return Vec::new(); + } + let mut over = s.backings.values().filter(|b| b.made && b.peak.max(b.cycle) >= limit).count().saturating_sub(keep); + if over == 0 { + return Vec::new(); + } + let Some(aside) = s.aside.get_mut(&alloc) else { return Vec::new() }; + let mut out = Vec::new(); + aside.retain(|raw| { + let heavy = over > 0 + && *raw != alloc + && free.contains(raw) + && s.backings.get(raw).is_some_and(|b| b.made && b.release_owner.is_none() && !b.retire_when_free && b.peak.max(b.cycle) >= limit); + if heavy { + over -= 1; + out.push(*raw); + } + !heavy + }); + out.into_iter().filter_map(|raw| s.backings.remove(&raw).map(|b| (raw, b))).collect() +} + +unsafe fn release_heavy(heavy: Vec<(usize, Backing)>) { + for (raw, backing) in heavy { + drop(backing); + super::console_list::allocator_reset(raw as *mut c_void); + drop(ID3D12CommandAllocator::from_raw(raw as *mut c_void)); + let n = HEAVY_RELEASED.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let (made, alive) = STATE.lock().unwrap().as_ref().map_or((0, 0), |s| (s.made, s.backings.values().filter(|b| b.made).count())); + crate::xlog_info!( + "D3D12.X: {n} PC allocators released after a cycle of >= {} recordings (their command buffers go with them); {made} made so far, {alive} alive", + heavy_cycle() + ); + } + } +} + /// Reset every idle aside backing once. The namespace token and backing probes make a driver /// callback, final Release, or newly recorded list invalidate the whole unlocked batch. unsafe fn reclaim_idle_aside(alloc: *mut c_void) { @@ -1326,6 +1448,12 @@ unsafe fn reclaim_idle_aside(alloc: *mut c_void) { let Some(s) = g.as_mut() else { return }; if !namespace_matches(s, a, &mine, &probes) { continue } if s.resetting.contains_key(&a) { return } + let heavy = retire_heavy_in(s, a, &free); + if !heavy.is_empty() { + drop(g); + release_heavy(heavy); + return; + } let mut work = Vec::new(); for raw in s.aside.get(&a).into_iter().flatten().copied() { let Some(probe) = probes.iter().find(|probe| probe.raw == raw && free.contains(&raw) && !probe.already_reset) else { continue }; @@ -1372,6 +1500,8 @@ fn commit_idle_resets( if let Some(backing) = s.backings.get_mut(&probe.raw) { retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); backing.already_reset = true; + backing.peak = backing.peak.max(backing.cycle); + backing.cycle = 0; } } } @@ -1462,7 +1592,10 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { return Some(crate::util::E_FAIL); } let current = s.cur.get(&a).copied().unwrap_or(a); - if !s.backings.contains_key(¤t) || free.contains(¤t) { + // (the title's own allocator records only until its first Reset: the command buffers + // vkd3d-proton keeps of a heavy cycle there could never be given back, the title owns it) + let leave_title = current == a && retire_heavy() && s.backings.contains_key(&a) && s.types.contains_key(&a) && !is_bundle(s, a); + if (!s.backings.contains_key(¤t) || free.contains(¤t)) && !leave_title { if current == a { let retired = s.backings.get_mut(¤t) .map(|backing| backing.marks.drain().map(|(_, (fence, _))| fence).collect::>()) @@ -1480,7 +1613,21 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: false, needed } }; } let Some(&ty) = s.types.get(&a) else { return Some(crate::util::E_FAIL) }; - if let Some(candidate) = s.aside.get(&a).and_then(|values| values.iter().copied().find(|raw| !s.backings.contains_key(raw) || free.contains(raw))) { + // (with `retire_heavy`: never the title's own allocator again, and a heavy spare first – its + // command buffers are there already, a light one would grow them anew) + let skip_own = retire_heavy() && !is_bundle(s, a); + let usable = |raw: &usize| !(skip_own && *raw == a) && (!s.backings.contains_key(raw) || free.contains(raw)); + let peak = |raw: &usize| if skip_own { s.backings.get(raw).map_or(0, |b| b.peak.max(b.cycle)) } else { 0 }; + let chosen = s.aside.get(&a).and_then(|values| { + let mut best: Option = None; + for raw in values.iter().copied().filter(usable) { + if best.is_none_or(|b| peak(&raw) > peak(&b)) { + best = Some(raw); + } + } + best + }); + if let Some(candidate) = chosen { let raw = candidate as *mut c_void; let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; let token = reserve_reset(s, a).unwrap(); @@ -1585,6 +1732,8 @@ fn commit_reset( if let Some(backing) = s.backings.get_mut(&candidate) { retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); backing.already_reset = true; + backing.peak = backing.peak.max(backing.cycle); + backing.cycle = 0; } if !swap { cancel_reset(s, alloc, token); @@ -1592,7 +1741,10 @@ fn commit_reset( } s.aside.entry(alloc).or_default().push(current); s.cur.insert(alloc, candidate); - if created { s.made += 1; } + if created { + s.made += 1; + backing_mut(s, candidate).made = true; + } s.swaps += 1; cancel_reset(s, alloc, token); if s.swaps.is_power_of_two() { @@ -1610,6 +1762,38 @@ fn commit_reset( mod tests { use super::*; + /// An idle PC allocator made here that took a heavy cycle leaves the namespace (to be released + /// with the command buffers vkd3d-proton keeps of that cycle); a light one, a busy one and one + /// the pool did not make stay. + #[test] + fn an_idle_allocator_made_here_after_a_heavy_cycle_is_released() { + let (alloc, heavy, light, busy, foreign) = (0x1000usize, 0x2000usize, 0x3000usize, 0x4000usize, 0x5000usize); + let mut s = State::default(); + s.aside.insert(alloc, vec![alloc, heavy, light, busy, foreign]); + for (raw, made, cycle) in [(alloc, false, 90), (heavy, true, 80), (light, true, 4), (busy, true, 80), (foreign, false, 80)] { + let b = backing_mut(&mut s, raw); + b.made = made; + b.cycle = cycle; + } + let limit = 16; + backing_mut(&mut s, light).peak = limit - 1; + let free: HashSet = [alloc, heavy, light, foreign].into_iter().collect(); + // (within the budget of heavy ones kept – heavy and busy – nothing goes) + assert!(retire_heavy_with(&mut s, alloc, &free, limit, 2).is_empty()); + let gone = retire_heavy_with(&mut s, alloc, &free, limit, 0); + assert_eq!(gone.iter().map(|(raw, _)| *raw).collect::>(), vec![heavy]); + assert_eq!(s.aside[&alloc], vec![alloc, light, busy, foreign]); + assert!(!s.backings.contains_key(&heavy) && s.backings.contains_key(&busy)); + // a heavy cycle seen at an earlier Reset counts too + backing_mut(&mut s, light).peak = limit; + let gone = retire_heavy_with(&mut s, alloc, &free, limit, 0); + assert_eq!(gone.iter().map(|(raw, _)| *raw).collect::>(), vec![light]); + // bundles keep no command buffers: nothing to release there + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_BUNDLE.0); + backing_mut(&mut s, busy).peak = limit; + assert!(retire_heavy_with(&mut s, alloc, &[busy].into_iter().collect(), limit, 0).is_empty()); + } + /// When a title list goes, the segments that recorded its put-off dispatches on its own /// allocator hold neither the PC allocator it stands for now nor the ones put aside: `forget` /// then releases those the GPU is done with (they were left behind, with what was held on them). @@ -2762,9 +2946,91 @@ mod tests { } } + /// A PC allocator made here that took a heavy cycle (counted per list Reset on it) is released + /// by the namespace's reclaim once the list has moved on and the GPU passed its submits. + /// (Compute lists: no other test shares their spares, `take_shared_aside`.) + #[test] + fn a_heavy_allocator_made_here_is_released_once_idle() { + unsafe { + if !retire_heavy() { + return; + } + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + TEST_HEAVY.with(|t| t.set(Some((3, 0)))); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE).unwrap(); + let a = alloc.as_raw(); + if !super::super::real::is_adopted(a) { + super::super::real::adopt(a, super::super::real::Kind::CommandAllocator); + } + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, None).unwrap(); + let l = list.as_raw() as usize; + created_on(l, a as usize, D3D12_COMMAND_LIST_TYPE_COMPUTE.0); + list.Close().unwrap(); + let lists = [Some(list.cast::().unwrap())]; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut value = 0; + let mut submit = || { + queue.ExecuteCommandLists(&lists); + executed(queue.as_raw(), &[l as *mut c_void]); + value += 1; + queue.Signal(&fence, value).unwrap(); + let start = std::time::Instant::now(); + while fence.GetCompletedValue() < value && start.elapsed().as_secs() < 10 { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(fence.GetCompletedValue() >= value, "the queue finishes"); + }; + let record = |times: usize| { + for _ in 0..times { + assert_eq!(reset_list(l, a as usize, D3D12_COMMAND_LIST_TYPE_COMPUTE.0, |pc| { + let pc_raw = pc as *mut c_void; + let pc_alloc = ID3D12CommandAllocator::from_raw_borrowed(&pc_raw).unwrap(); + list.Reset(pc_alloc, None).map_or_else(|e| e.code().0, |_| 0) + }), 0); + list.Close().unwrap(); + } + }; + submit(); + // the title's first Reset: a PC allocator made here takes the place of its own + alloc.Reset().unwrap(); + let heavy = current(a as usize); + assert_ne!(heavy, a as usize); + record(4); + assert_eq!(STATE.lock().unwrap().as_ref().unwrap().backings[&heavy].cycle, 4, "each list Reset counts"); + submit(); + // the list holds its recording there: the next Reset puts it aside + alloc.Reset().unwrap(); + let next = current(a as usize); + assert!(next != heavy && next != a as usize); + assert!(STATE.lock().unwrap().as_ref().unwrap().aside[&(a as usize)].contains(&heavy)); + // the list moves on and the GPU is done: the reclaim releases the heavy one + record(1); + submit(); + let before = HEAVY_RELEASED.load(Ordering::Relaxed); + reclaim_idle_aside(a); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert!(!s.backings.contains_key(&heavy), "released with its command buffers"); + assert!(!s.aside[&(a as usize)].contains(&heavy)); + } + assert!(HEAVY_RELEASED.load(Ordering::Relaxed) > before); + assert!(dev.GetDeviceRemovedReason().is_ok()); + TEST_HEAVY.with(|t| t.set(None)); + drop(lists); + drop(list); + drop(alloc); + assert_eq!(current(a as usize), a as usize, "a released allocator leaves nothing behind"); + } + } + /// A list recorded once and submitted again after the title reset its allocator: the - /// recording is still there (the device is not removed), the title's allocator goes on with - /// another PC allocator, and the first one is used again once the list has moved on. + /// recording is still there (the device is not removed), and the title's allocator goes on + /// with another PC allocator. Once the list has moved on, its own allocator is free again but + /// not recorded on (`retire_heavy`): a third PC allocator takes the place. #[test] fn a_recording_outlives_the_reset_of_the_titles_allocator() { unsafe { @@ -2817,17 +3083,29 @@ mod tests { executed(queue.as_raw(), &[l]); done(3); - // the next reset: the first PC allocator holds nothing now and is used again + // the next reset: the title's own allocator is free now, but it is not recorded on + // again (what vkd3d-proton keeps of a cycle there could not be given back) alloc.Reset().unwrap(); - assert_eq!(current(a as usize), a as usize, "the allocator put aside is free again"); + let third = current(a as usize); + if !retire_heavy() { + // (XCL_ALLOC_RETIRE=0: the title's own allocator is used again, as before) + assert_eq!(third, a as usize, "the allocator put aside is free again"); + drop(lists); + drop(list); + drop(alloc); + return; + } + assert!(third != a as usize && third != second, "a PC allocator made here takes the place"); assert!(dev.GetDeviceRemovedReason().is_ok()); // the title's allocator goes while another PC allocator stands for it: nothing of // it stays (the next allocator at its address is its own) + let third_alloc = ID3D12CommandAllocator::from_raw_borrowed(&(third as *mut c_void)).unwrap().clone(); assert_eq!(reset_list(l as usize, a as usize, D3D12_COMMAND_LIST_TYPE_DIRECT.0, |pc| { - assert_eq!(pc, a as usize); - list.Reset(&alloc, None).map_or_else(|e| e.code().0, |_| 0) + assert_eq!(pc, third); + list.Reset(&third_alloc, None).map_or_else(|e| e.code().0, |_| 0) }), 0); + drop(third_alloc); list.Close().unwrap(); alloc.Reset().unwrap(); assert_ne!(current(a as usize), a as usize); From 9f173d9dd1c1bc4fe760a189551012acd9119aca Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 11:59:59 +0100 Subject: [PATCH 173/175] D3D12.X: name the recorded work when the GPU wait watchdog fires A GPU queue wait that outlasts the watchdog stops the title, and on RADV the kernel's ring timeout and a full GPU reset follow, with no page fault to point at the work. Only the device-removed path printed the ring of recorded draws and dispatches, so these stops named no pipeline. Print it here too, before the stop (and with XCL_WAIT_TIMEOUT_CONTINUE=1). --- crates/xcl/src/hle/d3d12x/list_x.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 7af98d348b..abffaceefd 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3147,6 +3147,9 @@ fn wake_sync_watchdog() { if PRINTED.fetch_add(1, Ordering::Relaxed) < 3 { crate::xlog_warn!("D3D12.X: wait edges at that time-out: {}", edges_summary()); } + // the work the stuck queue may be running: without it a hang that the kernel + // later resets names no pipeline + super::watch::report("a GPU queue wait exceeded its watchdog"); if wait_timeout_continues() { crate::xlog_warn!("D3D12.X: XCL_WAIT_TIMEOUT_CONTINUE=1 – the timed-out GPU queue waits were released on the CPU and the title goes on"); } else { From b6aebe7de95ee62176de2fc2b6b86f70b5d0b8d0 Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 18:24:29 +0100 Subject: [PATCH 174/175] D3D12.X: keep amd-dev memory toggles off by default The amd-dev merge only reached stable 600 s runs when level pages, small textures, vram-small placements, zero-target-page fills and format aliasing were all turned off. Keep the merge head on main's opt-in defaults for these five switches so milestone-1 stability does not depend on per-user ENV edits. The feature code stays in place and can be re-enabled per run with =1 while the A/B and vendor coverage catches up. --- crates/xcl/src/hle/d3d12x/format_alias.rs | 4 ++-- crates/xcl/src/hle/d3d12x/small_tex.rs | 26 ++++++++++---------- crates/xcl/src/hle/d3d12x/vram.rs | 29 ++++++++++++----------- crates/xcl/src/hle/d3d12x/vram_small.rs | 4 ++-- 4 files changed, 31 insertions(+), 32 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs index 761f0c20d6..f10f472390 100644 --- a/crates/xcl/src/hle/d3d12x/format_alias.rs +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -15,7 +15,7 @@ //! on PC D3D12; texels of equal byte width must be transferred through an intermediate buffer //! (`CopyTextureRegion` across all mips and array/depth slices). //! -//! Set `XCL_FORMAT_ALIAS=0` to disable format-alias syncing. +//! Set `XCL_FORMAT_ALIAS=1` to enable format-alias syncing. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; @@ -548,7 +548,7 @@ static LIST_STATES: Mutex>> = Mutex::new(No pub fn enabled() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| !std::env::var("XCL_FORMAT_ALIAS").is_ok_and(|v| v.trim() == "0")) + *ON.get_or_init(|| std::env::var("XCL_FORMAT_ALIAS").is_ok_and(|v| v.trim() == "1")) } /// `XCL_FORMAT_ALIAS_DEDUP=0`: disable skipping redundant format-alias copies when the source diff --git a/crates/xcl/src/hle/d3d12x/small_tex.rs b/crates/xcl/src/hle/d3d12x/small_tex.rs index e183918471..5b195f55e0 100644 --- a/crates/xcl/src/hle/d3d12x/small_tex.rs +++ b/crates/xcl/src/hle/d3d12x/small_tex.rs @@ -1,6 +1,6 @@ //! Small sampled textures of the title that get no shared pages (`vram::place_pages` refuses them: //! a 1D texture cannot be a reserved resource) on 4 KiB placements in heaps of XCL's own -//! (on by default, `XCL_SMALL_TEXTURES=0` turns it off), instead of a committed resource each: a +//! (off by default, `XCL_SMALL_TEXTURES=1` turns it on), instead of a committed resource each: a //! committed resource takes at least 64 KiB of video memory, and a title's thousands of tiny //! lookup textures (a few hundred bytes each) took ~300 MiB that way. //! @@ -29,16 +29,15 @@ const UNIT: u64 = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64; const HEAP_BYTES: u64 = 4 << 20; const UNITS: usize = (HEAP_BYTES / UNIT) as usize; -/// Whether small sampled textures go on 4 KiB placements: on by default (`XCL_SMALL_TEXTURES=0` -/// turns it off), off in unit tests unless they ask for it. +/// Whether small sampled textures go on 4 KiB placements (`XCL_SMALL_TEXTURES=1`). pub(super) fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| switch_on(std::env::var("XCL_SMALL_TEXTURES").ok().as_deref(), !cfg!(test))) + *ON.get_or_init(|| switch_on(std::env::var("XCL_SMALL_TEXTURES").ok().as_deref())) } -/// `XCL_SMALL_TEXTURES` as set (`1`: on, anything else: off), `unset` when it is not. -fn switch_on(v: Option<&str>, unset: bool) -> bool { - v.map_or(unset, |v| v.trim() == "1") +/// `XCL_SMALL_TEXTURES` as set (`1`: on, anything else: off), including `unset`. +fn switch_on(v: Option<&str>) -> bool { + v.is_some_and(|v| v.trim() == "1") } /// The units of one heap: first fit of a run of `n`. @@ -191,14 +190,13 @@ mod tests { use super::*; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_SAMPLE_DESC}; - /// On by default (amd-dev's default), `XCL_SMALL_TEXTURES=0` (or anything but `1`) turns it off. + /// Off by default (`XCL_SMALL_TEXTURES=1` turns it on). #[test] - fn small_textures_are_on_unless_turned_off() { - assert!(switch_on(None, true), "unset outside unit tests: on"); - assert!(!switch_on(None, false), "unset in unit tests: off"); - assert!(switch_on(Some(" 1 "), false)); - assert!(!switch_on(Some("0"), true)); - assert!(!switch_on(Some("yes"), true)); + fn small_textures_are_off_by_default() { + assert!(!switch_on(None), "unset: off"); + assert!(switch_on(Some(" 1 "))); + assert!(!switch_on(Some("0"))); + assert!(!switch_on(Some("yes"))); } /// Units go first fit and come back: a freed run is taken again, a run longer than any gap is not. diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index f431944681..c2d6e054ee 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1440,7 +1440,7 @@ fn take_level_tiles(levels: Option<&mut Levels>) -> Vec<(Vec, Vec<(usize, .unwrap_or_default() } -/// Level pages (on by default, `XCL_TEXTURE_LEVEL_PAGES=0` turns them off): a sampled 2D texture +/// Level pages (off by default, `XCL_TEXTURE_LEVEL_PAGES=1` turns them on): a sampled 2D texture /// of one slice on the shared pages gets the pages of a level when an upload first has texels for /// it. A retail game places its streamed textures at full size and maps memory under their levels /// as it loads them, the small ones first; with a page for every 64 KiB a texture covers most of @@ -1455,17 +1455,17 @@ pub(super) fn level_pages() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| { let on = level_pages_on(std::env::var("XCL_TEXTURE_LEVEL_PAGES").ok().as_deref()); - if !on { - crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=0 - a sampled texture gets video memory pages for all of its levels at once"); + if on { + crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=1 - a sampled texture's levels get their video memory pages when an upload first has texels for them"); } on }) } } -/// `XCL_TEXTURE_LEVEL_PAGES` as set: on unless it is `0`. +/// `XCL_TEXTURE_LEVEL_PAGES` as set: on only when it is `1`. fn level_pages_on(v: Option<&str>) -> bool { - v.is_none_or(|v| v.trim() != "0") + v.is_some_and(|v| v.trim() == "1") } /// `level_pages` for a test (under `VRAM_TEST_LOCK`) @@ -2004,10 +2004,10 @@ fn coalesce_tile_runs(tiles: &mut Vec) -> Vec<(u32, u32, u32)> { /// Zero recycled page-pool tiles on the mapping queue before handing them to newly mapped /// textures so stale render-target/depth/UAV bytes never bleed into new targets (`#505`/`#1833`). -/// Enabled by default (`XCL_ZERO_TARGET_PAGES=0` disables). +/// Disabled by default (`XCL_ZERO_TARGET_PAGES=1` enables). fn zero_target_pages() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").map_or(true, |v| v.trim() != "0")) + *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").is_ok_and(|v| v.trim() == "1")) } /// Allocate one 64 MiB default heap for `Pages`. @@ -5204,11 +5204,11 @@ mod tests { assert_eq!(recycled, vec![(0, 3)], "the rolled-back recycled tile still needs zeroing"); } - /// Level pages are on unless `XCL_TEXTURE_LEVEL_PAGES=0`, and a sampled view over a live page - /// (a render target's) maps all of its levels at once: its texels come from the GPU. + /// Level pages are off unless `XCL_TEXTURE_LEVEL_PAGES=1`, and a sampled view over a live + /// page (a render target's) maps all of its levels at once: its texels come from the GPU. #[test] - fn level_pages_are_on_by_default_but_not_for_a_view_over_a_live_page() { - assert!(level_pages_on(None), "unset: on"); + fn level_pages_are_off_by_default_but_not_for_a_view_over_a_live_page() { + assert!(!level_pages_on(None), "unset: off"); assert!(level_pages_on(Some("1"))); assert!(!level_pages_on(Some(" 0 ")), "0: off"); let desc = D3D12_RESOURCE_DESC { @@ -5237,9 +5237,10 @@ mod tests { assert!(coalesce_tile_runs(&mut empty).is_empty()); } - /// A pool tile given back holds what its last texture had; the next texture mapped onto it - /// gets it zeroed on the mapping queue first (`XCL_ZERO_TARGET_PAGES`, on by default), so a - /// queue that waits for the mappings reads zeros there, not the old texture's bytes. + /// A pool tile given back holds what its last texture had; when zero-fill is enabled + /// (`XCL_ZERO_TARGET_PAGES=1`), the next texture mapped onto it gets it zeroed on the mapping + /// queue first, so a queue that waits for the mappings reads zeros there, not the old + /// texture's bytes. #[test] fn a_recycled_page_is_zeroed_before_a_new_texture_uses_it() { unsafe { diff --git a/crates/xcl/src/hle/d3d12x/vram_small.rs b/crates/xcl/src/hle/d3d12x/vram_small.rs index 807eed4c21..b99c1cf9bb 100644 --- a/crates/xcl/src/hle/d3d12x/vram_small.rs +++ b/crates/xcl/src/hle/d3d12x/vram_small.rs @@ -11,7 +11,7 @@ //! shared 16 MiB default heaps packs up to 4 096 textures into one heap with zero tile mappings, //! shares the exact `(heap, offset)` across repeated placements at the same `(va, size)` so //! same-address aliases see each other's uploads, and recycles released blocks by size class -//! after `IDLE` + `COOL`. `XCL_VRAM_SMALL=0` disables this path. +//! after `IDLE` + `COOL`. `XCL_VRAM_SMALL=1` enables this path. use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; @@ -238,7 +238,7 @@ static SMALL_POOLS: Mutex>> = M fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_VRAM_SMALL").map_or(true, |v| v.trim() != "0")) + *ON.get_or_init(|| std::env::var("XCL_VRAM_SMALL").is_ok_and(|v| v.trim() == "1")) } /// Whether `desc` and `console_bytes` are eligible for 4 KiB small-resource sub-allocation. From 1bb61081f5a73c2732134c8e04af0f453b24791a Mon Sep 17 00:00:00 2001 From: lucsoft Date: Tue, 1 Dec 2026 18:55:07 +0100 Subject: [PATCH 175/175] D3D12.X: let vram tests force zero-target-page fills The merge keeps XCL_ZERO_TARGET_PAGES off by default to match main, but `a_recycled_page_is_zeroed_before_a_new_texture_uses_it` validates the zero-fill path itself. Add a test-only AtomicBool override for `zero_target_pages()` and use a restore guard in that test so it can enable the path without depending on process env or leaking state to other tests. --- crates/xcl/src/hle/d3d12x/vram.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index c2d6e054ee..8b623946f0 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2006,10 +2006,19 @@ fn coalesce_tile_runs(tiles: &mut Vec) -> Vec<(u32, u32, u32)> { /// textures so stale render-target/depth/UAV bytes never bleed into new targets (`#505`/`#1833`). /// Disabled by default (`XCL_ZERO_TARGET_PAGES=1` enables). fn zero_target_pages() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").is_ok_and(|v| v.trim() == "1")) + #[cfg(test)] + return ZERO_TARGET_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed); + #[cfg(not(test))] + { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").is_ok_and(|v| v.trim() == "1")) + } } +/// `zero_target_pages` for a test (under `VRAM_TEST_LOCK`). +#[cfg(test)] +pub(super) static ZERO_TARGET_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + /// Allocate one 64 MiB default heap for `Pages`. unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { let desc = D3D12_HEAP_DESC { @@ -5244,6 +5253,14 @@ mod tests { #[test] fn a_recycled_page_is_zeroed_before_a_new_texture_uses_it() { unsafe { + struct RestoreBool<'a>(&'a std::sync::atomic::AtomicBool, bool); + impl Drop for RestoreBool<'_> { + fn drop(&mut self) { + self.0.store(self.1, std::sync::atomic::Ordering::Relaxed); + } + } + let was_zero = ZERO_TARGET_PAGES_FOR_TEST.swap(true, std::sync::atomic::Ordering::Relaxed); + let _restore_zero = RestoreBool(&ZERO_TARGET_PAGES_FOR_TEST, was_zero); let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { return crate::gpu::recomp::runner::skip_test("no GPU"); };